LuisSilva
LuisSilva

Reputation: 234

Cant's seem to adjust boxplot width

I can't change the width of ggplot2 boxplot.

I know it's probably the thousandth time someone makes a similar question to this but after spending my last 2 hours trying to find a solution (which i rarely do) i'm all out.

Besides i guess someone knowledgeable about ggplot2 can answer in 30 seconds.

Example code of similar problem

# Code from official ggplot2 help page
# https://ggplot2.tidyverse.org/reference/geom_boxplot.html
y <- rnorm(100)
df <- data.frame(
  x = 1,
  y0 = min(y),
  y25 = quantile(y, 0.25),
  y50 = median(y),
  y75 = quantile(y, 0.75),
  y100 = max(y)
)
ggplot(df, aes(x)) +
  geom_boxplot(
   aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),
   stat = "identity"
 )

I tried to changed the width so it is not the whole graphic with the boxplot, to no avail. i've tried putting width = 0.5/width = 0.1 in ggplot, geom_boxplot and in aes and it changes nothing.

Can someone help? Thanks

EDIT: Thanks for the help guys. For future reference the code i used was:

y <- rnorm(100)
df <- data.frame(
  x = 1,
  y0 = min(y),
  y25 = quantile(y, 0.25),
  y50 = median(y),
  y75 = quantile(y, 0.75),
  y100 = max(y)
)
ggplot(df, aes(as.factor(x))) +
  geom_boxplot(
   aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),
   width = 0.1,
   stat = "identity"
 )

Upvotes: 3

Views: 13491

Answers (2)

Dylan_Gomes
Dylan_Gomes

Reputation: 2232

The problem with the example that you have given seems to be that the X values are numeric. I am not sure that a boxplot is the best way to go if you have x and y values that are both numeric, but see John Bell's answer if this is, in fact, what you want.

But, in the case that your X values are actually factors, this answer should work. If you create a data frame with factors (groups) then the width functionality returns.

data<-data.frame("Group"=as.factor(rep(c(1,2),16)),"Y"=rnorm(32))

ggplot(aes(x=Group,y=Y),data=data)+
  geom_boxplot(width=.15)

enter image description here

ggplot(aes(x=Group,y=Y),data=data)+
  geom_boxplot(width=1)

enter image description here

Also might be worth checking out this USGS page for tips on ggplot2 boxplots: https://owi.usgs.gov/blog/boxplots/

Upvotes: 8

John Bell
John Bell

Reputation: 11

Adding xlim(0,2) widens the x-axis and thus narrows the boxplot:

ggplot(df, aes(x)) +
  geom_boxplot(
   aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),
   stat = "identity"
 ) +
 xlim(0,2)

Upvotes: 1

Related Questions