Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 为什么ggplot2 geom_箱线图无缘无故给出错误的顺序结果?_R_Ggplot2_Boxplot - Fatal编程技术网

R 为什么ggplot2 geom_箱线图无缘无故给出错误的顺序结果?

R 为什么ggplot2 geom_箱线图无缘无故给出错误的顺序结果?,r,ggplot2,boxplot,R,Ggplot2,Boxplot,我一直在使用ggplot2和geom_boxplot在一个图形中绘制多个boxplot。数据看起来像下面的thst Month Rainfall 1 45 1 12 1 14 2 65 2 45 2 78 3 10 3 35 3 92 . . . . . . 因此,通过使用箱线图,我希望看到每组(1

我一直在使用ggplot2和
geom_boxplot
在一个图形中绘制多个boxplot。数据看起来像下面的thst

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是带有降雨量和月份值的数据框


因为你的月份就像因素一样,你只需要对因素重新排序。在这里,我使用了
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))
库(dplyr)
图书馆(供猫用)
编辑31_1%
dplyr::mutate(月=forcats::fct_顺序(月))
ggplot2::ggplot(编辑31_1)+
geom_箱线图(aes(x=月,y=降雨量))


  • 使用的虚构数据:
库(ggplot2)
种子(1)

edit3月份按字典顺序排列,很可能是因为该列是字符或因子。将其转换为数字列。不确定最好的副本是什么,可能,或者可能,我只是使用
edit3$Month尝试了这一点,但没有实际的可复制示例。但我可以百分之百肯定地告诉你,你看到的排序是因为该列最初是一个字符或因子。如果它是一个因子,那么
as.integer
不一定会按您想要的方式转换它。这是我的第二个链接。啊,你可以使用整数x轴,你只需要指定
group=Month
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"))
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))