Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GGPlot2 Boxplot only shows flat lines

Tags:

r

ggplot2

boxplot

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.

like image 473
user3146687 Avatar asked Dec 19 '22 20:12

user3146687


2 Answers

You got those lines because variable Final.Result in your data frame is factor and not numeric (you can check it with function str()).

> str(df2)
'data.frame':   66 obs. of  3 variables:
 $ Location    : Factor w/ 17 levels "BOON KENG RD BLK 6 (DS)",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Parameter   : Factor w/ 54 levels "Aluminium","Ammonia (as N)",..: 37 37 37 37 37 37 37 37 37 37 ...
 $ Final.Result: Factor w/ 677 levels "< 0.0005","< 0.001",..: 645 644 654 653 647 643 647 647 646 646 ...

Try to convert those values to numeric (as in df2 there is no non numeric values). This will work only for df2 but if your whole data frame has those "< 0.0005","< 0.001" values, you should decide how to treat them (replace with NA, or some small constant).

df2$Final.Result2<-as.numeric(as.character(df2$Final.Result))
ggplot(df2,aes(x = factor(Location),y=Final.Result2)) + geom_boxplot()
like image 121
Didzis Elferts Avatar answered Dec 22 '22 09:12

Didzis Elferts


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

like image 28
akraf Avatar answered Dec 22 '22 09:12

akraf