如何使用R ggplot更改x轴刻度标签名称、顺序和箱线图颜色?

23

我有一个包含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来实现这一点?

2个回答

40
基于@shadow的回答,以下是您可以手动更改x轴标签的方法。我还加入了其他一些改变,有助于改善图形和图例的外观:
基于@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()

在绘图的scale_x_discrete层中添加labels选项可以更改坐标轴标签。将labels添加到scale_fill_manualscale_color_manual中都可以更改图例标签。将name添加到两者中都可以更改图例标题。最后,我向图表中添加了theme_bw(),以使背景为白色并在图表周围添加边框。希望这有所帮助!

enter image description here


我认为在 scale_fill_manual() 的 labels=c("hESC1","hESC2","hESC3","hESC4") 后面需要加一个逗号。 - Justin Meyer

7

是的,您可以这样做。请按照以下方式使用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

这个方法可以正确地为箱线图分配正确的颜色并更改它们的顺序。但是,我还希望更改轴标签的名称(例如将“orange”更改为“hESC”),并且在图例中反映出来。 - user2639056
@user2639056 我已经在下面回答了你的问题。 - rmbaughman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接