首页 > 解决方案 > 在面板/绘图之外添加变量名称

问题描述

这就是绘图的外观,我要添加的文本应该在左侧面板之外样本数据:

df <- data.frame("SL" = runif(50, 2.2, 5.8), "LMX" = runif(50, 1.8, 5.5))

我有许多不同的变量,我想用下面的代码制作一个箱形图。为了使所有面板都具有相同的大小,我确定了绘图边距,使其不受变量名称长度的影响。因此,现在我想在左侧面板之外添加变量名。然而,事实证明这比预期的要困难得多。我知道这个问题之前已经提出过,但没有一个解决方案适用于我(rnorm 或 geom_text)。非常感谢任何帮助,谢谢:)

df %>%
select("Servant Leadership" = SL) %>%
gather(key = "variable", value = "value") -> n
n$variable <- factor(n$variable, levels = c("Servant Leadership"))


ggplot(data = n, aes(y = value, x = as.numeric(variable))) +
stat_summary(fun.data = min.mean.sd.max, geom = "boxplot", col = "#323232", fill = "#EFC76C") + 
scale_fill_identity() + 
scale_x_continuous(breaks = as.numeric(unique(n$variable)), minor_breaks = NULL,
                 labels = "", expand = c(0.12, 0.12)) + 
scale_y_continuous(breaks = c(1, 2, 3, 4, 5, 6, 7)) +
expand_limits(y = c(1, 7)) + coord_flip() + labs(x = "", y = "") +
theme(text = element_text(size = 15), panel.background = element_rect(fill = "#EAEDED"), 
    panel.border = element_rect(fill=NA, color = "grey", size = 0.5, linetype = "solid")) +
theme(plot.margin=unit(c(0.2, 0.2, 0, 4),"cm"))

我忘记了之前运行的这段代码:

min.mean.sd.max <- function(x) {
r <- c(min(x), mean(x) - sd(x), mean(x), mean(x) + sd(x), max(x))
names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
r
}

这是我使用的包(可能不是全部在这段代码中):

library(reshape)
library(scales)
library(ggplot2)
library(dplyr)
library(tidyr)

标签: rggplot2annotategeom-text

解决方案


根据 Tung 的回答,我通过以下方式修改了箱线图的代码:

ggplot(data = n, aes(y = value, x = as.numeric(variable))) +
stat_summary(fun.data = min.mean.sd.max, geom = "boxplot", col = "#323232", fill = "#EFC76C") + 
scale_fill_identity() + 
scale_x_continuous(breaks = as.numeric(unique(n$variable)), minor_breaks = NULL,
                 labels = "", expand = c(0.12, 0.12)) + 
scale_y_continuous(breaks = c(1, 2, 3, 4, 5, 6, 7)) +
expand_limits(y = c(1, 7)) + coord_flip(clip = "off") + labs(x = "", y = "") +
theme(text = element_text(size = 18), panel.background = element_rect(fill = "#EAEDED"), 
    panel.border = element_rect(fill=NA, color = "grey", size = 0.5, linetype = "solid")) +
geom_text(x = 1, y = 0.5, inherit.aes = FALSE, label = "Servant Leadership", check_overlap = TRUE, hjust = 1, 
        fontface = 'plain', size = 6, color = "#4E4E4E") +
theme(plot.margin=unit(c(0.05, 4.5, 0, 9.5),"cm"))

添加变量名称,绘图区域保持不变,不随名称长度变化


推荐阅读