在R中的条形图+线ggplot图表中添加图例

时间:2020-02-07 19:07:58

标签: r ggplot2 legend

我有一个变量A(条形图)和变量B(线)的图,其中图例未显示。我想请教几个问题:

  • 传奇未显示。
  • 位置(x轴)仅显示7个中的3个

    我的数据:

Location <- c(1,2,3,4,5,6,7)
A <- c(0.81, 0.94, 2.31, 12.2, 11.52, 4.7, 10.13)
B <- c(3304, 97025, 187012, 25962, 383875, 96233, 227291)

df = data.frame(Location, A, B)

我的代码:

ggplot(df) + 
    geom_col(aes(Location, A), color = "black", fill = "tan1") +
    geom_line(aes(Location, B/40000), size = 1.5, color="black") +
    scale_y_continuous(sec.axis = sec_axis(~.*40000))

尝试添加图例:

+ theme(legend.position = c(0.8, 0.2))+
        scale_fill_manual(name = "", values = c("A" = "grey")) +
        scale_color_manual(name = "", values = c("B" = "black")) +

        theme_bw()

enter image description here

1 个答案:

答案 0 :(得分:3)

我相信您想确保自己的color中有aes来创建图例。

还添加了guides,以删除图例中黑线的填充。

如果您要搜索的是,可以将breaks添加到scale_x_continuous以显示所有x轴标签。

ggplot(df) + 
  geom_col(aes(Location, A, color = "A"), fill = "tan1") +
  geom_line(aes(Location, B/40000, color = "B"), size = 1.5) +
  scale_y_continuous(sec.axis = sec_axis(~.*40000)) + 
  scale_x_continuous(breaks = 1:7) +
  #theme(legend.position = c(0.8, 0.2))+
  #scale_fill_manual(name = "", values = c("A" = "grey")) +
  scale_color_manual(name = "", values = c("A" = "tan1", "B" = "black")) +
  theme_bw() +
  guides(color=guide_legend(override.aes=list(fill=c("tan1", NA))))

plot with legend