r - 增加ggplot2中图例项之间的空白
问题描述
我的问题是这个问题的延伸。请注意,我使用的是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()
)
上面的代码创建了这个图。
我想将图例标签(A、B、C)移动到更靠近其相应图标的位置,如下面的红色箭头所示,这将在图例类别之间创建更多空白。我该怎么做?
解决方案
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()
)
由reprex 包(v0.2.0) 于 2018 年 6 月 15 日创建。
推荐阅读
- azure - 订购时 Azure Function Service Bus 触发器是必不可少的吗?
- c++ - 使用 QWidget::event 覆盖小部件中的 Tab 按
- oauth-2.0 - OAuth2.createService 是否超出 PropertiesServices 中的存储容量?
- java - java从属性名中获取getter/setter名
- mysql - Mysql中建表中的set命令
- java - 如何使用 EdDSA/Ed448 签名算法重新生成私钥?
- linux - 多次出现的 Linux shell 字符串替换
- android - Android 布局:居中视图但尊重角视图
- javascript - Javscript 测验:我似乎无法保存用户的分数
- python - 如何将json输出转换为字符串值