在ggplot图中订购构面失败 [英] Ordering facets in a ggplot graph fails
本文介绍了在ggplot图中订购构面失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在ggplot2中遇到了无法理解的行为.
I'm experiencing behaviour in ggplot2 I cannot understand.
我正在尝试根据y轴的值对图形中的各个方面进行排序.如果我尝试根据x ="0"处的y轴的值对小平面进行排序,这是可行的,但是我尝试根据x ="4"处的y轴的值对小平面进行排序.没有得到期望的结果.
I am trying to sort facets in a graph according to values of the y-axes. This works if I try to order the facets according to the value of the y-axes at x = "0", however ordering according to the value of the y-axes at x = "4" does not give the desired result.
非常感谢所有帮助!
这是我的数据:
my_df <- structure(list(days_incubated = c(0L, 0L, 0L, 0L, 4L, 4L, 4L,
4L, 10L, 10L, 10L, 10L, 17L, 17L, 17L, 17L, 24L, 24L, 24L, 24L,
66L, 66L, 66L, 66L, 81L, 81L, 81L, 81L, 94L, 94L, 94L, 94L, 116L,
116L, 116L, 116L), jar = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 2L, 3L, 4L, 1L, 1L, 2L, 3L, 4L, 1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), co2 = c(15,
5, 50, 30, 2, 89, 14.0,
39.3, 1.2, 25.0, 10.27,
29.5, 5.54, 38.13, 27.33,
49.0, 28.62, 21.1, 24.0,
0.6, 1.04, 7.94, 1.2,
0.67, 1.9, 3.59, 4.92,
0.02, 13.2, 20.3, 21.52,
4.9, 6.6, 21.8, 12.28,
2.9)), row.names = c(NA, -36L), class = "data.frame")
这是图形的代码:
my_df %>%
group_by(days_incubated)%>%
mutate(co2_day0 = ifelse(days_incubated == 0, co2, NA),
jar = fct_reorder(factor(jar),
co2_day0,
mean,
na.rm = TRUE,
.desc = FALSE)) %>%
ggplot(aes(days_incubated, co2)) +
stat_summary(fun = mean) +
facet_wrap(vars(jar), scales = "free_y")
推荐答案
如果要进行所有计算而又不中断管道,则可以执行以下操作:
If you want to do all the calculations without breaking the pipe you could do :
library(dplyr)
library(ggplot2)
n <- 0
my_df %>%
mutate(jar = factor(jar,
jar[days_incubated == n][order(co2[days_incubated == n])])) %>%
ggplot(aes(days_incubated, co2)) +
stat_summary(fun = mean) +
facet_wrap(~jar, scales = "free_y")
使用 n = 4
n <- 4
my_df %>%
mutate(jar = factor(jar,
jar[days_incubated == n][order(co2[days_incubated == n])])) %>%
ggplot(aes(days_incubated, co2)) +
stat_summary(fun = mean) +
facet_wrap(~jar, scales = "free_y")
这篇关于在ggplot图中订购构面失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文