这是情节的代码
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)
Run Code Online (Sandbox Code Playgroud)

我希望有一个关于这个图的图例,它将识别数据值和平均值
Black point = Data
Red point = Mean.
Run Code Online (Sandbox Code Playgroud)
任何获得所需结果的指针都将受到高度赞赏.谢谢
And*_*rie 17
使用手动刻度,即在您的情况下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"))
Run Code Online (Sandbox Code Playgroud)

您可以将平均变量和数据组合在同一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)
Run Code Online (Sandbox Code Playgroud)

或者您无法合并,但在两个数据集中都包含该列
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)
Run Code Online (Sandbox Code Playgroud)
这给出了相同的结果