在ggplot中添加两个图例

Add two legends in ggplot

x <- c(1:3)
y1 <- c(2/28,13/35,43/65)
y2 <- c(1/2, 2/13, 5/43)
df <- data.frame(x, y1, y2)

x <- c(rep(1 , 5) , rep(2 , 5) , rep(3 , 5))
condition <- rep(c("1", "2", "3", "4", "5") , 3)
y3 <- c(1,  0,  0,  0,  0, 6,  4,  1,  0,  0, 12, 13,  5,  5,  3)
df2 <- data.frame(x, y3, condition)

cols <- c("1"="grey80","2"="grey70","3"="grey60","4"="grey50","5"="grey40")
ggplot() + 
  geom_bar(aes(fill=df2$condition, y=df2$y3, x=df2$x), position="stack", stat="identity", width = 0.5) +
  geom_line(mapping = aes(x = df$x, y = df$y1*50),linetype=1, size = 1, color = "black") + 
  geom_point(mapping = aes(x = df$x, y = df$y1*50), size = 2, color = "black") +
  geom_text(aes(x=df$x, y=df$y1*50, label = round(df$y1, 3)),vjust = "outward", hjust = "outward",show.legend = FALSE, color="black") +
  geom_line(mapping = aes(x = df$x, y = df$y2*50), linetype=2, size = 1, color = "black") +
  geom_point(mapping = aes(x = df$x, y = df$y2*50), size = 2, color = "black") +
  geom_text(aes(x=df$x, y=df$y2*50, label = round(df$y2, 3)),vjust = "outward", hjust = "outward",show.legend = FALSE, color="black") +
  scale_y_continuous(name = "Number of cases", sec.axis = sec_axis(~./50, name = "Percentage")) +
  scale_x_continuous(breaks = 1:3, labels=c("2008-2011","2012-2015","2016-2019")) + xlab(NULL) +
  scale_fill_manual(name = "Resection Index",values = cols) +
  theme_minimal()

我添加了颜色图例(切除指数)。但我不知道如何为两条线(实线和虚线)再添加一个图例。请问如何给线型多加一个图例?

基本上与 fill 相同。作为一般规则:如果你想要一个图例,那么你必须在美学上进行映射,即将 linetype = ... 移动到 aes() 内,然后通过例如设置你想要的排版scale_linetype_manual.

注意:不建议在 ggplot2 中使用 df$...。而是通过 data 参数传递您的数据,并简单地将变量名称映射到美学上。这也适用于多个数据帧:

cols <- c("1" = "grey80", "2" = "grey70", "3" = "grey60", "4" = "grey50", "5" = "grey40")
ltys <- c("1" = 1, "2" = 2)

library(ggplot2)

ggplot(data = df) +
  geom_bar(data = df2, aes(fill = condition, y = y3, x = x), position = "stack", stat = "identity", width = 0.5) +
  geom_line(mapping = aes(x = x, y = y1 * 50, linetype = "1"), size = 1, color = "black") +
  geom_point(mapping = aes(x = x, y = y1 * 50), size = 2, color = "black") +
  geom_text(aes(x = x, y = y1 * 50, label = round(y1, 3)), vjust = "outward", hjust = "outward", show.legend = FALSE, color = "black") +
  geom_line(mapping = aes(x = x, y = y2 * 50, linetype = "2"), size = 1, color = "black") +
  geom_point(mapping = aes(x = x, y = y2 * 50), size = 2, color = "black") +
  geom_text(aes(x = x, y = y2 * 50, label = round(y2, 3)), vjust = "outward", hjust = "outward", show.legend = FALSE, color = "black") +
  scale_y_continuous(name = "Number of cases", sec.axis = sec_axis(~ . / 50, name = "Percentage")) +
  scale_x_continuous(breaks = 1:3, labels = c("2008-2011", "2012-2015", "2016-2019")) +
  xlab(NULL) +
  scale_fill_manual(name = "Resection Index", values = cols) +
  scale_linetype_manual(name = "NAME", values = ltys) +
  theme_minimal()