joining all points inside a grouped point plot usi

2019-07-29 13:39发布

问题:

I have data frame like this

AA=
States   Clusters ncomp
HR  Cluster-1     9
HR  Cluster-2     4
HR  Cluster-3     9
WB  Cluster-1    13
WB  Cluster-2    13
WB  Cluster-3    13
WB  Cluster-4    13
TL  Cluster-1     9
TL  Cluster-2    11
TL  Cluster-3     9
TL  Cluster-4    10
TL  Cluster-5    11
TL  Cluster-6     7
OR  Cluster-1    15
OR  Cluster-2    15
OR  Cluster-3    15
OR  Cluster-4    14
OR  Cluster-5    15
OR  Cluster-6    15

Need to plot which looks as. I don't want to use facet_wrap. I can create grouped point plot

回答1:

You can try a hidden facet_grid and one tidyverse line to separate the Cluster column. This can be done also by ave like

d$C2 <- ave(as.numeric(d$Clusters),  d$States, FUN = function(x) seq(1,length(x))) 

library(tidyverse)
d %>% 
  separate(Clusters, into=c("C1", "C2"), sep="-") %>% 
  ggplot(aes(as.numeric(C2), ncomp, color=States)) + 
   geom_vline(data = .  %>%   count(States) %>% 
                mutate(x=n/2+0.5),
              aes(xintercept=x),
              color="white")+
   geom_point() + 
   geom_line(aes(group=1)) + 
   facet_grid(~States, switch = "x",scales = "free_x", space = "free_x") + 
   scale_x_continuous(breaks = NULL, minor_breaks = NULL, expand = c(0.2,0.5))+
   xlab("States") + 
   theme(axis.text.x = element_blank(),
         axis.ticks = element_blank(),
         strip.background = element_blank(),
         panel.spacing.x= unit(0, "mm")) 

Another approach is using an interaction term like this:

d %>% 
  # calculate a numeric interaction between clusters and States 
  mutate(x=as.numeric(interaction(Clusters,States))) %>%
   # calculate breaks 
   group_by(States) %>%
   mutate(xbreaks=mean(x)) %>% 
  {ggplot(.,aes(x, ncomp, color=States)) + 
    geom_point() +
    geom_line() +
    scale_x_continuous(breaks = unique(.$xbreaks), labels = unique(.$States),minor_breaks = NULL)}

The fancy {} must be done to pipe break and label values.



标签: r ggplot2