Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: plotting bars when using stat_summary()

Here is my current script and the output:

ggplot(data.and.factors.prov,aes(x=assumptions,y=FP,
                       colour=factor(Design.Complexity))) +
       stat_summary(fun.data=mean_cl_normal,position=position_dodge(width=0.5)) +
       geom_blank() + scale_colour_manual(values=1:7,name='Design Complexity') + 
       coord_flip()

enter image description here

How can I have (horizontal) bars (starting at FP=0 and ending at the point position) instead of points ? (I don't want to lose the error bars)

I'd like to give you my data.and.factors.prov data.table but it is too big to be posted ! If you need a reproducible example, please let me know how I can give you my data set ?!

like image 255
Remi.b Avatar asked Jun 12 '13 14:06

Remi.b


People also ask

What does Stat_summary do in R?

The function stat_summary() can be used to add mean/median points and more to a dot plot.

What does stat =' summary do in Ggplot?

ggplot2 has the ability to summarise data with stat_summary . This particular Stat will calculate a summary of your data at each unique x value. The following creates a scatter plot of some points with a mean calculated at each x and connected by a line.

What is fun data?

fun.data. A function that is given the complete data and should return a data frame with variables ymin , y , and ymax . fun.min, fun, fun.max. Alternatively, supply three individual functions that are each passed a vector of values and should return a single number.


1 Answers

For the stat_summary() default geom is "pointrange". To get the bars and errorbars one solution is to use two stat_summary() calls - one to make errorbars and second to calculate just mean values and plot bars. You will need also to adjust width= inside the position_dodge() and fill= to the same factor as for colour= to change filling of bars.

Here is an example with mtcars data.

ggplot(mtcars,aes(x=factor(cyl),y=mpg,colour=factor(gear),fill=factor(gear))) +  
  stat_summary(fun.data=mean_cl_normal,position=position_dodge(0.95),geom="errorbar") + 
  stat_summary(fun.y=mean,position=position_dodge(width=0.95),geom="bar")+
  coord_flip()

enter image description here

like image 199
Didzis Elferts Avatar answered Sep 28 '22 06:09

Didzis Elferts