如何调整ggplot直方图的时间轴坐标 [英] How to adjust time scale axis for ggplot histogram

查看:303
本文介绍了如何调整ggplot直方图的时间轴坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个数据框,其中一列由 POSIXct 日期时间值组成。我试图用 ggplot2 绘制这些时间戳的直方图,但我有两个问题:


  1. 我不知道如何在 geom_histogram()中设置binwidth。我想将每个垃圾箱设置为一天或一周。我试过提供一个difftime对象,但是我得到一个错误。我也尝试过 binwidth = 1 但R只是挂起。

  2. 如何在 scale_x_time()?我可以使用它的唯一方法是使用 as.Date()来转换我的 POSIXct 时间戳。


解决方案


  1. 以每周为单位设置 binwidth = 7 * 24 * 60 * 60

  2. 限制可以作为2个POSIXct对象的向量。

举例:

  y <-as.POSIXct('1970/01/01')+ cumsum(rnorm(100,mean = 24 * 60 * 60,sd = 24 * 60 * 60))
p <-qplot(y ,binwidth = 7 * 24 * 60 * 60,fill = I('steelblue'),col = I('black'))
p <-p + scale_x_datetime(major =1 week,
次要=1天,
格式=%e /%m /%Y,
限制= c(as.POSIXct('1970/02/01'),
as.POSIXct('1970/03/31')))
print(p)


I am working with a data frame where one of the columns consists of POSIXct date-time values. I am trying to plot a histogram of these timestamps using ggplot2 but I'm having two issues:

  1. I don't know how to set the binwidth in geom_histogram(). I'd like to set each bin to a day or a week. I've tried providing a difftime object, but I get an error. I also tried binwidth=1 but R just hangs.

  2. How do I set the limits in scale_x_time()? The only way I could get it to work was by converting my POSIXct timestamps using as.Date().

解决方案

  1. The binwidth is measured in seconds, so to bin per week set binwidth=7*24*60*60.
  2. Limits can be given as a vector of 2 POSIXct objects.

An example:

y<-as.POSIXct('1970/01/01')+cumsum(rnorm(100,mean=24*60*60,sd=24*60*60))
p<-qplot(y,binwidth=7*24*60*60,fill=I('steelblue'),col=I('black'))
p<-p+scale_x_datetime(major="1 week",
                      minor="1 days",
                      format="%e/%m/%Y",
                      limits=c(as.POSIXct('1970/02/01'),
                               as.POSIXct('1970/03/31')))
print(p)

这篇关于如何调整ggplot直方图的时间轴坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆