我使用dplyr和ggplot来创建热图。 (我过去曾使用过有用的类似包,但需要更多自定义。)剩下的一项任务是在热图中按行重排行。
在下面的简化示例中,我将如何排列行以便"很多"列从高到低?即,露营排在顶部,游泳将在下面?在现实生活中,有22行,所以我不想手动安排它们。
感谢您的帮助!
# not shown: use dplyr (gather, count, mutate) to create
# the following simplified data.frame in long format:
df <- tibble(
value = c("A little","A little","A lot","A lot","Don't know","Don't know", "Not at all","Not at all"),
Item = rep(c("Swimming","Camping"), 4),
percent = c(10, 14, 50, 83, 20, .25, 10, 3)
)
df
# manually set column order (non-alphabetical)
col_order <- c("Not at all", "A little", "A lot", "Don't know")
df$value <- factor(df$value, levels = col_order)
# plot results
p <- ggplot(df, aes(x = value,
y = Item)) +
geom_tile(aes(fill = percent)) +
geom_text(aes(label = paste0(round(percent, 0), sep = "%")),
size = 4, colour = "black") +
scale_fill_gradient(low = "#e5ebf0",
high = "#325f87",
limits = c(0, 100)) +
xlab("") +
ylab("") +
theme_tufte() # + additional customization
print(p)