gpt4 book ai didi

r - ggplot x 轴作为带小时的日期

转载 作者:行者123 更新时间:2023-12-04 10:36:52 28 4
gpt4 key购买 nike

我尝试制作显示每小时频率的 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" ?
谢谢你的帮助!

最佳答案

我只是想我会提供一个例子来配合我的评论。您可以使用 scales 包中的 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"))

关于r - ggplot x 轴作为带小时的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36460980/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com