How to create boxplot for multiple categories with long names in base R?

R ProgrammingServer Side ProgrammingProgramming

In base R, we use boxplot function to create the boxplots but if we have categorical vector and the corresponding numerical vector then the boxplot can be easily created. For this purpose, we should save those vectors in a data frame and use the $ operator and las = 2 argument to create the boxplot as shown in the below example.

Example

Consider the below vectors:

Countries<−sample(c("China","India","Canada","USA","Russia","Indonesia","Nepal"),5000,replace=TRUE)
> Rate<−rnorm(5000,10,1)

Create the data frame using above vectors −

df<−data.frame(Countries,Rate)
> head(df,20)

Output

Countries    Rate
1 Russia    9.885246
2 Nepal     9.895285
3 USA      11.524113
4 Nepal    10.133226
5 Indonesia 9.711389
6 Russia    10.017597
7 Nepal      9.204832
8 Russia     8.436829
9 Russia    10.579013
10 Canada    7.984238
11 Canada    9.407908
12 Indonesia 9.047598
13 China     9.193126
14 India     8.524555
15 China    10.398155
16 India     6.926581
17 China    10.104521
18 Canada   10.178826
19 India    12.006973
20 Canada   10.371956

Creating boxplot for countries −

boxplot(df$Rate~df$Countries)

Output

Creating boxplot for countries by changing the printing direction of country’s name −

boxplot(df$Rate~df$Countries,las=2,xlab="")

Output

raja
Published on 17-Oct-2020 12:18:34
Advertisements