【发布时间】:2013-08-29 11:54:07
【问题描述】:
我有一个数字变量,要绘制在 x 轴上,包含从 0 到 23 的数字。我 a) 需要将这些时间转换为 Date 对象,以便在 ggplot 中可视化它们,并且我 b) 想让 x 轴以 am/pm 格式显示这些数字。
到目前为止我有:
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 实际上会一直持续到23,但由于空间原因,我只包括了0 和1。我想要的是 x 轴显示6am, 9am, 12am, 3pm, 6pm, 9pm, 12pm,或类似的东西。不能这么难吧?我尝试使用需要Date 对象的scale_x_date 进行试验,但我失败了,因为我不知道如何处理原点——只有几个小时没有任何原点!
【问题讨论】:
-
对不起,时间显然不是
Dates。 -
好的,但使用
scale_x_date的唯一方法是将其转换为Date对象,对吗?还是有类似scale_x_hour的东西? ;-) -
我发布了一个使用字符串的替代解决方案(如果您想使用
scale_x_datetime并进行一些改进,我可以将日期解决方案放回去。