2014-05-09 233 views
17

我有一个包含CSV文件的文件夹,每个数据,例如两列:如何使用R ggplot更改x轴刻度标签名称,顺序和boxplot颜色?

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做到这一点?

回答

32

大厦关闭@影子的答案,这里是你如何可以手动更改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_manualscale_color_manual可让您更改图例标签。向两者添加name可让您更改图例标题。最后,我将theme_bw()添加到情节,使背景变成白色,并在情节周围添加边框。希望有所帮助!

enter image description here

6

是的,你可以做到这一点。使用scale_color_manualscale_fill_manualscale_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 
+0

这适用于将正确的颜色分配给箱图并更改它们的顺序。不过,我也希望更改轴标签的名称(例如,将“orange”更改为“hESC”),并将其反映在图例中。 – user2639056

+0

@ user2639056我在下面回答了您的问题。 – rmbaughman