【问题标题】:Why ggplot2 geom_boxplot gives wrong order results for no reason?为什么 ggplot2 geom_boxplot 无缘无故给出错误的订单结果?
【发布时间】:2019-05-30 20:31:03
【问题描述】:

我一直在使用 ggplot2 和 geom_boxplot 在一张图中绘制多个箱线图。数据如下所示。

Month   Rainfall

1         45
1         12
1         14
2         65
2         45
2         78
3         10
3         35
3         92
.         .
.         .
.         .

因此,通过使用箱线图,我想查看每个组(1、2、3...)的降雨量值的箱线图。我得到的结果很奇怪,订单似乎一团糟。有什么帮助吗?

ggplot(data=edit3)+geom_boxplot(aes(x=Month, y=Rainfall))

注意:edit3 是具有 Rainfall 和 Month 值的数据框。

dput(head(edit3[,c("Month","Rainfall")],9))
structure(list(Month = c("1", "1", "1", "1", "1", "1", "1", "1", 
"2"), Rainfall = c(NA, 135.6, 34.2, 39.4, 134.6, 234.6, 69.6, 
92.8, NA)), row.names = c(NA, -9L), class = c("tbl_df", "tbl", 
"data.frame"))

【问题讨论】:

  • 月份按字典顺序排列,很可能是因为该列是一个字符或一个因子。将其转换为数字列。
  • 不确定最好的副本是什么,可能是this 或者可能是this
  • 我刚刚使用edit3$Month <- as.integer(edit3$Month) 进行了尝试,结果只是Rainfall 总值的一个箱线图。有什么建议吗?
  • 并非没有实际可重现的示例。但我可以 100% 肯定地告诉您,您看到的排序是因为该列最初是一个字符或因素。如果这是一个因素,那么as.integer 不一定会按照您想要的方式转换它。看看我的第二个链接。
  • 啊,你去吧,你可以用整数 x 轴,你只需要指定group = Month

标签: r ggplot2 boxplot


【解决方案1】:

因为您的月份就像因子一样,您只需对因子重新排序即可。这里我使用了forcats 包。

library(dplyr)
library(forcats)

edit31_1 <- edit3 %>% 
  dplyr::mutate(Month = forcats::fct_inorder(Month))

ggplot2::ggplot(edit31_1) +
  geom_boxplot(aes(x = Month, y = Rainfall))


  • 使用的虚构数据:
library(ggplot2)

set.seed(1)
edit3 <- data.frame(Month = as.factor(rep(paste(seq(1, 12, 1)), 3)),
                    Rainfall = rnorm(n = 36, mean = 60, sd = 30))

ggplot2::ggplot(edit3) +
  geom_boxplot(aes(x = Month, y = Rainfall))

【讨论】:

    猜你喜欢
    • 2013-02-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多