简体   繁体   English

在 R 中使用具有不同 x 轴组的 ggplot2 创建箱线图

[英]Creating boxplot in R with ggplot2 with different x-axis groups

I can't seem to wrangle the following data:我似乎无法整理以下数据:

https://i.stack.imgur.com/r4w6j.png

Year 2020   Year 2019   Year 2018
275 274 269
262 274 267
261 271 264
261 267 262
257 266 261
255 265 261
254 265 260
253 265 259
253 264 258

so that the x axis shows the Year of each box plot and y axis shows the values.这样 x 轴显示每个框 plot 的年份,y 轴显示值。 Each column is about 50 items long representing 50 different student-scores for that year每列大约有 50 个项目,代表当年 50 个不同的学生分数

I removed the whitespace from the column names.我从列名中删除了空格。

First, it's best to use tidyr::pivot_longer to convert the data in long form, as ggplot2 is designed to work with long form, rather than wide form data.首先,最好使用 tidyr::pivot_longer 来转换长格式数据,因为 ggplot2 设计用于处理长格式,而不是宽格式数据。

If you have a lot of columns, you can replace the cols=c("Year_2020", "Year_2019", "Year_2018") to everything()如果您有很多列,您可以将cols=c("Year_2020", "Year_2019", "Year_2018")everything()

    dat %>% 
tidyr::pivot_longer(cols=c("Year_2020", "Year_2019", "Year_2018"), names_to="year") %>% 
ggplot2::ggplot(aes(x=year, y=value)) + geom_boxplot()

在此处输入图像描述

You can also use reshape2::melt(data) to concert your data from wide to long form and then use ggplot您还可以使用 reshape2::melt(data) 将数据从宽格式变为长格式,然后使用 ggplot

In base R , it is easierbase R中,它更容易

boxplot(df1)

data数据在此处输入图像描述

df1 <- structure(list(Year2020 = c(275L, 262L, 261L, 261L, 257L, 255L, 
254L, 253L, 253L), Year2019 = c(274L, 274L, 271L, 267L, 266L, 
265L, 265L, 265L, 264L), Year2018 = c(269L, 267L, 264L, 262L, 
261L, 261L, 260L, 259L, 258L)), class = "data.frame", row.names = c(NA, 
-9L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM