r - 在面板/绘图之外添加变量名称
问题描述
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)
解决方案
根据 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"))
推荐阅读
- python - Flask PyMongo HTML 显示读取数据
- php - 根据php中的数组项循环替换字符串
- javascript - 如何将html与js分开?
- java - 已解决 [org.springframework.beans.TypeMismatchException String:无法将“java.lang.String”类型的值转换为所需类型
- vapor - Vapor 4 中的原始查询
- java - 汇编程序快速排序比 java array.sort 慢?
- wpf - 我如何在开始菜单中制作一个包含多个应用程序的安装程序(就像微软一样)
- ssl - Ansible,如何信任证书?
- python - 具有大稀疏矩阵的大循环的 Python 3 内存错误
- terraform-provider-aws - Terraform 错误 - 错误:需要参数或块定义