在热图中排列行(ggplot geom_tile)

时间:2017-10-30 16:07:23

标签: r ggplot2 dplyr rows heatmap

我使用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)

enter image description here

1 个答案:

答案 0 :(得分:2)

列类似,您可以在绘图之前将列转换为一个因子,levels的排列项为 A很多 按升序排列;

ggplot行之前添加此内容:

a_lot = df[df$value == 'A lot',]
df$Item = factor(df$Item, levels = a_lot$Item[order(a_lot$percent)])

给出:

enter image description here