簡體   English   中英

在 R 中使用具有不同 x 軸組的 ggplot2 創建箱線圖

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

我似乎無法整理以下數據:

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

這樣 x 軸顯示每個框 plot 的年份,y 軸顯示值。 每列大約有 50 個項目,代表當年 50 個不同的學生分數

我從列名中刪除了空格。

首先,最好使用 tidyr::pivot_longer 來轉換長格式數據,因為 ggplot2 設計用於處理長格式,而不是寬格式數據。

如果您有很多列,您可以將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()

在此處輸入圖像描述

您還可以使用 reshape2::melt(data) 將數據從寬格式變為長格式,然后使用 ggplot

base R中,它更容易

boxplot(df1)

數據在此處輸入圖像描述

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