如何在stat_summary()中更改颜色

时间:2016-08-12 19:00:42

标签: ggplot2

我试图绘制两列原始数据(我已经使用熔化将它们组合成一个数据框),然后为每个数据框添加单独的误差条。但是,我想为每列生成一对颜色的原始数据,而错误栏则是另一组颜色,但我似乎无法让它工作。我得到的情节在下面的链接。我希望为原始数据和误差条设置不同的颜色对。为了便于说明,下面编码了一个简单的可重复示例。

 dat2.m<-data.frame(obs=c(2,4,6,8,12,16,2,4,6),variable=c("raw","raw","raw","ip","raw","ip","raw","ip","ip"),value=runif(9,0,10))

    c <- ggplot(dat2.m, aes(x=obs, y=value, color=variable,fill=variable,size = 0.02)) +geom_jitter(size=1.25) + scale_colour_manual(values = c("blue","Red"))

   c<- c+stat_summary(fun.data="median_hilow",fun.args=(conf.int=0.95),aes(color=variable), position="dodge",geom="errorbar", size=0.5,lty=1)

    print(c)

[1]: http://i.stack.imgur.com/A5KHk.jpg

2 个答案:

答案 0 :(得分:0)

解决此问题的一种方法是使用对geom_pointstat_summary的重复调用。使用这些函数的data参数将数据集的子集提供给每个调用,并将颜色属性设置在aes()之外。它是重复性的,有点挫败了ggplot的紧凑性,但它确实如此。

c <- ggplot(dat2.m, aes(x = obs, y = value, size = 0.02)) +
    geom_jitter(data = subset(dat2.m, variable == 'raw'), color = 'blue', size=1.25) + 
    geom_jitter(data = subset(dat2.m, variable == 'ip'), color = 'red', size=1.25) +
    stat_summary(data = subset(dat2.m, variable == 'raw'), fun.data="median_hilow", fun.args=(conf.int=0.95), color = 'pink', position="dodge",geom="errorbar", size=0.5,lty=1) +
    stat_summary(data = subset(dat2.m, variable == 'ip'), fun.data="median_hilow", fun.args=(conf.int=0.95), color = 'green', position="dodge",geom="errorbar", size=0.5,lty=1)

print(c)

enter image description here

答案 1 :(得分:0)

记录:我认为这是一个非常非常糟糕的主意。除非你有一个关键的用例,否则我认为你应该重新审视你的计划。

但是,您可以通过添加一组新变量来解决这个问题,最后用空格填充。你会想要/需要玩传说,但这应该有效(虽然它绝对是丑陋的):

dat2.m<-    data.frame(obs=c(2,4,6,8,12,16,2,4,6),variable=c("raw","raw","raw","ip","raw","ip","raw","ip","ip"),value=runif(9,0,10))


c <- ggplot(dat2.m, aes(x=obs, y=value, color=variable,fill=variable,size = 0.02)) +geom_jitter(size=1.25) + scale_colour_manual(values = c("blue","Red","green","purple"))

c<- c+stat_summary(fun.data="median_hilow",fun.args=(conf.int=0.95),aes(color=paste(variable," ")), position="dodge",geom="errorbar", size=0.5,lty=1)

print(c)
相关问题