[英]Setting 24-hour scale on Y-axis with ggplot2
我有以下列表:
> head(myList)
ID Day Time
1 57790 0 12:27:41
2 66922 0 15:00:00
3 83457 0 18:22:37
4 83571 0 18:28:01
5 85613 0 19:06:05
6 93268 0 21:00:00
由以下数据类型组成:
> myList %>% summarise_all(typeof) %>% gather()
key value
1 ID integer
2 Day double
3 Time character
使用ggplot(myList, aes(x = Day, y = Time)) + geom_point()
产生以下 plot:
如您所见,Y 轴全乱了。 如何让这个轴在 24 小时制中的每个小时只显示一个标记,而不是列出每个单独的时间值?
我已经绑定了各种scale_y_
函数,但我不断收到有关此错误的各种主题: Error: Discrete value supplied to continuous scale
。
谢谢你的帮助。
更新 - 12 月 10 日 17:00 CST
使用此代码时,我得到以下结果:Y 轴不在 00:00 开始或在 24:00 终止。 00:00-01:00(图表顶部)的绘图应位于图表底部。 不过,它是如此接近。 :)
> myList$Time <- as.POSIXct(myList$Time, format = "%H:%M:%S")
> g <- ggplot(myList, aes(x = factor(Day), y = Time)) + geom_point() +
scale_y_datetime(labels = function(x) format(x, "%H:%M", tz = "EST"),
date_breaks = '1 hour',expand = c(0,0))
> plot(g)
查看各种scale_date
函数:
https://ggplot2.tidyverse.org/reference/scale_date.html
这是一个使用 NYC Flight 数据和scale_y_time()
的示例。 请注意,我冒昧地使用geom_jitter()
来更好地显示数据。
library(tidyverse)
library(lubridate)
flightdata <- nycflights13::flights %>%
slice(1:3000) %>%
mutate(flight_time = lubridate::hm(paste(hour, minute)),
flight_date = lubridate::ymd(paste(year, month, day))) %>%
select(flight_time, flight_date)
ggplot(flightdata, aes(x = flight_date, y = flight_time)) +
#geom_point() +
geom_jitter() +
scale_y_time()
试试这个方法:
library(ggplot2)
#Data
myList$Time <- as.POSIXct(myList$Time,format="%H:%M:%S")
#Code
ggplot(myList, aes(x = factor(Day), y = Time)) + geom_point()+
scale_y_datetime(labels = function(x) format(x, "%H:%M", tz = "EST"),
date_breaks = '1 hour',expand = c(0,0),
limits = as.POSIXct(c('00:00:00','24:00:00'),
format="%H:%M:%S"),
date_labels = c('00:00','00:01','00:02','00:03',
'00:04','00:05','00:06','00:07',
'00:08','00:09','10:00','11:00',
'12:00','13:00','14:00','15:00',
'16:00','17:00','18:00','19:00',
'20:00','21:00','22:00','23:00',
'24:00'))+
xlab('Day')
Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.