0

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?

3
  • 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). Commented Dec 4, 2015 at 21:16
  • This "color = dose" makes me assume that you're trying to plot 3 boxplots of dose (not len)...is that the case? Commented Dec 4, 2015 at 21:20
  • 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="") Commented Dec 4, 2015 at 21:23

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

You also could use the group aesthetic ie aes(x = dose, y = len, color = dose, group = dose) This will maintain the different distances between 0.5 and 1, vs 1 and 2 if that is important for your graph.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.