简体   繁体   中英

R heat map of annual time series by entire year

I am trying to make a heatmap of several years of daily averages of salinity in an estuary in R.

I would like the format to include month on the x-axis and year on the y-axis, so each Jan 1st directly above another Jan. 1st. In other words, NOT like a typical annual calendar style (not like this: http://www.r-bloggers.com/ggplot2-time-series-heatmaps/ ).

So far I have only been able to plot by the day of the year using:

{r} d <- read.xlsx('GC salinity transposed.xlsx', sheetName = "vert-3", header = TRUE, stringsAsFactors = FALSE, colClasses = c("integer", "integer", "numeric"), endRow = 2254)

{r} ggplot(d, aes(x = Day.Number, y = Year)) + geom_tile(aes(fill = Salinity)) + scale_fill_gradient(name = 'Mean Daily Salinity', low = 'white', high = 'blue') + theme(axis.title.y = element_blank())

And get this: heat map not quite right

Could someone please tell me a better way to do this - a way that would include month, rather than day of the year along the x-axis? Thank you. New to R.

The lubridate package comes in handy for stuff like this. Does this code do what you want? I'm assuming you only have one salinity reading per month and there's no need to average across multiple values in the same month.

library(lubridate)
library(ggplot2)

# Define some data
df <- data.frame(date = seq.Date(from = as.Date("2015-01-01"), by = 1, length.out = 400),
                 salinity = runif(400, min=5, max=7))
# Create fields for plotting
df$day <- paste0(ifelse(month(df$date)<10,"0",""),
                 month(df$date),
                 "-",
                 ifelse(day(df$date)<10,"0",""),
                 day(df$date))
df$month <- paste0(ifelse(month(df$date)<10,"0",""),
                   month(df$date))
df$year <- year(df$date)
library(lubridate)
library(ggplot2)

# Define some data
df <- data.frame(date = seq.Date(from = as.Date("2015-01-01"), by = 1, length.out = 400),
                 salinity = runif(400, min=5, max=7))
# Create fields for plotting
df$day <- paste0(ifelse(month(df$date)<10,"0",""),
                 month(df$date),
                 "-",
                 ifelse(day(df$date)<10,"0",""),
                 day(df$date))
df$month <- paste0(ifelse(month(df$date)<10,"0",""),
                   month(df$date))
df$year <- year(df$date)
#Plot results by month
ggplot(data=df) +
  geom_tile(aes(x = month, y = year, fill = salinity)) +
  scale_y_continuous(breaks = c(2015,2016))
#Plot results by day
ggplot(data=df) +
  geom_tile(aes(x = day, y = year, fill = salinity)) +
  scale_y_continuous(breaks = c(2015,2016))

Results by month:

在此处输入图片说明

Results by day (do you really want this? It's very hard to read with 366 x-axis values): 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM