ggplot2中的中心图例相对于图像 [英] Center legend in ggplot2 relative to image

查看:38
本文介绍了ggplot2中的中心图例相对于图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保持字幕居中,而不必通过 theme()中的 legend.position 手动更改位置.如果选择"bottom" ,则标题将相对于图形框架而不是图像居中,因此有必要对页边距进行更改.有什么办法可以像图片中那样通过某些参数来居中吗?

解决方案

您将不得不使用一种变通方法,例如提取图例,然后将其与原始图结合.这是使用(v0.3.0)于2019年12月25日创建sup>

I would like to leave my subtitle centered without having to manually change the position by legend.position in theme(). If I select "bottom", the caption will be centered relative to the graphic frame rather than the image, making it necessary to make changes to the margins. Is there any way to center by some argument as in the image?

解决方案

You will have to use a workaround such as extracting the legend then combine it with the original plot. Here is an example using get_legend and plot_grid functions from the cowplot package.

library(ggplot2)
library(cowplot)
#> 
#> ********************************************************
#> Note: As of version 1.0.0, cowplot does not change the
#>   default ggplot2 theme anymore. To recover the previous
#>   behavior, execute:
#>   theme_set(theme_cowplot())
#> ********************************************************

p1 <- ggplot(iris, aes(x = Species, y = Petal.Length)) +
  geom_col(aes(fill = Species)) +
  coord_flip() +
  scale_fill_brewer(palette = 'Set2') +
  theme_minimal(base_size = 14) +
  theme(legend.position = 'bottom')

# extract the legend
p1_legend <- get_legend(p1)

# plot p1 and legend together
p2 <- plot_grid(p1 + theme(legend.position = 'none'), p1_legend,
          nrow = 2, rel_heights = c(1, 0.1))

# comparison
plot_grid(p1, p2, 
          nrow = 2)

Created on 2019-12-25 by the reprex package (v0.3.0)

这篇关于ggplot2中的中心图例相对于图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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