如何设置这个`geom_tile`的y轴在每个点都有一个格式化的`yearmon`标签?

时间:2016-05-25 10:49:25

标签: r ggplot2 data.table zoo

我有一张热图,显示y轴观察的年月配对值和底轴观察的小时值。数据保存在data.table对象中。

在默认ggplot2中,图表如下所示:

base ggplot

ggplot(repeatability, aes(x = iHrMi, y = iYrMo, fill = erraticity)) +
    geom_tile() +
    facet_grid(. ~ off) +
    scale_x_discrete(name = "Time", breaks = c("00:00", "12:00"))

这很好,但我的目标是让y轴上的标签包含缩写名称,而不是月份的数字,并保留其顺序。 zoo的扩展程序为ggplot2,可让您像这样绘制yearmon个对象:

with zoo::yearmon and expand = 0

ggplot(repeatability, aes(x = iHrMi, y = zoo::as.yearmon(iYrMo), fill = erraticity, group = iYrMo)) +
    geom_tile() +
    facet_grid(. ~ off) + 
    zoo::scale_y_yearmon(name = "Year Month", expand = c(0,0)) +
    scale_x_discrete(name = "Time", breaks = c("00:00", "12:00"))

这是正确的格式,但没有正确数量的标签,我想每月一个。此外,如果expand保留为默认值,则y轴会展开,并包含那些没有数据的句点。

如果我提供了一个n参数,要获得12个标签,就会发生这种情况:

with zoo::yearmon and expand = 0 AND n= 12

我没有得到12行,但是我得到了一个额外的奇数标签,吹过x轴截距。

ggplot(repeatability, aes(x = iHrMi, y = zoo::as.yearmon(iYrMo), fill = erraticity, group = iYrMo)) +
    geom_tile() +
    facet_grid(. ~ off) + 
    zoo::scale_y_yearmon(name = "Year Month", expand = c(0,0), n = 12) +
    scale_x_discrete(name = "Time", breaks = c("00:00", "12:00"))

这是用于制作它的表的头部。我担心我不确定如何以有用的方式输入整个表格。如果有人对如何包含更全面的版本有任何有用的建议,我会更新此信息:

structure(list(iYrMo = c("2013-08", "2013-08", "2013-08", "2013-08", 
"2013-08", "2013-08"), iHrMi = c("00:00", "00:30", "01:00", "01:30", 
"02:00", "02:30"), off = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Weekday", 
"Weekend/Holiday"), class = "factor"), fit = c(0.883255368890743, 
0.888802101750935, 0.887399903327103, 0.896846543832244, 0.895936947283074, 
0.898059799540441), erraticity = structure(c(4L, 4L, 4L, 4L, 
4L, 4L), .Label = c("Most", "More", "Less", "Least"), class = "factor")), .Names = c("iYrMo", 
"iHrMi", "off", "fit", "erraticity"), class = c("data.table", 
"data.frame"), row.names = c(NA, -6L))

1 个答案:

答案 0 :(得分:1)

请注意,yearmon只是一种双重类型,0等于Jan 00002013 + 6/12等于July 2013

您可以使用限制和中断参数(与ggplot中的scale_y_continuous相同):

library(zoo)
ggplot(repeatability, aes(x = iHrMi, y = as.yearmon(iYrMo), fill = erraticity, group = iYrMo)) +
  geom_tile() +
  facet_grid(. ~ off) + 
  scale_y_yearmon(name = "Year Month", limits = c(2013,2015), breaks = seq(2013,2015, by = 1/12)) +
  scale_x_discrete(name = "Time", breaks = c("00:00", "12:00"))

使用可重现的数据给出:

enter image description here

凌乱,但轴是正确的。