根据某一特定行订购热图

时间:2018-11-22 07:33:45

标签: r ggplot2 heatmap

我正在尝试执行以下操作。考虑以下数据集

trends <- c('Virtual Assistant', 'Citizen DS', 'Deep Learning', 'Speech Recognition', 
          'Handwritten Recognition', 'Machine Translation', 'Chatbots', 
          'NLP')

impact <- sample(5,8, replace = TRUE)
maturity <- sample(5,8, replace = TRUE)
strategy <- sample(5,8, replace = TRUE)
h <- sample(5,8, replace = TRUE)

df <- data.frame(trends, impact, maturity, strategy, h)
rownames(df) <- df$trends

我正在尝试生成热图。到目前为止很好。那比较容易。例如,我可以使用

dftemp = df[,c("impact", "maturity", "strategy", "h")]
dt2 <- dftemp %>%
  rownames_to_column() %>%
  gather(colname, value, -rowname)

然后

ggplot(dt2, aes(x = rowname, y = colname, fill = value)) +
  geom_tile()

我知道x轴上的标签是水平的,但我知道如何解决。我想要的是基于一个特定的行对x轴进行排序。例如,我想使热图的行“ impact”(例如)值按升序排列。任何人都可以指出正确的方向吗? 我应该将x转换为因子并在那里更改水平吗?

1 个答案:

答案 0 :(得分:3)

是的,您可以将其转换为因子并指定级别。因此,我们可以根据impact行进行更改

dt2$rowname <- factor(dt2$rowname, levels = df$trends[order(df$impact)])

library(ggplot2)
ggplot(dt2, aes(x = rowname, y = colname, fill = value)) +
    geom_tile()

enter image description here