[英]Creating boxplot in R with ggplot2 with different x-axis groups
我從列名中刪除了空格。
首先,最好使用 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.