Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot heatmap using geom_tile(): how to sort by year and show all years in y-axis?

Tags:

r

ggplot2

After studying Hadley's book and searching here on SO I have created a heatmap consisting of a matrix of years and months, with the colour varying according the percentage change in a time series variable. The heatmap and the code I used to get it are shown below. I have a few remaining questions that I haven't been able to resolve on my own.

1) How can I sort/order the matrix so that the years in the y-axis run from the earliest to the latest? In this case I want the years to start from the top at 1995 and continue to 2011 at the bottom of the y-axis.

2) I want every year to be shown on the y-axis but instead it is showing only every 5th year. I thought that the scale_y_date in my code would deal with this but it seems to have no affect. How can I force the y-axis to display each year?

3) I suspect this is still on the ggplot2 "to do" list, but is there any way to make the x-axis labels (in this case the Jan, Feb, Mar, Apr etc) display at the top of the plot rather than at the bottom?

require(ggplot2)
mydf <- data.frame(date=seq(as.Date("1995/1/1"), by="month", length.out=203),yoy=runif(203, min=-1, max=1))
p_heat <- ggplot(mydf, aes(x=month(date,label=TRUE),y=year(date), fill = yoy, label = sprintf("%1.1f%%", 100*yoy),size=10)) + 
  scale_y_date(major="years", format="%Y") +
  geom_tile() + geom_text(aes(size=10)) +
  scale_fill_gradient2(low = "red", high = "green") +
  scale_x_discrete(expand=c(0,0)) +
  scale_y_continuous(expand=c(0,0)) +
  opts(title="Value (%)") +
  opts(panel.grid.minor=theme_blank()) +
  opts(axis.ticks = theme_blank()) +
  opts(panel.grid.major=theme_blank()) +
  opts(axis.title.y = theme_blank()) +
  opts(axis.title.x = theme_blank()) +
  opts(legend.position = "none")
p_heat

enter image description here

like image 235
SlowLearner Avatar asked Jan 09 '12 04:01

SlowLearner


1 Answers

For the first two points, you can replace scale_y_continuous with scale_y_reverse to have the earliest years on top, and explicitly specify the breaks and labels.

p_heat +  scale_y_reverse(breaks=1995:2011, labels=1995:2011, expand=c(0,0) )
like image 120
Vincent Zoonekynd Avatar answered Oct 26 '22 02:10

Vincent Zoonekynd