根据颜色向 GGPlot Lollipop 图表添加图例

时间:2021-06-07 20:56:52

标签: r ggplot2

我使用以下代码创建了一个棒棒糖图表。我试图在图表中添加一个图例,将橙色详细说明为“2020”,将紫色详细说明为“平均”。我该怎么做?

ggplot(LGA_top3) +
  geom_segment(aes(x = LGA, xend = LGA, y = 2020, yend = Average)) +
  geom_point(aes(x = LGA, y = 2020), color="orange", size=3) +
  geom_point(aes(x = LGA, y = Average), color="purple", size=3) +
  coord_flip() +
  theme(legend.position="right") +
  facet_wrap(~`Offence Category`, ncol=1, scale="free_y") +
  labs(x = "Local Government Area (LGA)", y = "Total")

enter image description here

1 个答案:

答案 0 :(得分:1)

我会推荐这样的东西。如果您提供可重现的示例,则更容易,因为您当前的代码无法为您提供更准确的答案。请使用 dput(your_data) 并将结果粘贴到此处。

ggplot(LGA_top3) +
  geom_segment(aes(x = LGA, xend = LGA, y = 2020, yend = Average)) +
  geom_point(aes(x = LGA, y = 2020, color = "2020"), size=3) +
  geom_point(aes(x = LGA, y = Average, color = 'Average'), size=3) +
  coord_flip() +
  scale_color_manual(values = c('orange', 'purple')) +
  theme(legend.position="right") +
  facet_wrap(~`Offence Category`, ncol=1, scale="free_y") +
  labs(x = "Local Government Area (LGA)", y = "Total")