如何根据列的值订购 ggplot 热图?

How can I order a ggplot heatmap based on the value of a column?

以下 R 代码段

library(ggplot2)
library(reshape2)

data <- data.frame(
          item  = c('foo', 'bar', 'baz'),
          val_1 = c(   7 ,    9 ,    3 ),
          val_2 = c(   1 ,    2 ,    3 )
        );

data

data$tot = data$val_1 + data$val_2;

data.molten = melt(data);

ggplot(
   data = data.molten,
   aes(x = variable, y = item ))  +
   geom_tile(aes(fill  = value))  +
   geom_text(aes(label = value))

产生

是否可以按 tot 的值降序排列,使 bar 的行在顶部,baz 的行在底部。

添加这一行:

data$item <- reorder(data$item,data$tot)

melting 之前。

关于这个主题的规范 Whosebug 问题是 here,答案基本上总是 "set the factor levels in the desired order",但在实践中如何做到这一点可能因情况而异,其方式略有超出单个 Whosebug 答案的范围。

您可以在 ggplot() 中的 aes() 中使用 reorder()

像这样...

    ggplot(
       data = data.molten,
       aes(x = variable, y = reorder(item, value), fill = value)  +
       geom_tile()+
       geom_text(aes(label = value))