[英]Convert 24h to AM/PM format
I have a numeric variable, to be plotted on the x-axis, containing digits from 0 to 23. I a) need to convert these hours into Date
objects in order to visualize them in a ggplot
, and I b) want to have the x-axis display these numbers in am/pm format. 我有一个数字变量,要在x轴上绘制,包含从0到23的数字。我a)需要将这些小时数转换为Date
对象,以便在ggplot
其可视化;我b)想要x轴以am / pm格式显示这些数字。
So far I have: 到目前为止,我有:
library("ggplot2")
library(scales)
Sys.setlocale(category = "LC_ALL", locale = "English")
# data
hod <- structure(list(h = c(0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L),
t = c(NA, 2L, 4L, 1L, 3L, NA, 2L, 4L, 1L, 3L), n = c(226L,
226L, 226L, 226L, 226L, 226L, 226L, 226L, 226L, 226L), mean = c(4.52654867256637,
33.6769911504425, 6.34513274336283, 30.3672566371681, 0.309734513274336,
2.84513274336283, 20.0088495575221, 3.38938053097345, 17.7787610619469,
0.101769911504425), std = c(2.74131025125736, 13.4781731703065,
3.0316031901839, 10.9165210711549, 0.603524251739029, 2.25142987605743,
10.9354466064168, 2.27892859595505, 8.76056582129717, 0.33032092222724
)), .Names = c("h", "t", "n", "mean", "std"), row.names = c(NA,
10L), class = "data.frame")
ggplot(hod, aes(x=h, y=mean, colour=as.factor(t))) +
geom_line(size = .1) +
geom_point() +
theme_minimal()
hod$h
would actually continue up until 23
, but I only included 0
and 1
for reasons of space. hod$h
实际上将一直持续到23
,但是出于空间原因,我只包括了0
和1
。 What I want is the x-axis to show 6am, 9am, 12am, 3pm, 6pm, 9pm, 12pm
, or something like this. 我想要的是x轴显示6am, 9am, 12am, 3pm, 6pm, 9pm, 12pm
或类似的东西。 Can't be that hard can it? 可以这么难吗? I tried experimenting with scale_x_date
which requires a Date
object, but I failed because I didn't know how to deal with the origin - there isn't any origin just hours! 我尝试使用需要Date
对象的scale_x_date
进行试验,但是失败了,因为我不知道如何处理原点-数小时内没有任何原点!
You could use strftime
to format times as you require and use this as the x
aesthetic. 您可以根据需要使用strftime
格式化时间,并将其用作x
美感。 You will then have to also use a grouping aesthetic. 然后,您还必须使用分组美学。 We use lubridate
to make it easy to work with hours. 我们使用lubridate
使其易于长时间工作。 Try this: 尝试这个:
require(lubridate)
hod$time <- tolower( strftime( Sys.Date()+hours(hod$h) , "%I %p" ) )
# [1] "12 am" "12 am" "12 am" "12 am" "12 am" "01 am" "01 am" "01 am" "01 am" "01 am"
ggplot(hod, aes( x = time , y=mean, colour=as.factor(t) , group = t ) ) +
geom_line(size = .1) +
geom_point()
ggplot(hod, aes( x = h , y=mean, colour=as.factor(t))) +
geom_line(size = .1) +
geom_point() +
scale_x_continuous(limits=c(0,24),
breaks=0:12*2,
labels=c(paste(0:5*2,"am"),
"12 pm",
paste(7:11*2-12,"pm"),
"0 am"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.