Daniel
Daniel

Reputation: 435

Arrange rows in heatmap (ggplot geom_tile)

I'm using dplyr and ggplot to create heatmaps. (I've used the useful -likert- package in the past, but want more customization.) The one remaining task to do is rearrange rows by one column in the heatmap.

In the simplified example below, how would I arrange the rows so that the "A lot" column descends from high to low? I.e., The Camping row would be at the top, and Swimming would be underneath? In real life, there are 22 rows, so I don't want to arrange them manually.

Thanks for your help!

# 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

Upvotes: 2

Views: 5017

Answers (1)

akuiper
akuiper

Reputation: 215117

Similar to the value column, you can convert the Item column to a factor before plotting, where the levels is arranged Item for A lot with percent in ascending order;

Add this before ggplot line:

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

gives:

enter image description here

Upvotes: 2

Related Questions