我有一个数字变量,要绘制在x轴上,包含数字从0到23.我a)需要将这些小时转换为Date
对象,以便将它们可视化为ggplot
,以及b)希望x轴以am/pm格式显示这些数字。将24小时转换为上午/下午格式
到目前为止,我有:
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
,或类似的东西。不能那么难吗?我试着用scale_x_date
进行试验,这需要一个Date
的对象,但是我失败了,因为我不知道如何处理这个起源 - 几小时内就没有任何起源!
我很抱歉,但是时间显然不是'Date's。 – Roland
好吧,但使用'scale_x_date'的唯一方法是将其转换为'Date'对象,对吧?或者有什么像'scale_x_hour'? ;-) – wnstnsmth
我发布了一个替代解决方案,它使用字符串代替(如果您想使用'scale_x_datetime'进行一些改进,我可以将日期解决方案返回。 –