我有数据框df
,有46行和3列。基于一个因子水平的值对ggplot2图进行重新排序
我想通过program_ID
变量创建一个youth_activity_rc
变量的值的图,如此代码/图。 。 。
library(ggplot2)
ggplot(df, aes(x = program_name, y = total_minutes_p, group = youth_activity_rc, fill = youth_activity_rc)) +
geom_col(position = position_stack(reverse = T)) +
coord_flip()
。 。 。但随着program_ID
变量重新排序的youth_activity_rc
变量Not Focused
因子水平值的基础上:
有许多的演示如何做到这一点的单一变量的基础上的问题(即this question),但根据与某个因素水平相关的价值(本例中为Not Focused
),我无法找到这样的结果;这似乎很简单,但至少根据其他答案中推荐的解决方案(即使用stats::reorder()
或dplyr::arrange()
),它不是。
的数据是在这里:
df <- structure(list(program_ID = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L,
5L, 5L, 5L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L,
8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L), .Label = c("1", "2", "4", "5",
"6", "7", "8", "9", "10"), class = "factor"), youth_activity_rc = structure(c(2L,
6L, 5L, 1L, 3L, 2L, 6L, 1L, 3L, 2L, 6L, 5L, 1L, 3L, 2L, 6L, 4L,
5L, 1L, 3L, 2L, 6L, 5L, 1L, 3L, 2L, 6L, 1L, 3L, 2L, 6L, 4L, 1L,
3L, 2L, 6L, 4L, 5L, 1L, 3L, 2L, 6L, 4L, 5L, 1L, 3L), .Label = c("Not Focused",
"Basic Skills Activity", "Program Staff Led", "Field Trip Speaker",
"Lab Activity", "Creating Product"), class = "factor"), total_minutes_p = c(0.248,
0.116, 0.075, 0.458, 0.103, 0.466, 0.015, 0.202, 0.317, 0.248,
0.263, 0.006, 0.372, 0.111, 0.183, 0.172, 0.088, 0.048, 0.305,
0.203, 0.157, 0.066, 0.079, 0.592, 0.106, 0.128, 0.423, 0.423,
0.026, 0.176, 0.233, 0.125, 0.426, 0.04, 0.164, 0.188, 0.046,
0.007, 0.524, 0.072, 0.163, 0.112, 0.013, 0.021, 0.567, 0.124
)), .Names = c("program_ID", "youth_activity_rc", "total_minutes_p"
), row.names = c(NA, -46L), vars = "program_ID", labels = structure(list(
program_ID = c(1, 2, 4, 5, 6, 7, 8, 9, 10)), .Names = "program_ID", row.names = c(NA,
-9L), class = "data.frame", vars = "program_ID", drop = TRUE), indices = list(
0:4, 5:8, 9:13, 14:19, 20:24, 25:28, 29:33, 34:39, 40:45), drop = TRUE, group_sizes = c(5L,
4L, 5L, 6L, 5L, 4L, 5L, 6L, 6L), biggest_group_size = 6L, class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
任何直接的方式,如果不'Focused'没有发生来做到这一点“youth_activity_rc”的第一个级别,而不是将其设置为第一级? –
不是我所知道的,但是如果您不想永久性地改变您的订购因子的水平,可以在'arrange'内完成。请参阅编辑。 – aosmith