我有一个包含csv文件的文件夹,每个文件都有两列数据,例如:
0,red
15.657,red
0,red
0,red
4.429,red
687.172,green
136.758,green
15.189,red
0.152,red
23.539,red
0.348,red
0.17,blue
0.171,red
0,red
61.543,green
0.624,blue
0.259,red
338.714,green
787.223,green
1.511,red
0.422,red
9.08,orange
7.358,orange
25.848,orange
29.28,orange
我使用以下R代码生成箱图:
files <- list.files(path="D:/Ubuntu/BoxPlots/test/", pattern=NULL, full.names=F, recursive=FALSE)
files.len<-length(files)
col_headings<-c("RPKM", "Lineage")
for (i in files){
i2<-paste(i,"png", sep=".")
boxplots<-read.csv(i, header=FALSE)
names(boxplots)<-col_headings
png(i2)
bplot<-ggplot(boxplots, aes(Lineage, RPKM)) + geom_boxplot(aes(fill=factor(Lineage))) + geom_point(aes(colour=factor(Lineage)))
print(bplot)
graphics.off()
}
现在我想更改箱图的颜色以匹配相应的x轴颜色标签。我还想更改x轴标签的名称,以及它们的顺序。有没有办法使用ggplot或qplot来做到这一点?
答案 0 :(得分:32)
建立@ shadow的答案,以下是如何手动更改x轴标签的方法。我还进行了一些其他更改,这些更改有助于改善图形和图例的外观:
colorder <- c( "green", "orange", "red", "blue")
bplot<-ggplot(temp, aes(Lineage, RPKM)) +
geom_boxplot(aes(fill=factor(Lineage))) +
geom_point(aes(colour=factor(Lineage))) +
scale_color_manual(breaks=colorder, # color scale (for points)
limits=colorder,
values=colorder,
labels=c("hESC1","hESC2","hESC3","hESC4"),
name="Group") +
scale_fill_manual(breaks=colorder, # fill scale (for boxes)
limits=colorder,
values=colorder,
labels=c("hESC1","hESC2","hESC3","hESC4")
name="Group") +
scale_x_discrete(limits=colorder,labels=c("hESC1","hESC2","hESC3","hESC4")) +
theme_bw()
将labels
选项添加到绘图的scale_x_discrete
图层可以更改轴标签。向labels
和scale_fill_manual
添加scale_color_manual
可让您更改图例标签。向两者添加name
可让您更改图例标题。最后,我将theme_bw()
添加到绘图中,使背景变白并在绘图周围添加边框。希望有所帮助!
答案 1 :(得分:6)
是的,你可以这样做。使用scale_color_manual
,scale_fill_manual
和scale_x_discrete
,如下所示:
# specify colors and order
colorder <- c( "green", "orange", "red", "blue")
bplot<-ggplot(boxplots, aes(Lineage, RPKM)) +
geom_boxplot(aes(fill=factor(Lineage))) +
geom_point(aes(colour=factor(Lineage))) +
scale_color_manual(breaks=colorder, # color scale (for points)
limits=colorder,
values=colorder) +
scale_fill_manual(breaks=colorder, # fill scale (for boxes)
limits=colorder,
values=colorder) +
scale_x_discrete(limits=colorder) # order of x-axis