如何使用R中的ggplot在单独的字段中绘制日期和小时

时间:2014-04-08 21:25:42

标签: r datetime ggplot2 posixct

我有以下数据框

head(d[, c(1,2,7)], 10)
         date hour total_sess
2  2014-04-06   00        115
3  2014-04-07   01          3
4  2014-04-07   16          3
5  2014-04-07   21        115
6  2014-04-08   00        115
7  2014-04-08   06          3
8  2014-04-09   05          3
9  2014-04-09   11        201
10 2014-04-09   14          3
11 2014-04-09   20          3

如何使用ggplot绘制条形图,其中X轴=小时(沿轴指示日期)和Y轴为total_sess

我尝试了以下但无法生成连续流

ggplot(data = d, aes(x = hour, y = total_sess, fill = factor(date)) +
 geom_bar(stat='identity') +
 theme(axis.text.x = element_text(angle = 90, hjust = 0.5))

2 个答案:

答案 0 :(得分:1)

我会转换字段' date'和'小时'到as.POSIXct以用作x轴。在您显示的数据中,'小时'似乎是一个character变量(前导零),你可以像这样创建一个时间变量:

d$time <- as.POSIXct(paste0(d$date, " ", d$hour, ":00:00"))

&#39;时间&#39;变量可以用作x变量,并且日期的颜色不是必需的(但是如果你愿意,当然可以添加)。

ggplot(data = d, aes(x = time, y = total_sess)) +
  geom_bar(stat='identity') +
  theme_bw()

enter image description here

当您的x变量属于as.POSIXct类时,您可以使用scale_x_datetime。然后,使用breaks = date_breakslabels = date_format参数(加载library(scales))很容易格式化x轴。请参阅示例here

答案 1 :(得分:0)

如何使用geom_tile

library(lubridate)
library(ggplot2)
ggplot(data = data, aes(x = hour, y = ymd(date))) +
  geom_tile(aes(fill=total_sess)) +
  theme_bw()

enter image description here