我有數據框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