首页 > 解决方案 > 到图例文本ggplot的距离

问题描述

我试图在图例框(指示器)和图例文本之间拉开一点距离。我有一个改编自这个惊人页面的代码。这是我的 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)))

我很抱歉造成混乱..

带有调整图例文本的最终图表

标签: rggplot2themeslegend

解决方案


这有助于解决问题:

  1. 删除legend.title = element_blank()legend.text.align = 2theme()
  2. 添加fill = ""labs()

调试时的好奇观察:使用您的原始代码,只需更改字体系列,例如从“Georgia”更改为“Open Sans”,即可消除图例中两个标签之间对齐的差异。



推荐阅读