将图例标签与ggplot左对齐

Que*_*Roy 4 r ggplot2

我有一个传说,看起来像这样:

图例

令人有些困惑的是,例如“ color-a”标签恰好位于其左侧的点与右侧的点之间的中心。我希望此标签离其左侧的点更近,以使哪个标签与哪个点相关联更为明显。

我曾尝试使用legend.key.widthlegend.title.alignlegend.spacing.x到目前为止,没有运气...

这是一个最小的可重现示例:

library(tidyverse)

# Test data, it does not matter.
data <- tibble(
  color = c(rep('color-a', 5), rep('color-b', 5), rep('color-c', 5), rep('color-d', 5)),
  x = rep(seq(0, 4, 1), 4),
  y = c(seq(0, .4, 0.1), seq(0, .4, 0.1) + 0.1, seq(0, .4, 0.1) + 0.3, seq(0, .4, 0.1) + 0.4)
)

# Plot
ggplot(data, aes(x = x, y = y, color = color)) +
  scale_color_discrete(guide="legend") +
  geom_point() +
  theme_minimal() +
  theme(legend.position = "bottom")
Run Code Online (Sandbox Code Playgroud)

Axe*_*man 5

您不能让它们比现有的对齐方式更多。但是,您可以设置一个margin,以在文本右侧之间创建更多空间:

ggplot(data, aes(x = x, y = y, color = color)) +
  scale_color_discrete(guide='legend') +
  geom_point() +
  theme_minimal() +
  theme(
    legend.position = "bottom", 
    legend.text = element_text(margin = margin(0, 50, 0, 0))) ## <- here
  )
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明