在 panel/plot 之外添加变量名称

Adding variable name outside of panel/plot

样本数据:

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

我有很多不同的变量,我想用下面的代码为每个变量绘制一个箱线图。为了让所有面板都具有相同的大小,我确定了绘图边距,使其不受变量名称长度的影响。因此,现在我想将面板外的变量名添加到左侧。 然而,事实证明这比预期的要困难。我知道之前有人提出过这个问题,但是 none 的解决方案适用于我(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)

根据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"))