首页 > 解决方案 > 如何对齐ggplot中的图例键和文本?

问题描述

我有以下数据框:

 df = data.frame(
  x = c(1:10, 1:10),
  y = 1:20,
  group = rep(c('male', 'female'), each = 10))

ggplot(df, aes(x=x, y=y, color = group)) + 
  geom_smooth()

如您所见,文本图例(男性、女性)出现在关键图例(蓝色和红色水平条)的右侧。出于语言原因,我想要相反:关键图例应该在文本图例的右侧。我只找到了将文本向左或向右对齐的解决方案,但没有将键放在文本之前或之后。(请参阅此处在 ggplot 中对齐图例文本

ggplot(df, aes(x=x, y=y, color = group)) + 
  geom_smooth() +
  theme(
    legend.text.align = 1)

任何想法?

标签: rggplot2legend

解决方案


我希望这是你想要的

library(ggplot2)

df = data.frame(
  x = c(1:10, 1:10),
  y = 1:20,
  group = rep(c('male', 'female'), each = 10))

ggplot(df, aes(x=x, y=y, color = group)) + 
  geom_smooth() +  
  theme(legend.position = 'right') + 
  guides(color = guide_legend(title.position = "top", 
                              # hjust = 0.5 centres the title horizontally
                              title.hjust = 0.5,
                              label.position = "left")) 
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

reprex 包(v0.3.0)于 2020 年 1 月 8 日创建


推荐阅读