[英]ggplot x-axis as date with hours
我嘗試制作每小時顯示頻率的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"
?
謝謝你的幫助!
我只是想提供一個例子來贊同我的評論。 您可以使用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")
這樣做的好處是,您無需更改/重新格式化原始數據。 這是結果圖的樣子:
更新 :這是使用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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.