【发布时间】:2017-06-14 04:48:04
【问题描述】:
我有数据框df,有 46 行和 3 列。
我正在尝试通过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"))
【问题讨论】: