【问题标题】:Overlay Each Bar of Stacked ggplot2 Barchart with Line用线条覆盖堆叠 ggplot2 条形图的每个条形图
【发布时间】:2019-05-29 09:34:49
【问题描述】:

我有一个堆叠的 ggplot2 条形图,如下所示:

# Example data
data <- data.frame(level = rep(1:3, 3),
                   values = c(20, 30, 25, 15, 10, 5, 18, 20, 30),
                   group = as.factor(rep(LETTERS[1:3], each = 3)))

# Draw plot without lines
library("ggplot2")
my_plot <- ggplot(data, aes(x = level, y = values, fill = group)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(breaks = c("A", "B", "C"),
                    values = c("forestgreen", "darkgoldenrod1", "brown2"))
my_plot

现在,我想用特定高度的蓝线覆盖此条形图的每个条形。蓝线也应该出现在情节的图例中。

这些行的数据如下所示:

# Data for lines
data_line <- data.frame(level = 1:3,
                        values = c(25, 40, 10),
                        group = as.factor("D"))

输出应如下所示(用油漆绘制的图像):

问题:如何将这些数据添加为覆盖线?

【问题讨论】:

    标签: r ggplot2 graphics bar-chart overlay


    【解决方案1】:

    一个使用geom_segment的选项

    my_plot + 
      geom_segment(data = data_line, 
                   aes(x = level - 0.45,
                       xend = level + 0.45,
                       y = values,
                       yend = values, 
                       col = "D"), # 'fake' a legend
                   size = 2,
                   inherit.aes = FALSE) +
      scale_color_manual(name = NULL,
                         values = c(D = "#007fff")) + 
      guides(fill = guide_legend(order = 1),
             color = guide_legend(order = 2)) +
      theme(legend.margin = margin(t = -1, b = -15)) # trial and error
    

    【讨论】:

    • 非常感谢您的回复!是否可以将两个图例“合并”为一个图例,顺序为 A、B、C、D?
    • 非常感谢您的更新,现在正是我想要的!