0

I would like to improve the years in Y axis. How to put the years using intervals (each 2 or 5 years)? Or how to include a secundary Y axis and interleave Y axis ticks?

year <- seq(1977,2021,1)
jan = runif(45, min=-4, max=4)
feb = runif(45, min=-4, max=4)
mar = runif(45, min=-4, max=4)
apr = runif(45, min=-4, max=4)
may = runif(45, min=-4, max=4)
jun = runif(45, min=-4, max=4)
jul = runif(45, min=-4, max=4)
aug = runif(45, min=-4, max=4)
sep = runif(45, min=-4, max=4)
oct = runif(45, min=-4, max=4)
nov = runif(45, min=-4, max=4)
dec = runif(45, min=-4, max=4)

df = data.frame(year,jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec)
df <- reshape2::melt(df, id.vars = "year")

df$year <- factor(df$year, levels = (unique(df$year)))
df$variable <- factor(df$variable, levels = (unique(df$variable)))

library(ggplot2)
e1 <- ggplot(df, aes(x = variable, y = year, fill = value)) +
  geom_raster()+
  guides(fill=guide_legend(title="Bohicon"))+
  scale_fill_gradientn(colours=c("#FF0000FF","#FFFFFFFF","#0000FFFF"))+
  theme(legend.position="bottom")

e1

Many thanks!

Marcel
  • 147
  • 4

1 Answers1

0

I understand that you simply want to set your year breaks to every 5 years?

  1. Do not convert years to factor
  2. Use scale_y_continuous to set axis breaks

NB: I have also shortened your code for the reproducible example, most importantly using "replicate" and the R ready made month vector month.abb. I'm sure one can do this even shorter, the challenge is out.

library(ggplot2)
year <- seq(1977,2021,1)
df <- cbind(year, setNames(data.frame(replicate(12, runif(45, min=-4, max=4))), month.abb))
df_long <- reshape2::melt(df, id.vars = "year")

ggplot(df_long, aes(x = variable, y = year, fill = value)) +
  geom_raster()+
  guides(fill=guide_legend(title="Bohicon"))+
  scale_fill_gradientn(colours=c("#FF0000FF","#FFFFFFFF","#0000FFFF"))+
  theme(legend.position="bottom") +
## now you can simply set the breaks as desired
  scale_y_continuous(breaks = seq(1980, 2020, 5))

enter image description here

tjebo
  • 21,977
  • 7
  • 58
  • 94