GGPlot2 Boxplot only shows flat lines

Viewed 23032

I have been working on this for hours, cant seem to get this right. The boxplot only gives me flat vertical lines, its driving me crazy. I get the same input with or without factor function

ggplot(df2,aes(x = factor(Location),y=Final.Result)) + geom_boxplot()

Solved! there are some data values such as "< 0.005" which R picks up as string and converts everything to factor.

3 Answers

This answer is only related to the title of the question, but this question ranks top if I google "ggplot2 boxplot only lines" and there was no other helpful search result on that search term, so I feel it fits here well:

Boxplots only work if you specify the quantity as y aestetic.

EDIT: Since ggplot 3.3.0, there is the orientation= parameter that allows to change the orientation. See the ggplot NEWS on this

Compare

 ggplot(mtcars, aes(x = factor(cyl), y = disp)) + geom_boxplot()

sample boxplot with x = quantity and y = grouping

which gives correct boxplots with

 ggplot(mtcars, aes(y = factor(cyl), x = disp)) + geom_boxplot()

boxplot with incorrect aesthetic setting

which gives only lines instead of box plots.

To obtain horizontal box plots, use coord_flip():

 ggplot(mtcars, aes(x = factor(cyl), y = disp)) + 
   geom_boxplot() + coord_flip()

vertical boxplot

Another reason you get flat lines instead of boxes is that you summarized the numeric values in your table (eg calculating mean, median, etc.) and now boxplot() sees only a single value.

Related