ggplot x轴作为日期与小时

时间:2016-04-06 19:46:55

标签: r ggplot2

我尝试制作每小时显示频率的ggplot。我有x轴问题,我将原始日期格式从2015-01-02 02:07:27更改为2015-01-02 02,我使用了format(dates, format = "%Y-%m-%d %H")。在我的ggplot中,我使用了a aes(x=as.Date(dates)..但在x轴上我的格式为2015-01-02。可以在x轴上以格式"%Y-%m-%d %H"显示日期?
谢谢你的帮助!

1 个答案:

答案 0 :(得分:7)

我只是想我提供一个例子来赞同我的评论。您可以使用 scale 包中的 date_format()函数。

require(ggplot2)
require(scales)

#Create a test sequence of dates
test_dates = seq(from = as.POSIXct("2015-01-02 02:07:27", format="%Y-%m-%d %H:%M:%S"),
                 to = as.POSIXct("2015-01-04 02:00:00", format="%Y-%m-%d %H:%M:%S"),
                 by = "hour")
#Set seed for random variable
set.seed(1)
#Create the test data
time_data = 
    data.frame(dates = test_dates,
               measurements = runif(n = length(test_dates),
                                    min = 0, max = 1))
#Plot the data
ggplot(time_data, aes(x = dates, y = measurements)) +
    geom_line() +
    #Here is where I format the x-axis
    scale_x_datetime(labels = date_format("%Y-%m-%d %H"),
                     date_breaks = "8 hours")

这样做的好处是,您不需要更改/重新格式化原始数据。这是结果图的样子: enter image description here

更新:以下是使用OP评论中的测试数据的另一个示例:

require(ggplot2)
require(scales)

#Create the test data
example_data <-
    data.frame(a = as.POSIXct(c("2015-01-02 06:07:27", "2015-01-02 06:42:36", "2015-01-02 08:07:38", "2015-01-02 08:08:45", "2015-01-02 08:12:23", "2015-01-03 09:07:27", "2015-01-03 09:42:36")),
               b = c("1","1","1","1","1","1","1"))

#Pull out date and hour components
example_data$days <- as.POSIXct(format(example_data$a, "%Y-%m-%d"))
#This doesn't work because format just returns a character string, not a dateTime
example_data$hours <- format(example_data$a, "%Y-%m-%d %H")
#Instead, you need to re-cast the output of format as a dateTime
example_data$hours <- as.POSIXct(format(example_data$a, "%Y-%m-%d %H"), format="%Y-%m-%d %H")

#Plot the data
ggplot(data = example_data, aes(x=days)) + geom_bar(stat="bin")
ggplot(data = example_data, aes(x=hours)) + geom_bar(stat="bin")

#Now use axis-scaling and date_format to get just the data and hours
ggplot(data = example_data, aes(x=hours)) +
    geom_bar(stat="bin") +
    scale_x_datetime(labels = date_format("%Y-%m-%d %H"))