Search code examples
rggplot2heatmapaxes

How can I reorder the objects on the y-axis of my heatmap in ggplot?


This is what I have at the moment:

heat=read.csv("heat.csv")
head(heat)
heat$trap <- as.character(heat$trap)
class(heat$trap)
levels(heat$trap) <- c("T1", "T2", "T3", "T4","T5", "T6", "T7", "T8", "T9", "T10")

saeat <- ggplot(data = heat, mapping = aes(x = trip, y = trap, fill = sand)) + geom_tile() + ylab(label = "Trap") + xlab(label = "Month") + scale_fill_gradient(name = "Proportion of eggs", low = "#000033", high = "#FFFF33")
saeat

sand.heat <- veat + theme(strip.placement = "outside",plot.title = element_text(hjust = 0.5), axis.title.y = element_blank(), strip.background = element_rect(fill = "#EEEEEE", color = "#FFFFFF")) + ggtitle(label = "Sand treatment") + scale_y_discrete(breaks=c("T1", "T2", "T3", "T4","T5", "T6", "T7", "T8", "T9", "T10"))

swallows.heat

Here's an image of the heatmap, with the y-axis not aligned properly

I'm not able to find a way to order my y-axis in this manner: T1 to T10. But T10 winds up right after T1. Any suggestions for how I can change this?


Solution

  • I'm not sure if works with a character variable in the same way, but if you use a factor variable you can reorder the levels in the way you want it.

    # make a factor variable
    heat$trap <- as.factor(heat$trap)
    
    # check the current levels
    levels(heat$trap)
    [1] "T1"  "T10" "T2"  "T3"  "T4"  "T5"  "T6"  "T7"  "T8"  "T9"
    
    # reorder the levels
    heat$trap <- factor(heat$trap, levels = levels(heat$trap)[c(1, 3:10, 2)])
    
    # check the correct order
    levels(heat$trap)
    [1] "T1"  "T2"  "T3"  "T4"  "T5"  "T6"  "T7"  "T8"  "T9"  "T10"