R ggplot geom_tile 日期的垂直间距不均匀

Afi*_*ari 3 r ggplot2

set.seed(1990)

ID <- rep(LETTERS,each = 12)
n <- rep(round(runif(12,1,10)), 26)
datetime <- rep(seq(as.POSIXct("2020-01-01"), as.POSIXct("2020-12-01"), by="month"), 26)
datetime <- lubridate::date(datetime)
dataset <- tibble(ID, datetime, n)

ggplot(dataset 
       ,
       aes(x=datetime,y= reorder(ID, n),fill=n))+
  geom_tile(color = 'gray') +
  scale_x_date(expand = c(0,0),breaks = seq(as.Date("2014-07-01"), as.Date("2020-12-01"), by = "1 month"), date_labels = "%Y %b", name = 'Monthly') 

Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

间隔似乎是由特定月份的天数长度决定的,这在这种情况下并没有多大用处。

我找到的临时解决方案是将日期转换为因子,但似乎仍然不是最好的,因为水平空间也不均匀。

dataset$datetime <- factor(dataset$datetime)

ggplot(dataset 
       ,
       aes(x=datetime,y= reorder(ID, n),fill=n))+
  geom_tile(color = 'gray')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但我将失去使用scale_x_date() 进行标记的能力

> ggplot(dataset 
+        ,
+        aes(x=datetime,y= reorder(ID, n),fill=n))+
+   geom_tile(color = 'gray') +
+   scale_x_date(expand = c(0,0),breaks = seq(as.Date("2014-07-01"), as.Date("2020-12-01"), by = "1 month"), date_labels = "%Y %b", name = 'Monthly') 
Error: Invalid input: date_trans works with objects of class Date only
Run Code Online (Sandbox Code Playgroud)

我希望实现的是这个完美的正方形,所有瓷砖之间的间距相等,如下所示。 在此输入图像描述

Ian*_*ell 5

这有点像黑客,但是如何将日期更改为调用中的一个aes()因素zoo::as.yearmon(datetime). 然后你可以使用coord_equal()

library(zoo)
ggplot(dataset, aes(y = as.factor(zoo::as.yearmon(datetime)),
                    x = reorder(ID, n), fill=n)) +
  geom_tile(color = 'gray') + labs(x = "Factor", y = "Date") +
  coord_equal() 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您需要更多格式控制,请添加对以下内容的调用format

ggplot(dataset ,aes(y = reorder(as.factor(format(zoo::as.yearmon(datetime),"%Y %b")),
                                zoo::as.yearmon(datetime)),
                    x = reorder(ID, n), fill = n)) +
  geom_tile(color = 'gray') + labs(x = "Factor", y = "Date") +
  coord_equal() 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述