繁体   English   中英

在ggplot2中将按键图例和标签与图例框的右侧对齐

[英]Aligning the keys legend and labels to the right side of the legend box, in ggplot2

我有以下数据框,其中我将y预测为年龄和性别的函数:

df = data.frame(
  age = c('old', 'old', 'young', 'young'),
  gender = c('male', 'female', 'male', 'female'),
  y = 1:4)

和相应的图形:

ggplot(df, aes(x=age, y=y, fill = gender)) + 
  geom_col(position = 'dodge')

在此处输入图片说明

我想控制图例框的外观。 特别是,我希望将整个框向右对齐(而不是向左对齐)。 因此,按键图例应出现在框的右侧,而左侧应是标签。

我知道theme()函数的legend.text.align参数,但它仅控制键及其对应标签之间的距离。

关于如何反转对齐的任何想法?

您可以使用guide_legend(label.position = ...来调整标签位置,标签等。

ggplot(df, aes(x=age, y=y, fill = gender)) + 
  geom_col(position = 'dodge') +
  guides(fill = guide_legend(# title.hjust = 1, # adjust title if needed
                             label.position = "left",
                             label.hjust = 1)

在此处输入图片说明

有关更多信息: https : //ggplot2.tidyverse.org/reference/guide_legend.html

暂无
暂无

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

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