如何在ggplot2中旋转图例符号? [英] How to rotate legend symbols in ggplot2?

查看:652
本文介绍了如何在ggplot2中旋转图例符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑使用数据 mtcars 和函数 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()



事实上,误差线在图形上是水平的,但在图例中垂直困扰我:)如何旋转这些符号? 解决方案

我没有提出一个适用于正常ggplot2工作流程的答案,所以现在,这里有一个很好的答案。关闭 stat_summary 图例。然后,添加点和线的几何数据,这些数据超出了想要绘制的实际数据的范围。这将创建你想要的点和水平线图例。然后将绘图轴限制设置为仅包含实际数据的范围,以便假数据点不可见。

  ggplot(mtcars,aes(x = gear,y = cyl,color = as.factor(rep(1:2,16))))+ 
stat_summary(fun.data = mean_cl_boot,position = position_dodge(0.4) (aes(y = cyl-100),size = 2.5)+
coord_flip(aes(y = cyl-100))+
geom_point ylim = range(mtcars $ cyl))



另一个选择是使用网格函数将legend-key grobs旋转90度,但是我会留给那些熟练掌握网格比我。


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?

解决方案

I'm not coming up with an answer that works within the normal ggplot2 workflow, so for now, here's a hacky answer. Turn off the stat_summary legend. Then, add point and line geoms with data that is outside the range of the actual data you want to plot. This will create the point and horizontal line legend that you want. Then set the plot axis limits to include only the range of your real data, so that the fake data points are not visible.

ggplot(mtcars, aes(x=gear, y=cyl, color=as.factor(rep(1:2,16)))) + 
  stat_summary(fun.data=mean_cl_boot, position=position_dodge(0.4), show.legend=FALSE) + 
  geom_line(aes(y=cyl-100)) +
  geom_point(aes(y=cyl-100), size=2.5) +
  coord_flip(ylim=range(mtcars$cyl)) 

Another option would be to rotate the legend-key grobs by 90 degrees using grid functions, but I'll leave that for someone who's more skilled with grid than I am.

这篇关于如何在ggplot2中旋转图例符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆