How to create boxplot for categories with grey color palette in reverse order using ggplot2 in R?

R ProgrammingServer Side ProgrammingProgramming

To create boxplot for categories with grey color palette in reverse order using ggplot2, we can follow the below steps −

  • First of all, create a data frame.
  • Then, create the boxplot for categories with color of bars in grey palette.
  • Create the boxplot for categories with color of bars with grey palette in reverse order.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

Group<-sample(c("Low","Medium","High"),25,replace=TRUE)
Score<-sample(1:100,25)
df<-data.frame(Group,Score)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   Group Score
1  High   33
2  Low    43
3  Medium 16
4  Low    90
5  High   67
6  Medium 52
7  High   82
8  High   62
9  Medium 28
10 High   39
11 Low    15
12 High   57
13 Low    51
14 Medium 100
15 Low   97
16 Medium 23
17 High 72
18 Medium 96
19 Low 22
20 Medium 35
21 Low 6
22 High 88
23 Medium 65
24 Low 11
25 High 37

Create boxplot with bars in grey color palette

Use scale_fill_grey to create the boxplot with bars in grey color palette −

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()

Output

Create boxplot with bars in grey color palette in reverse order

Use scale_fill_grey to create the boxplot with bars in reverse order with grey color palette(the default value for start and end are start=0.2 and end=0.8) −

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(start=0.8,end=
0.2)

Output

raja
Published on 06-Aug-2021 12:05:57
Advertisements