R语言 如何根据分类变量分割这些箱线图?

6ju8rftf  于 2023-06-27  发布在  其他
关注(0)|答案(2)|浏览(135)

请问我如何将这四个中的每一个分配到两个包含男性和女性脉搏计的箱形图中。

islands = read.csv('Data.csv')boxplot(islands$Pulse.meter.First..0m, islands$Pulse.meter.25m, islands$Pulse.meter.Second..0m, islands$Pulse.meter.25m.1)

比如

boxplot(islands$Pulse.meter.25m ~ islands$Sex)

可以区分它们,但不能同时为其中四个工作。
我现在有一个这样的boxplot:

我想要一个像这样的箱线图:

toe95027

toe950271#

这里有一个使用随机数据的例子,因为你没有提供数据下载。关键是首先将数据从“宽”格式转换为“长”格式,因为您目前拥有的数据每个值都有一列,其中所有值都在同一列中,并且有一个额外的标签列。然后,interaction函数可用于创建脉搏计类型和性别之间的交互。

# example data with random values
islands <- data.frame(Sex = rep(c('Male', 'Female'), 15),
                      Pulse.meter.First..0m = rnorm(30, mean = 2),
                      Pulse.meter.25m = rnorm(30, mean = 1),
                      Pulse.meter.Second..0m = rnorm(30, mean = 3),
                      Pulse.meter.25m.1 = rnorm(30, mean = 4))
                      
# reshape from wide to long
islands_long <- reshape(islands,
                        direction = "long",
                        varying = 2:5,
                        v.names = "value",
                        times = names(islands)[2:5],
                        timevar = 'measurement')

# plot the boxplot, 'cex.axis' decrease the font size so all the x-axis labels are visible
boxplot(value ~ interaction(Sex, measurement), data = islands_long, pars=list(cex.axis=0.5))

这产生:

igsr9ssn

igsr9ssn2#

library(ggplot2)
library(dplyr)
library(tidyverse)

df <- data.frame(
  Gender = sample(c("Male", "Female"), 20, replace = TRUE),
  Pulse.meter.First..0m  = sample(10:60, 20, replace = FALSE),
  Pulse.meter.25m  = sample(30:60, 20, replace = FALSE),
  Pulse.meter.Second..0m = sample(30:60, 20, replace = FALSE),
  Pulse.meter.25m.1  = sample(10:60, 20, replace = FALSE)
)

df <- df %>%
  group_by(Gender) %>%
  pivot_longer(cols = Pulse.meter.First..0m:Pulse.meter.25m.1, names_to = "Pulse_meter", values_to = "Count") %>%
  unite("Groups", Gender:Pulse_meter)


df$Groups <- factor(df$Groups, levels=c("Female_Pulse.meter.First..0m", "Male_Pulse.meter.First..0m",
                                        "Female_Pulse.meter.25m","Male_Pulse.meter.25m",
                                        "Female_Pulse.meter.Second..0m","Male_Pulse.meter.Second..0m",
                                        "Female_Pulse.meter.25m.1","Male_Pulse.meter.25m.1"))
 

ggplot(data = df, aes(x= Groups, y = Count)) +
  geom_boxplot() +
  scale_x_discrete(labels=c("(F,0m)","(M,0m)","(F,25m)","(M,25m)", "(F,second_0m)", "(M,second_0m)",
                            "(F,25m.1)","(M,25m.1)")) +
  labs(y="Counts") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

相关问题