Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to make geom_vline legend key horizontal when using coord_flip, ggplot2? [duplicate]

Consider for example this plot using the data mtcars and the function coord_flip

library(ggplot2)
library(Hmisc)

ggplot(mtcars,aes(x=gear,y=cyl)) + stat_summary(aes(color=as.factor(rep(1:2,16))),
fun.data=mean_cl_boot, position=position_dodge(0.4)) + coord_flip()

enter image description here

The fact that error bars are horizontal on the graph but vertical in the legend bothers me :) How can I rotate these symbols?

like image 624
Remi.b Avatar asked Dec 17 '25 23:12

Remi.b


1 Answers

Tweak the legend key

GeomPointrange$draw_key <-  function (data, params, size)     {

         draw_key_vpath <- function (data, params, size) {
           # only need to change the x&y coords so that the line is horizontal
           # originally, the vertical line was `0.5, 0.1, 0.5, 0.9`
              segmentsGrob(0.1, 0.5, 0.9, 0.5, 
              gp = gpar(col = alpha(data$colour, data$alpha), 
              lwd = data$size * .pt, lty = data$linetype, 
              lineend = "butt"), arrow = params$arrow)
              }

    grobTree(draw_key_vpath(data, params, size), 
             draw_key_point(transform(data, size = data$size * 4), params))
}

Then plot

 ggplot(mtcars,aes(x=gear,y=cyl)) + 
    stat_summary(aes(color=as.factor(rep(1:2,16))),
                  fun.data=mean_cl_boot, position=position_dodge(0.4)) + 
    coord_flip()
like image 187
user20650 Avatar answered Dec 19 '25 15:12

user20650



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!