ggplot x轴作为日期与小时

A.T*_*ska 4 r ggplot2

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

Bra*_*ood 9

我只是想提供一个例子来赞同我的评论.您可以使用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")
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,您无需更改/重新格式化原始数据.这是结果图的样子: 在此输入图像描述

更新:这是使用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"))
Run Code Online (Sandbox Code Playgroud)