根据分组ggplot2的条形着色和阴影/纹理

时间:2014-06-26 16:43:14

标签: r ggplot2

我正在尝试制作一个条形图,就像下面的示例数据和脚本一样,在给予治疗之前和之后,从4个人中进行测量。抱歉,我没有足够的声誉来上传示例图片。

我想用某种颜色绘制个体(例如Tom为绿色,Fred红色等)但是对于代表治疗的条形图,我想在颜色的顶部添加对角线以表示治疗。< / p>

这可能很容易吗?我改编自下面的代码:Generate ggplot2 boxplot with different colours for multiple groups

非常感谢任何建议。我希望我想做的事情有道理。

示例数据(抱歉,不知道如何上传以便从.csv导入):

Name,Time,Dose,Variable,n,Mean,SD,Median,Upper.SEM,Lower.SEM
Ted,1,0,P,3,20.1341,1.049791,20,0.5728394,0.5569923
Fred,1,0,P,3,38.63702,1.042969,37.74,0.9499892,0.9271918
Tom,6,0,P,3,42.3231,1.073583,43.75,1.7710033,1.6998725
Peter,6,0,P,3,36.01035,1.208213,35.63,4.1551262,3.7252776
Ted,1,1,P,3,22.79528,1.110182,21.64,1.4179833,1.334943
Fred,1,1,P,3,24.25966,1.156925,23.82,2.1300073,1.9580866
Tom,6,1,P,3,13.78995,1.170568,13.15,1.3126463,1.1985573
Peter,6,1,P,3,23.3236,1.4403,20.65,5.4688355,4.4300848

我一直在使用的代码:

g<- ggplot(example, aes(x=Name, y=Mean,fill=interaction(Name,Dose) ))
g<-g + geom_bar(stat="identity", position="dodge") 
g<-g + geom_errorbar(aes(ymax=Mean+Upper.SEM, ymin=Mean-Lower.SEM),       position=position_dodge(0.9), width=0.5)
g<- g+ scale_fill_manual(values=c("green","green","red","red","green","green","red","red"
                    ))
g

1 个答案:

答案 0 :(得分:2)

您似乎想要使用纹理,正如@Henrik评论中的链接所解释的那样,ggplot中无法实现。一种可能的解决方法是为名称使用不同的颜色,并为剂量使用不同的颜色。

library(ggplot2)
library(RColorBrewer)
categories         <- aggregate(Dose~Name,example,function(x)length(unique(x)))  # number of sub-category for each category
category.palettes  <- c("Purples","Reds","Greens","Blues")
colors <- unlist(lapply(1:nrow(categories),
                        function(i){colorRampPalette(brewer.pal(9,category.palettes[i])[3:7])(categories[i,2])}))
names <- sort(unique(example$Name))

g <- ggplot(example, aes(x=Name, y=Mean,fill=interaction(Dose,Name) ))
g <- g + geom_bar(stat="identity", position="dodge") 
g <- g + geom_errorbar(aes(ymax=Mean+Upper.SEM, ymin=Mean-Lower.SEM), position=position_dodge(0.9), width=0.5)
g <- g+ scale_fill_manual("Subject", values=colors, breaks=paste0("1.",names),labels=names)
g