且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将堆栈和闪避与ggplot2中的条形图合并

更新时间:2023-11-26 13:31:58

在我看来,这里的线图更加直观:

It seems to me that a line plot is more intuitive here:

 library(forcats)

 data %>% 
   filter(!is.na(`Mean % of auxotrophs`)) %>%
   ggplot(aes(x = Timepoint, y = `Mean % of auxotrophs`, 
              color = fct_relevel(Mutator, c("o","m","n")), linetype=`Ancestral genotype`)) +
   geom_line() +
   geom_point(size=4) + 
   labs(linetype="Ancestral\ngenotype", colour="Mutator")

要回应您的评论:这是一种通过Ancestral genotype分别堆叠然后躲避每对的简单方法.我们分别为mutS-mutS+绘制堆叠的条形图,并通过在相反方向上少量移动Timepoint来手动避开条形图.将小节width设置为偏移量的两倍将导致成对的小节相互接触.我添加了少量的额外移位(5.5而不是5),以便在每对中的两个小节之间创建少量的空间.

To respond to your comment: Here's a hacky way to stack separately by Ancestral genotype and then dodge each pair. We plot stacked bars separately for mutS- and mutS+, and dodge the bars manually by shifting Timepoint a small amount in opposite directions. Setting the bar width equal twice the shift amount will result in pairs of bars that touch each other. I've added a small amount of extra shift (5.5 instead of 5) to create a tiny amount of space between the two bars in each pair.

 ggplot() +
   geom_col(data=data %>% filter(`Ancestral genotype`=="mutS+"),
            aes(x = Timepoint + 5.5, y = `Mean % of auxotrophs`, fill=Mutator),
            width=10, colour="grey40", size=0.4) + 
   geom_col(data=data %>% filter(`Ancestral genotype`=="mutS-"),
            aes(x = Timepoint - 5.5, y = `Mean % of auxotrophs`, fill=Mutator), 
            width=10, colour="grey40", size=0.4) + 
   scale_fill_discrete(drop=FALSE) +
   scale_y_continuous(limits=c(0,26), expand=c(0,0)) +
   labs(x="Timepoint")

注意:在以上两个示例中,我都将Timepoint保留为数字变量(即,我跳过了将其转换为字符的步骤),以确保x轴及时标定.单位,而不是将其转换为分类轴. 3D图是可憎的,这不仅是由于3D透视图导致的失真,而且还因为它会产生错误的外观,即每次测量都以相同的时间间隔分开.

Note: In both of the examples above, I've kept Timepoint as a numeric variable (i.e., I skipped the step where you converted it to character) in order to ensure that the x-axis is denominated in time units, rather than converting it to a categorical axis. The 3D plot is an abomination, not only because of distortion due to the 3D perspective, but also because it creates a false appearance that each measurement is separated by the same time interval.