1

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?

r2evans
  • 141,215
  • 6
  • 77
  • 149
kittenbuns
  • 55
  • 6
  • 1
    Ordering is being done lexicographically, where `"T10"` comes before `"T2"`. Any question on SO that asks about ordering things on the axis comes down to this: convert that y-axis variable to a factor and force the levels, as `factor(..., levels=...)`. – r2evans May 23 '20 at 13:55

1 Answers1

1

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"
starja
  • 9,887
  • 1
  • 13
  • 28
  • 1
    Hard-coding the indices like that is a bit fragile. I'd recommend finding a way to do it programmatically, such as `levels(heat$trap)[ order(as.integer(gsub("\\D", "", levels(heat$trap)))) ]`. – r2evans May 23 '20 at 13:58
  • Thanks- this worked really well! – kittenbuns May 23 '20 at 14:38