简体   繁体   English

使用geom_tile()的R ggplot热图:如何按年份排序并在y轴上显示所有年份?

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

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. 在研究了Hadley的书并在此处进行搜索之后,我创建了一个由年和月的矩阵组成的热图,颜色根据时间序列变量的百分比变化而变化。 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? 1)如何对矩阵进行排序/排序,以使y轴中的年份从最早到最晚? 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. 在这种情况下,我希望年份从Y轴的顶部开始,一直到2011年在Y轴的底部开始。

2) I want every year to be shown on the y-axis but instead it is showing only every 5th year. 2)我希望每年在y轴上显示,但只每5年显示一次。 I thought that the scale_y_date in my code would deal with this but it seems to have no affect. 我以为我的代码中的scale_y_date可以解决这个问题,但似乎没有影响。 How can I force the y-axis to display each year? 如何强制每年显示y轴?

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? 3)我怀疑这仍在ggplot2“要做”列表中,但是有什么方法可以使x轴标签(在本例中为Jan,Feb,Mar,Apr等)显示在图的顶部比在底部?

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

在此处输入图片说明

对于前两点,您可以将scale_y_continuous替换为scale_y_reverse以将最早的年份scale_y_reverse ,并明确指定休息时间和标签。

p_heat +  scale_y_reverse(breaks=1995:2011, labels=1995:2011, expand=c(0,0) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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