Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create box plot based on min and max alone

Tags:

plot

r

ggplot2

In ggplot, we can create a bar plot by specifying the colum in the data frame that has the height of the bars

library("ggplot2")
library(plyr)
mm <- ddply(mtcars, "cyl", summarise, mmpg = mean(mpg))
ggplot(mm, aes(x = factor(cyl), y = mmpg)) + geom_bar(stat = "identity")

However, I cannot figure out how to make a similar plot that both top AND bottom of the bars are specified. For instance using the data below

df <- read.table(text = " id  min  max 
    Sp1     8.5          13.2     
 Sp2     11.7          14.5     
 Sp3     14.7          17.7     ", header=TRUE)

We would get a plot closely resembling this: enter image description here

Any suggestions?

like image 553
Lucas Fortini Avatar asked Oct 12 '25 06:10

Lucas Fortini


2 Answers

You can use geom_crossbar:

ggplot(df) +
  geom_crossbar(aes(ymin = min, ymax = max, x = id, y = min),
                fill = "blue", fatten = 0)

enter image description here

like image 169
Sven Hohenstein Avatar answered Oct 15 '25 10:10

Sven Hohenstein


You can use geom_boxplot if you precise all the aes.

df$med = 0.5*(df$min+df$max)
ggplot(df, 
       aes(x=id, ymin=min, lower=min,fill=id ,
           middle=`med`, upper=max, ymax=max)) +
  geom_boxplot(stat="identity")

enter image description here

like image 21
agstudy Avatar answered Oct 15 '25 08:10

agstudy