如何在R中使用ggplot2创建使用灰色调色板的类别箱线图?
要使用ggplot2创建具有灰色调色板的类别箱线图,我们可以按照以下步骤操作:
- 首先,创建一个数据框。
- 然后,创建具有默认条形颜色的类别箱线图。
- 创建具有灰色调色板条形颜色的类别箱线图。
创建数据框
让我们创建一个如下所示的数据框:
Group<-sample(c("Low","Medium","High"),25,replace=TRUE) Score<-sample(1:100,25) df<-data.frame(Group,Score) df
执行上述脚本后,将生成以下输出(由于随机化,此输出在您的系统上会有所不同):
Group Score 1 Low 57 2 Low 50 3 Medium 27 4 High 84 5 High 100 6 Low 95 7 Low 13 8 High 12 9 Medium 11 10 Medium 42 11 Medium 25 12 Low 5 13 High 85 14 Low 70 15 Medium 33 16 Medium 92 17 Low 58 18 High 88 19 High 61 20 High 8 21 High 39 22 Medium 38 23 High 37 24 High 96 25 Low 6
创建条形颜色为默认颜色的箱线图
加载ggplot2包并创建条形颜色为默认颜色的箱线图:
Group<-sample(c("Low","Medium","High"),25,replace=TRUE) Score<-sample(1:100,25) df<-data.frame(Group,Score) library(ggplot2) ggplot(df,aes(Group,Score,fill=Group))+geom_boxplot()
输出
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
创建条形颜色为灰色的箱线图
使用scale_fill_grey创建条形颜色为灰色调色板的箱线图:
Group<-sample(c("Low","Medium","High"),25,replace=TRUE) Score<-sample(1:100,25) df<-data.frame(Group,Score) library(ggplot2) ggplot(df,aes(Group,Score,fill=Group))+geom_boxplot()+scale_fill_grey()
输出
广告