ggplot2中图例项之间的空白增加 [英] Increasing whitespace between legend items in ggplot2

查看:154
本文介绍了ggplot2中图例项之间的空白增加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是 github 上使用,而在CRAN上还没有. /p>

My question is an extension of this question. Note that I'm using version 2.3.0 which is available on github, not yet on 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()
        ) 

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

The code above creates this plot.

我想将图例标签(A,B,C)移到它们相应的图标附近,如下面的红色箭头所示,这将在图例类别之间创建更多的空白.我该怎么办?

I would like to move the legend labels (A, B, C) closer to their corresponding icons, as shown by the red arrows below, which would create more whitespace between the legend categories. How would I do that?

推荐答案

一种可能的解决方法是使用

One possible workaround is to add extra whitespace on the right of Categories using 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()
  ) 

reprex软件包(v0.2.0)于2018-06-15创建. /sup>

Created on 2018-06-15 by the reprex package (v0.2.0).

这篇关于ggplot2中图例项之间的空白增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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