r - 如何在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 添加一个图例,描述图中颜色所代表的含义。我已经在网上搜索过,但找不到这个特定问题的答案,有人可以在这里帮助我吗?
谢谢!
解决方案
您应该以长格式获取数据,然后绘制而不是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')
推荐阅读
- python-3.x - 有没有办法在比较整数输入时比较 IF 语句中的字符串?
- python - python代码无法从tensorflow解析gFile
- c# - 一次从文件中读取内容...静态还是单例?
- algorithm - 图像处理算法的标准
- javascript - Lodash 克隆数组与扩展运算符
- file-upload - 使用 FtpWebRequest 上传文件后图像损坏
- r - 变量可以在函数中声明为全局吗?
- c - 使用 POSIX 系统函数在 C 中实现 rev 命令
- android - NotificationListenerService 不包括 EXTRA_PEOPLE_LIST
- javascript - 验证 es 模块是否可摇树