将进化线添加到堆叠的条形图中

时间:2019-04-02 13:14:15

标签: r ggplot2 ggpubr

我想在堆积的条形图上添加线条,以便逐组展示演进。目前,我找到了ggpubr软件包的替代解决方案。

任何帮助将不胜感激!谢谢!

# My dataset     
dff
#    day composition median
# 1   JO           a  12.21
# 2   JO           b   0.79
# 3   JO           c  42.06
# 4   JO           d  30.65
# 5   JO           e   0.00
# 6  J28           a   1.28
# 7  J28           b   0.38
# 8  J28           c  85.13
# 9  J28           d   7.90
# 10 J28           e   0.00

# Stacked barplot
library(ggplot2)
ggplot(data = dff) +   
  geom_col(aes(x = day, y = median, fill = composition)) + 
  ylim(0,100)

enter image description here

# Median linked by lines
library(ggpubr)
ggpaired(data = dff,x = "day", y = "median", color = "composition",
 line.color = "gray", line.size = 0.4, xlab = FALSE, ylab = "Median")

enter image description here

所需的解决方案(或类似的东西)

enter image description here

1 个答案:

答案 0 :(得分:3)

您可以尝试以下方法:

w = 0.9 # this is the width of geom_col; in case you want something other than the default width

ggplot(data = dff,
       aes(x = day, y = median, fill = composition)) +   
  geom_col(width = w) +
  geom_line(aes(x = ifelse(as.integer(day) == 1, 
                           as.integer(day) + w/2,
                           as.integer(day) - w/2)),
            position = "stack")

plot

数据:

dff <- read.table(text = "    day composition median
1   JO           a  12.21
2   JO           b   0.79
3   JO           c  42.06
4   JO           d  30.65
5   JO           e   0.00
6  J28           a   1.28
7  J28           b   0.38
8  J28           c  85.13
9  J28           d   7.90
10 J28           e   0.00")