Home > OS >  costumizing barplot in R
costumizing barplot in R

Time:12-24

I want to plot the result of a test in a barplot sorted by to groups. I want to insert all possible results (0 to 50 points), even if nobody reached that result.

I got this, I want spaces in real length, for example between 30 and 41.

enter image description here

team=c("m","w","m","w","w","m","m","w","m","w","m","w","m","m","m","m","m","w","w","m")
pts=c(12,27,6,26,29,16,23,30,20,17,41,14,8,9,5,7,28,42,6,27)`
 
df <- data.frame(team,pts)
df

barplot(table(df$team, df$pts), las=1, beside=TRUE,border="white",
axis.lty = 1,  xlim=c(0,50), ylim= c(0,2),axes=FALSE,
col=c("lightblue","pink")
)

Now I wonder, how I can customize the x-axis so that every possible result is displayed.

CodePudding user response:

A ggplot solution is as below:

1. Load the package, create data frame

library(tidyverse)  # install.packages("tidyverse") if you don't have tidyverse


df <- data.frame(
  team=c("m","w","m","w","w","m","m","w","m","w","m","w","m","m","m","m","m","w","w","m"),
  pts=c(12,27,6,26,29,16,23,30,20,17,41,14,8,9,5,7,28,42,6,27)
  )

2. Plot the barchart with the full range of x-axis (from 0 to 50)

df |> 
  ggplot(aes(x = pts, fill = team), color = "white")  
  geom_bar(position = "dodge")  
  theme_minimal()  
  scale_x_continuous(limits = c(0, 50),
                     expand = c(0, 0))  
  scale_y_continuous(expand = expansion(mult = c(0, 0.15)))

3. Outcome

enter image description here

Hope this is helpful.

  • Related