2012-08-07 145 views
11

这里是剧情图例汇总统计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. 

任何指针获得所需的结果将不胜感激。由于

+3

1:然后,颜色值在比例使用每个的geom的aes()功能图谱。标题还可以包含“自定义”一词。我会想象自己在寻找一个“ggplot中的自定义传说”。 – 2012-08-07 08:09:47

回答

17

使用手动标尺,即您的情况scale_colour_manual。为很好的问题,可再现例如,可视化和充分描述的期望的输出

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

+0

比我的方法更简单! – mnel 2012-08-07 04:58:49

7

您可以组合的平均变量和数据在同一个data.frame和颜色/尺寸柱这是一个因素,无论是datamean

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) 

enter image description here

或者你可以不组合,但包括在两个数据集中的列

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) 

这给出了相同的结果

+0

+1比我的方法更灵活;-) – Andrie 2012-08-07 04:59:21