r - 如何使用 ggplot 制作此箱线图?
问题描述
我需要使用 ggplot 创建一个图形,但我只能使用基础 R 创建它。
这是我正在做的一项调查。可变分数范围从 0 到 100。
这是我使用 R Base 创建的箱线图: Boxplot
#My data looks like this:
Gender <- c("Man", "Man", "Woman", "Woman", "Man", "Woman", "Woman", "Man", "Woman", "Man")
V1 <- c(85, 100, 80, 70, 85, 85, 80, 70, 100, 80)
V2 <- c(92, 92, 84, 78, 80, 94, 100, 94, 100, 94)
V3 <- c(86, 80, 60, 53, 80, 73, 80, 73, 86, 93)
V4 <- c(80, 70, 20, 40, 60, 20, 100, 40, 60, 20)
V5 <- c(100, 90, 100, 80, 100, 100, 100, 100, 100, 100)
boxplot(Dados$V1, Dados$V2, Dados$V3, Dados$V4, Dados$V5, data = Dados,
horizontal = F, main = NULL, ylab = NULL, names = c("Sexismo", "LGBTfobia", "AmbUniver", "GenSexEns", "Valores"),
col = c("darkred", "darkolivegreen4", "yellow3", "purple4", "darkorange3"),
cex.lab = 1.9, cex.axis = 2.7, cex = 1.5, cex.main = 2.8, lwd = 3, lty = "solid", bty = 7)
如何使用 ggplot 做到这一点?我不能,因为我不能像在基础 R 上的箱线图那样将 Vs 放在 x 轴上。我怎么能在 ggplot 中将男人和女人并排放置,因为它们也是组件同一个变量“性别”?
有谁能够帮我?
解决方案
您可以使用将数据转换为长格式tidyr::pivot_longer
library(tidyr)
library(ggplot2)
df %>%
pivot_longer(-Gender) %>%
ggplot(aes(name, value))+
geom_boxplot(aes(fill = name, colour = Gender), position = position_dodge2(width = 0.9))+
scale_colour_manual(breaks = c("Woman", "Man"),
values = c("green", "gray30"))+
scale_fill_manual(breaks = c("V1", "V2", "V3", "V4", "V5"),
values = c("darkred", "darkolivegreen4", "yellow3", "purple4", "darkorange3"))+
scale_x_discrete(labels = c("Sexismo", "LGBTfobia", "AmbUniver", "GenSexEns", "Valores"))+
guides(fill = 'none') +
theme(legend.position = "bottom")
由reprex 包于 2021-09-23 创建 (v2.0.0 )
数据
Gender <- c("Man", "Man", "Woman", "Woman", "Man", "Woman", "Woman", "Man", "Woman", "Man")
V1 <- c(85, 100, 80, 70, 85, 85, 80, 70, 100, 80)
V2 <- c(92, 92, 84, 78, 80, 94, 100, 94, 100, 94)
V3 <- c(86, 80, 60, 53, 80, 73, 80, 73, 86, 93)
V4 <- c(80, 70, 20, 40, 60, 20, 100, 40, 60, 20)
V5 <- c(100, 90, 100, 80, 100, 100, 100, 100, 100, 100)
df <- data.frame(Gender, V1, V2, V3, V4, V5)
推荐阅读
- python - 使用 Python 和 OpenCV 将捕获的图像保存到 MySQL 数据库
- c++ - 如何在双向链表的网格中旋转列
- c# - C# winforms .net 4.7 内存限制
- assembly - 如何使用 ADD 在汇编中左移,而不使用 SHL?
- json - 通过 Curl 检索问题数据的 Jira Rest API:语法问题
- python - 从压缩文件夹内的文件夹中读取 H5File 到 pandas 数据帧
- c++ - 如何保存向量中的位置以供以后插入?
- oracle - 列出列值更改的行
- python - 根据它们的存在更新 mongo 中的多个字段
- python - 如何在python中按索引比较两个列表?