【问题标题】:How to plot when Date and hour in separate field using ggplot in R如何使用 R 中的 ggplot 在单独的字段中绘制日期和时间
【发布时间】:2014-04-08 21:25:42
【问题描述】:

我有以下数据框

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))

【问题讨论】:

    标签: r datetime ggplot2 posixct


    【解决方案1】:

    我会将“日期”和“小时”列转换为 as.POSIXct 以用作 x 轴。在您显示的数据中,“小时”似乎是一个 character 变量(前导零),您可以像这样创建一个时间变量:

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

    “时间”变量可以用作 x 变量,按日期着色并不是真正必要的(当然,如果您愿意,可以添加)。

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

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

    【讨论】:

    • 还有一个愚蠢的问题,如果 d$date 和 d$hour 有 Factor's 作为它们的类呢?
    【解决方案2】:

    geom_tile怎么样:

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

    【讨论】:

    • 谢谢,但是当我对整个数据集使用这种方法时,整个图是蓝色的,很难像上面那样清楚地辨认出瓷砖
    猜你喜欢
    • 2020-12-14
    • 2018-02-10
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多