簡體   English   中英

使用Line疊加堆疊的ggplot2條形圖的每個條形圖

[英]Overlay Each Bar of Stacked ggplot2 Barchart with Line

我有一個堆疊的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"))

輸出應如下所示(在繪制中繪制的圖像):

在此輸入圖像描述

問題:如何將這些數據添加為重疊線?

使用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

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM