r - 在 ggplot2 中增加图例项之间的空白

标签 r ggplot2

我的问题是 this question 的扩展名.请注意,我使用的是 github 上提供的 2.3.0 版,尚未在 CRAN 上。

library(ggplot2)

df <- data.frame("Categories" = rep(c("A", "B", "C"), 3),  
                 "values" = c(rep(0.39, 3), rep(0.37, 3), rep(0.24, 3)),
                 "X" = 1:9)

ggplot(df, aes(x = X, y = values, colour = Categories)) +
  geom_line() +
  theme(
        legend.position = "top",
        legend.spacing.x = unit(2, unit = "cm"),
        legend.title = element_blank()
        ) 

上面的代码创建了这个图。

enter image description here

我想将图例标签(A、B、C)移动到更靠近其相应图标的位置,如下面的红色箭头所示,这将在图例类别之间创建更多空白。我该怎么做?

enter image description here

最佳答案

一种可能的解决方法是在 Categories 的右侧添加额外的空格。使用 stringr::str_pad

library(ggplot2)

df <- data.frame("Categories" = rep(c("A", "B", "C"), 3),  
                 "values" = c(rep(0.39, 3), rep(0.37, 3), rep(0.24, 3)),
                 "X" = 1:9)

# define a custom function
str_pad_custom <- function(labels){
  new_labels <- stringr::str_pad(labels, 10, "right")
  return(new_labels)
}

ggplot(df, aes(x = X, y = values, colour = Categories)) +
  geom_line() +
  scale_color_brewer(labels  = str_pad_custom,
                     palette = "Dark2") +
  theme(
    legend.position = "top",
    legend.key.width = unit(1.0,  unit = "cm"),
    legend.spacing.x = unit(0.25, unit = "cm"),
    legend.title = element_blank()
  ) 



创建于 2018-06-15 由 reprex package (v0.2.0)。

关于r - 在 ggplot2 中增加图例项之间的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50883294/

相关文章:

r - 如何在ggplot2 geom_boxplot中使用实心方 block 作为图例键

r - 仅标记选定的中断

r - 如何为ggplot2全局设置主题?

r - ggplot2 中具有两种色阶的并排堆叠条形图

r - 如何将R中公共(public)列上的两个数据框与其他数据框合并?

r - 为间隔创建标签

regex - 清理 R 中的字符串 : add punctuation w/o overwriting last character

r - nearPoints 无法从 Shiny 的坐标信息中自动推断出 `xvar`

r - ggplot2 使用 geom_errorbar 和 geom_point 将点添加到绘图中

r - ggplot2: "geom_point requires the following missing aesthetics: x, y"