1

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

I got this but 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?

Shawn Hemelstrand
  • 2,676
  • 4
  • 17
  • 30

1 Answers1

1

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.

Grasshopper_NZ
  • 302
  • 1
  • 10
  • Thank you so much! This has been extremly helpful for me and exaktly what I was looking for :) – montarenbici Dec 24 '22 at 03:21
  • Glad to know that! For any future plots, you can modify scale_x_continuous(limits = c(0, 50)) to any other values. 0 is the left limit, 50 is the right limit. – Grasshopper_NZ Dec 24 '22 at 03:43