Laura Jonutytė
Laura Jonutytė

Reputation: 59

How to order a heatmap in R by x or y?

I've created a heatmap on temperatures by city. ggplot orders cities by default, from Z-A, not what I want. How can I change the code so that the cities would be ordered A-Z, how overall x and y can be ordered in ggplot ?

ggplot(Cities, aes(x = Month, y = City, fill = AvgTemp, frame = City)) +
  geom_tile(color = "white", size = 0.5) +
  scale_fill_gradient(name = "Average Temperature",low = "blue", high = "red") +
  coord_equal() +
  labs(x = "Month", y = "", title = "Average Temp") +
  theme_tufte() +
  theme(axis.ticks = element_blank()) +
  theme(axis.text = element_text(size = 15)) +
  theme(plot.title = element_text(size = 15)) +
  theme(legend.title = element_text(size = 10)) +
  theme(legend.text = element_text(size = 10)) 

Upvotes: 2

Views: 4881

Answers (1)

rafa.pereira
rafa.pereira

Reputation: 13827

I've included a reorder in your aes(y=).

 ggplot(data=Cities) +
   geom_tile( aes(x=Month, y=reorder(City, AvgTemp, median, order=TRUE), fill = AvgTemp), color = "white", size = 0.5) +
   scale_fill_gradient(name = "Average Temperature",low = "blue", high = "red") +
   coord_equal() +
   labs(x = "Month", y = "", title = "Average Temp") +
   theme_tufte()

Upvotes: 1

Related Questions