首页 > 解决方案 > 如何在R中的多个图中添加图例

问题描述

我有这个代码:

testPlot= ggplot(residFrame) +
  geom_point(aes(x=STATEFP, y=total_diff, colour='total'), colour='red', shape=1) +
  geom_point(aes(x=STATEFP, y=desalination_diff, colour='desalination'), colour='blue', shape=1) + 
  geom_point(aes(x=STATEFP, y=surfacewater_diff), colour='green', shape=1) +
  geom_point(aes(x=STATEFP, y=groundwater_diff), colour='yellow', shape=1) +
  xlab('STATEFP') + ylab('Difference') + ggtitle('Difference for all states', subtitle='For each source')
testPlot

现在我想向 testPlot 添加一个图例,描述图中颜色所代表的含义。我已经在网上搜索过,但找不到这个特定问题的答案,有人可以在这里帮助我吗?

谢谢!

标签: rggplot2legend

解决方案


您应该以长格式获取数据,然后绘制而不是geom_point多次调用。您尚未提供数据示例,但您可以尝试。

library(ggplot2)

residFrame %>%
  tidyr::pivot_longer(cols = ends_with('diff')) %>%
  ggplot() + aes(STATEFP, value, color = name) + 
  geom_point(shape = 1) + 
  xlab('STATEFP') + ylab('Difference') + 
  ggtitle('Difference for all states', subtitle='For each source')

推荐阅读