为什么 ggplot2 geom_boxplot 无缘无故给出错误的顺序结果?
Why ggplot2 geom_boxplot gives wrong order results for no reason?
我一直在使用 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"))
因为你的月份就像因子,你只需要对因子重新排序。这里我使用了 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))
我一直在使用 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"))
因为你的月份就像因子,你只需要对因子重新排序。这里我使用了 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))