我正在尝试使图例框(指示符)与图例文本之间的距离更大一些。我有一个改编自this amazing page的代码。这是我的MWE:
library(openxlsx) # for reading in Excel data
library(dplyr) # for data manipulation
library(tidyr) # for data manipulation
library(magrittr) # for easier syntax in one or two areas
library(gridExtra) # for generating some comparison plots
library(ggplot2) # for generating the visualizations
mwedata <- data.frame(Metro=c(rep("Dayton,OH",6)))
mwedata$class <- as.character(c("Lower","Middle","Upper","Lower","Middle","Upper"))
mwedata$year <- as.numeric(c(rep(2000,3),rep(2014,3)))
mwedata$value <- as.numeric(c(0.221,0.580,0.199,0.269,0.527,0.204))
mwedata <- mwedata %>%
mutate(y_label = paste0(round(value*100, 1), "%"))
plot <- ggplot(mwedata, aes(x = class, y = value, fill = factor(year))) +
geom_bar(stat = "identity", position = "dodge") +
scale_fill_manual(values = c("#29ABE2", "#217693")) +
geom_text(aes(label = y_label), position = position_dodge(0.9),
vjust = 1.5, color = "white", family = "Georgia")
plot <- plot +
scale_y_continuous(labels = scales::percent) +
scale_x_discrete(labels = c("Lower" = "Lower Class",
"Middle" = "Middle Class", "Upper" = "Upper Class")) +
labs(title = "Distribution of Adults by Income in Dayton, OH",
subtitle = "The percentage of adults in the middle class eroded by 5.3% from 2000 to 2014. Although a small \nfraction of these individuals moved into the upper class (+0.5%), the majority of these middle class \nindividuals moved into the lower income class (+4.8%).",
caption = "Source: Pew Research Center analysis of the \n2000 decennial census and 2014 American \nCommunity Survey (IPUMS)")
plot +
theme_minimal() +
theme(axis.title = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank(),
legend.position = c(1,1), legend.justification = c(1,1),
legend.background = element_blank(),
legend.direction="vertical",
text = element_text(family = "Georgia"),
plot.title = element_text(size = 18, margin = margin(b = 10)),
plot.subtitle = element_text(size = 10, color = "darkslategrey", margin = margin(b = 25)),
plot.caption = element_text(size = 8, margin = margin(t = 10), color = "grey70", hjust = 0),
legend.title = element_blank(),
legend.text.align = 2)
代码legend.text.align
的最后一行应该将文本从图例彩色框中移出,但似乎只适用于两者中的较低者。参见下图。谁能帮我吗?
编辑1:
我完全忘记了包含定义的data.frame。我现在已经更新了MWE,因此它实际上是具有以下代码行的WE
mwedata <- data.frame(Metro=c(rep("Dayton,OH",6)))
对不起,我很困惑。
答案 0 :(得分:1)
这有助于解决问题:
legend.title = element_blank()
中删除legend.text.align = 2
和theme()
fill = ""
添加到labs()
调试时好奇地观察:使用您的原始代码, just 更改字体系列,例如从“乔治亚州”到“开放Sans”,消除了图例中两个标签之间对齐的差异。