2

I am trying to do the following. Consider the following dataset

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

I am trying to generate a heatmap. So far is good. That is relatively easy. For example I can use

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

and then

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

I know the labels on the x-axis are horizontal, but I know how to fix that. What I would like to have is to order the x-axis based on one specific rows. For example I would like to have the heatmap with the row "impact" (for example) values in ascending order. Anyone can point me in the right direction? Shoudl I convert the x in a factor and change the levels there?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Umberto
  • 1,387
  • 1
  • 13
  • 29

1 Answers1

3

Yes, you could convert it into factors and specify the levels. So to change it based on impact row we can do

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213