0
votes

I am new to ggplot (aka ggplot2) and have noticed that for some reason it always makes my boxplots so large that a single box dominates the entire plot. The plot below was generated from the ToothGrowth dataset using the following code:

bp = ggplot(ToothGrowth, aes(x=dose, y=len, color = dose)) + geom_boxplot() + theme(legend.position = "none")
bp

Huge Boxplot

In case you haven't got the ToothGrowth dataset for some reason (its in the library "datasets"), the variables len and dose are both numeric. len has three discreet values, (0.5, 1.0, 2.0) while dose is continuous from approximately 4-30. I expect my boxplot to show three different boxes for the three discreet values of len

I suspect this is caused by some weird graphics settings but I have no idea where to begin my search. Has anyone else run into this kind of problem?

1
The width parameter controls how wide the boxes are relative to the rest of the plot. ggplot(ToothGrowth, aes(x=dose, y=len, group=dose)) + geom_boxplot(width=0.2).eipi10
This "color = dose" makes me assume that you're trying to plot 3 boxplots of dose (not len)...is that the case?Matias Andina
Or, for a single boxplot (not grouped by dose in this case): ggplot(ToothGrowth, aes(x="", y=len)) + geom_boxplot(width=0.5) + labs(x="")eipi10

1 Answers

3
votes

I'm guessing that you want to plot for each "level" of dose one boxplot. That could be done converting into a factor your x within the ggplot2 call.

Here's how to:

bp = ggplot(ToothGrowth, aes(x=factor(dose), y=len, color = dose)) + geom_boxplot() + theme(legend.position = "none")
bp

And here's the plot

enter image description here


Another option is to use the group aesthetic, which allows you to keep the x axis on your original scale (instead of assuming a 1 unit difference between each level if you use factor()). In this case they're pretty similar, but could be important for other uses.

bp = ggplot(ToothGrowth, aes(x=dose, y=len, color = dose, group = dose)) + geom_boxplot() + theme(legend.position = "none")
bp

enter image description here