gpt4 book ai didi

r - 如何根据 R ggplot2 中的 y 轴值重新排序 x 轴

转载 作者:行者123 更新时间:2023-12-04 14:12:28 26 4
gpt4 key购买 nike

我正在尝试根据 y 轴的平均值对错误图上的 x 轴重新排序(我不介意它是升序还是降序)。我应用了基于 this post 的解决方案,但是出于某种原因,它似乎忽略了 reorder 命令。知道这里发生了什么吗?

enter image description here

#Import data.
df <- structure(list(X_Variable = c(4L, 4L, 13L, 18L, 12L, 3L, 15L,
NA, 18L, 4L, 17L, NA, 3L, 15L, 4L, 6L, 12L, NA, 2L, 1L, NA, 15L,
1L, 6L, 1L, 12L, NA, 6L, NA, 15L, NA, 1L, 7L, 15L, 11L, NA, NA,
1L, 1L, 7L, 2L, 2L, 12L, 11L, 15L, 17L, 1L, 4L, 11L, 15L, 2L,
3L, 13L, 17L, 15L, 6L, 3L, 14L, 12L, 8L, 12L, 11L, NA, 2L, 11L,
NA, 4L, 8L, 15L, 4L, 7L, 8L, 15L, 15L, 15L, 6L, 3L, 6L, 8L, 15L,
4L, 2L, 1L, 1L, 7L, 17L, 15L, 1L, NA, 5L, 13L, 1L, 15L, 4L, 15L,
13L, 18L, 1L, 15L, 6L, NA, 6L, NA, 6L, 1L, 16L, 4L, 1L, NA, 2L,
12L, NA, 7L, 2L, 15L, 13L, 13L, 16L, NA, 7L, 2L, 4L, 15L, 11L,
15L, 2L, 5L, 13L, 2L, 9L, 7L, 6L, 15L, 15L, 11L, 3L, 15L, 13L,
NA, 4L, 8L, NA, 4L, 8L, 18L, 4L, 1L, 8L, 5L, 18L), Y_Variable = c(6L,
4L, 5L, 4L, 4L, 3L, 7L, 1L, 1L, 7L, 4L, NA, 5L, 1L, 6L, 1L, 6L,
3L, 6L, 4L, NA, 4L, 6L, 5L, 1L, 4L, 1L, 1L, 6L, 3L, 4L, 1L, 1L,
2L, 3L, 4L, 4L, 2L, 2L, 2L, 4L, 1L, 1L, 5L, 4L, 1L, 4L, 4L, 3L,
3L, 2L, 2L, 1L, 3L, NA, 2L, 4L, 1L, 2L, 2L, 6L, 3L, NA, 2L, 2L,
NA, 4L, 2L, 3L, 6L, 5L, 4L, 1L, 5L, 3L, 1L, 4L, 6L, 1L, 5L, 4L,
2L, 1L, 5L, 4L, 3L, 2L, NA, 4L, 2L, NA, 4L, 5L, 5L, 4L, 2L, 1L,
5L, 2L, 2L, 4L, 1L, 4L, 1L, 5L, 2L, 1L, 3L, NA, 2L, 2L, 2L, 5L,
1L, 1L, 4L, 2L, 2L, NA, 3L, 5L, 7L, 1L, 1L, 1L, 1L, 4L, 1L, 2L,
2L, 3L, 3L, 3L, 4L, 1L, 4L, 3L, 4L, 3L, 6L, 1L, 5L, 4L, 2L, 5L,
2L, 3L, 1L, 1L, 2L)), row.names = c(NA, -150L), class = "data.frame")

#Error plot ordered by Y-Variable.
ggplot(df, aes(x=reorder(X_Variable, Y_Variable, FUN=mean), y=Y_Variable))+
geom_point(stat="summary", fun.y="mean")+
geom_errorbar(stat="summary", fun.data="mean_se", fun.args=list(mult=1.96), width=0.1)

最佳答案

我只先删除了缺失值。减号在我的机器上工作正常。

df1<-df %>% 
filter(!is.na(X_Variable), !is.na(Y_Variable))

ggplot(df1, aes(x=reorder(X_Variable, -Y_Variable, FUN=mean), y=Y_Variable))+
geom_point(stat="summary", fun.y="mean")+
geom_errorbar(stat="summary", fun.data="mean_se", fun.args=list(mult=1.96), width=0.1)

编辑:由于缺少值,X_Variable 1、13 和 15 排在最后。希望这会有所帮助。

df %>% group_by(X_Variable) %>% 
summarise(
Y_Variable = mean(Y_Variable)) %>%
arrange(Y_Variable)

# A tibble: 18 x 2
X_Variable Y_Variable
<int> <dbl>
1 4 4.71
2 3 3.67
3 12 3.57
4 7 3.29
5 17 2.75
6 18 2.6
7 11 2.57
8 2 2.55
9 5 2.33
10 6 2.3
11 9 2
12 16 2
13 8 1.86
14 14 1
15 1 NA
16 13 NA
17 15 NA
18 NA NA
>

enter image description here

关于r - 如何根据 R ggplot2 中的 y 轴值重新排序 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63165943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com