Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Heatmap of world Temperature in r package for ggplot2
#This is inspired by this piral animation of the same dataset
#http://www.climate-lab-book.ac.uk/2016/spiralling-global-temperatures/
#and this R code to produce the animation
#https://gist.github.com/jebyrnes/b34930da0052a86f5ffe254ce9900357
# It also uses elements of this http://www.r-bloggers.com/making-faceted-heatmaps-with-ggplot2/
# and this https://rpubs.com/bradleyboehmke/weather_graphic graphic
library(dplyr)
library(tidyr)
library(ggplot2)
library(animation)
library(viridis)
library(scales)
library(ggthemes)
#Data explanation at https://crudata.uea.ac.uk/cru/data/temperature/
#r code to read data https://crudata.uea.ac.uk/cru/data/temperature/read_cru_hemi.r
# data https://crudata.uea.ac.uk/cru/data/temperature/HadCRUT4-gl.dat
#As well as data read in script
source("read_cru_hemi.r")
temp_dat <- read_cru_hemi("./HadCRUT4-gl.dat")
#remove cover
temp_dat_monthly <- temp_dat %>%
select(-starts_with("cover")) %>%
select(-starts_with("annual")) %>%
gather(month, anomaly, -year) %>%
mutate(month = gsub("month\\.", "", month)) %>%
mutate(month = as.numeric(month)) %>%
filter(year !=2016)
dgr_fmt <- function(x, ...) {
parse(text = paste(x, "", sep = ""))
}
a <- dgr_fmt(seq(1850,2015, by=30))
gg <- ggplot(temp_dat_monthly, aes(x=month, y=year, fill=anomaly))
gg <- gg + geom_tile(color="white", size=0.1)
gg <- gg + scale_fill_viridis(name="Difference from \nAverage in °C",option="inferno")
plot.title = 'Average World Temperature since 1850'
plot.subtitle = 'Data is HadCRUT4-gl from crudata'
gg <- gg + ggtitle(bquote(atop(.(plot.title), atop(italic(.(plot.subtitle)), ""))))
gg <- gg + labs(x=NULL, y=NULL)
gg <- gg + theme_tufte(base_family="Helvetica")
gg <- gg +
coord_cartesian(ylim = c(1850,2015)) +
scale_y_continuous(breaks = seq(1850,2015, by=30), labels = a) +
scale_x_continuous(expand = c(0, 0),
breaks = c(1,2,3,4,5,6,7,8,9,10,11,12),
labels = c("Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"))
gg <- gg + theme(plot.title=element_text(hjust=0))
gg <- gg + theme(axis.ticks=element_blank())
gg <- gg + theme(axis.text=element_text(size=7))
ggsave("heat.png")
@parsashams

This comment has been minimized.

Copy link

@parsashams parsashams commented Jun 15, 2016

beautiful plot!

@arvi1000

This comment has been minimized.

Copy link

@arvi1000 arvi1000 commented Jun 15, 2016

Underused tip: instead of writing out the months in lines 42-44, you can use the built-in constant month.abb

@cavedave

This comment has been minimized.

Copy link
Owner Author

@cavedave cavedave commented Apr 13, 2020

ughpnln124b41

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment