为多个组生成不同颜色的ggplot2 boxplot

时间:2013-04-15 23:17:27

标签: r ggplot2 boxplot

我对R和ggplot相当新。

我正在尝试生成一个按两个变量排序的boxplot。在我的情况下物种和实验。 到目前为止我用

得到了什么
ggplot(DF, aes(Species, Protein, fill=Experiment, dodge=Experiment)) +
    stat_boxplot(geom ='errorbar')+
    geom_boxplot()

是我的物种的箱形图,每个物种有2个条,每个实验一个。

现在我的问题是,是否有可能以这种方式改变颜色,我每种物种都有不同的颜色,并且可以说,实验中这些颜色的颜色不同?

让我们说,第一个物种不是一个黑色和浅蓝色的酒吧,第二个是一个黑暗和浅绿色的酒吧等。

数据采用csv文件的形式,如下所示:

Experiment,Species,Protein
Spring,D_strigosa,5.107767364
Spring,D_strigosa,8.288980741
Spring,D_strigosa,7.537376567
Spring,D_strigosa,4.811744241
Spring,D_strigosa,9.559043454
Spring,M_cavernosa,13.66759289
Spring,M_cavernosa,23.54880195
Spring,M_cavernosa,11.00790037
Spring,M_cavernosa,13.70597973
Spring,M_cavernosa,12.26970906
Spring,M_faveolata,9.559043454
Spring,M_faveolata,4.135860474
Spring,M_faveolata,4.557306615
Spring,M_faveolata,7.621872315
Spring,M_faveolata,6.016859956
Spring,M_annularis,6.294920733
Spring,M_annularis,5.163371831
Spring,M_annularis,2.177243143
Spring,M_annularis,3.55966551
Autumn,D_strigosa,3.709978392
Autumn,D_strigosa,7.192777836
Autumn,D_strigosa,5.31544441
Autumn,D_strigosa,6.578602058
Autumn,D_strigosa,5.610085559
Autumn,M_cavernosa,11.64182554
Autumn,M_cavernosa,10.44968102
Autumn,M_cavernosa,9.377389318
Autumn,M_cavernosa,10.99346107
Autumn,M_cavernosa,11.5676896
Autumn,M_faveolata,4.638054165
Autumn,M_faveolata,7.191664953
Autumn,M_faveolata,6.981827102
Autumn,M_faveolata,6.386452477
Autumn,M_annularis,4.709770404
Autumn,M_annularis,3.554071459
Autumn,M_annularis,4.596686351
Autumn,M_annularis,3.530585628

1 个答案:

答案 0 :(得分:11)

您应该interaction()使用fill=并在Species内提供Experimentinteraction()。然后使用scale_fill_manual(),您可以为所需的颜色设置values=(颜色数对应于方框图的数量)。颜色顺序首先是SpeciesAutumn的颜色,然后是SpeciesSpring的颜色。

ggplot(DF, aes(Species, Protein, fill=interaction(Species,Experiment), dodge=Experiment)) +
  stat_boxplot(geom ='errorbar')+
  geom_boxplot()+
  scale_fill_manual(values=c("blue","green","red","cyan",
             + "darkblue","darkgreen","darkred","darkcyan"))

enter image description here