首页 > 解决方案 > 如何使用 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 中将男人和女人并排放置,因为它们也是组件同一个变量“性别”?

有谁能够帮我?

标签: rggplot2boxplot

解决方案


您可以使用将数据转换为长格式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)

推荐阅读