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()
The fact that error bars are horizontal on the graph but vertical in the legend bothers me :) How can I rotate these symbols?
For Moving the position of ggplot2 legend at any side of the plot, we simply add the theme() function to geom_point() function.
You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.
Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With