r - 如何使 ggplot 图例水平添加对象(相对于垂直)

标签 r ggplot2 legend

ggplot 中的图例可以作为水平图例移动到图形的底部,方法是将以下参数添加到 主题 功能:

  • legend.position="bottom" 将图例移动到图表下方
  • legend.direction="horizo​​ntal" 将图例定向为水平。

然而,并不是真的......

legend.direction="horizo​​ntal" 似乎只是减少了图例中的行数和每行 中图例对象的数量。

这可以使用 guides(color=guide_legend(nrow=x)

手动完成
dat <- data.frame(plot = rep(letters,2), val = rep(1:length(letters),2))
library(ggplot2)
ggplot(dat, aes(x = val, y = val, color = plot)) + 
  geom_point() +
  theme(legend.position="bottom") +
  guides(color=guide_legend(nrow=2))

enter image description here

无论....

如果您在上述代码的图形输出中注意到,即使我可以控制图例的“尺寸”(即行数),我也不知道如何更改 <图例的 em>顺序从垂直到水平

  • 所以 a 不是 above b 等(按“垂直”排序),我想要将 b 添加到 a 之后(按“水平”排序)。

如何让我的图例添加对象水平而不是垂直?

像这样:

enter image description here

最佳答案

尝试将 byrow = TRUE 添加到 guide_legend:

ggplot(dat, aes(x = val, y = val, color = plot)) + 
  geom_point() +
  theme(legend.position="bottom") +
  guides(color=guide_legend(nrow=2, byrow = TRUE))

enter image description here

关于r - 如何使 ggplot 图例水平添加对象(相对于垂直),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50417230/

相关文章:

从 grid.arrange 中删除边框

r - RStudio 如何确定控制台宽度,为什么它似乎总是出错?

r - agrep:只返回最佳匹配

r - 每列循环

R 传单 map - 根据所选图层组更改图例

r - 将图例居中在 r 中的两个图下方

减小条形图中图例区域的大小

Rstudio Shiny 的 renderDataTable 标题多行?

r - 如何在 R 中将 30 秒数据扩展到 60 分钟数据

r - 将 x 轴限制为当前星期