11

这是情节的代码

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)

在此处输入图像描述

我想要这个图的图例,它将识别数据值和平均值,就像这样

Black point = Data
Red point   = Mean.

我怎样才能做到这一点?

4

2 回答 2

17

使用手动比例,即在您的情况下scale_colour_manualaes()然后使用每个 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"))

在此处输入图像描述

于 2012-08-07T04:53:32.830 回答
7

您可以将平均变量和数据组合在同一个 data.frame 和 color /size by column 这是一个因素,data或者mean

library(reshape2)

# in long format
dsl <- melt(ds, value.name = 'y')
# add variable column to df data.frame
df[['variable']] <- 'data'
# combine
all_data <- rbind(df,dsl)

# drop  sd rows

data_w_mean <- subset(all_data,variable != 'sd',drop = T)

# create vectors for use with scale_..._manual
colour_scales <- setNames(c('black','red'),c('data','mean'))
size_scales <- setNames(c(1,3),c('data','mean') )

ggplot(data_w_mean, aes(x = gp, y = y)) +
  geom_point(aes(colour = variable, size = variable)) +
  scale_colour_manual(name = 'Type', values = colour_scales) +
  scale_size_manual(name = 'Type', values = size_scales)

在此处输入图像描述

或者您不能合并,但在两个数据集中都包含该列

dsl_mean <- subset(dsl,variable != 'sd',drop = T)  
ggplot(df, aes(x = gp, y = y, colour = variable, size = variable)) +
  geom_point() +
  geom_point(data = dsl_mean) +
  scale_colour_manual(name = 'Type', values = colour_scales) +
  scale_size_manual(name = 'Type', values = size_scales)

给出相同的结果

于 2012-08-07T04:53:20.013 回答