r - ggplot2 中汇总统计的图例

标签 r ggplot2

这是情节的代码

library(ggplot2)
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)), y = rnorm(30))
library(plyr)
ds <- ddply(df, .(gp), summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(x = gp, y = y)) +
   geom_point() +
   geom_point(data = ds, aes(y = mean), colour = 'red', size = 3)
enter image description here
我想要这个图的图例,它将识别数据值和平均值这样的事情
Black point = Data
Red point   = Mean.
我怎样才能做到这一点?

最佳答案

使用手动秤,即在您的情况下 scale_colour_manual .然后使用 aes() 将颜色映射到比例尺中的值每个geom的功能:

ggplot(df, aes(x = gp, y = y)) +
  geom_point(aes(colour="data")) +
  geom_point(data = ds, aes(y = mean, colour = "mean"), size = 3) +
  scale_colour_manual("Legend", values=c("mean"="red", "data"="black"))

enter image description here

关于r - ggplot2 中汇总统计的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11839360/

相关文章:

r - 用均值向量调用rnorm

r - 在 rstan 中指定矩阵的先验分布

r - 如何在 R 中进行哈希调用

r - 使用 ggraph/ggplot2 在网络图中定位节点和边

r - ggplot 图例中缺少彩条,Windows 远程桌面

r - ggplot2 scale_x_datetime 造成烦恼

R 如何将不同长度的数字向量转换为固定长度的二进制向量

r - 如何根据行模式对数据进行子集化?

r - 如何使用 sf 更改国家之间共享边界的颜色?

r - 如何将表格添加到ggplot?