简体   繁体   English

带g_legend的水平图例

[英]Horizontal Legend with g_legend

I'm using the commonly referenced g_legend function to pull a legend out of a graph made with ggplot2 such that I can organize it with multiple plots using grid.arrange. 我正在使用通用引用的g_legend函数从由ggplot2制作的图形中提取图例,以便可以使用grid.arrange将其与多个图一起组织。 I want the legend to be a single row of elements such that I can easily put it at the bottom of my grid. 我希望图例是一行元素,以便可以轻松地将其放在网格的底部。 However, regardless of format on the original plot, g_legend always returns a legend with a single column. 但是,无论原始绘图的格式如何,g_legend总是返回带有单列的图例。 Does anyone know of a way to force the legend to only have a single row? 有谁知道强制图例仅排一行的方法?

#extract legend
#https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

I had the same problem, and I've just solved it. 我遇到了同样的问题,而我已经解决了。 You have to add legend options to your "p1.leg": 您必须在“ p1.leg”中添加图例选项:

p1.leg <- ggplot(data,aes(v1, v2,colour=v3))+geom_area() + theme(legend.direction = "horizontal", legend.position = "bottom")
p1 <- ggplot(data, aes( v1, v2),

Then it works. 然后就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM