繁体   English   中英

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

[英]How to change x-axis tick label names, order and boxplot colour using R ggplot?

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

建立@ 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图层可以更改轴标签。 通过向scale_fill_manualscale_color_manual添加labels ,您可以更改图例标签。 为两者添加name可让您更改图例标题。 最后,我将theme_bw()添加到绘图中,使背景变白并在绘图周围添加边框。 希望有所帮助!

在此输入图像描述

是的,你可以这样做。 使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM