[英]Change number of x ticks on time series using ggplot2
I'm trying to plot a time series x_output
that looks like this: 我正在尝试绘制一个如下所示的时间序列x_output
:
timestamp city wait_time weekday time
2015-07-14 09:00:00 Boston 1.6 Tuesday 09:00:00
2015-07-14 09:01:00 Boston 1.8 Tuesday 09:00:00
2015-07-14 09:02:00 Boston 2.4 Tuesday 09:00:00
2015-07-14 09:03:00 Boston 2.9 Tuesday 09:00:00
2015-07-14 09:04:00 Boston 4.5 Tuesday 09:00:00
2015-07-14 09:05:00 Boston 5.6 Tuesday 09:00:00
Here's how I'm plotting it: 这是我正在绘制它的方式:
brks <- seq(1, length(x_output$timestamp), 10)
brks_labels <- x_output[brks, ]
p <- ggplot(x_output, aes(x=as.character(timestamp), y=wait_time, group=city)) + geom_line(aes(color=city), size=1.5) + theme(axis.text.x = element_text(angle = 90, hjust=1), legend.position = "bottom") + labs(x=NULL, y="Waiting time (minutes)") + scale_x_discrete(breaks = brks, labels = brks_labels)
print(p)
I have to use x_output$timestamp
as a character (ie. categorical variable) because otherwise, ggplot2 thinks it's continuous and includes white blank areas that have no values. 我必须使用x_output$timestamp
作为字符(即分类变量),否则,ggplot2认为它是连续的并且包括没有值的白色空白区域。
For some reason however, scale_x_discrete
does not seem to be working. 但是出于某种原因, scale_x_discrete
似乎不起作用。 I believe I got the input for breaks right, however, the labels now aren't showing. 我相信我得到了休息的输入,但是,标签现在没有显示。 Does anyone know why? 有谁知道为什么? Here's what plots: 这是什么情节:
I'm trying to simply have the labels appear every 10 timestamps on the x-axis (which is why I put the breaks into an array as brks
). 我试图简单地在x轴上每10个时间戳出现标签(这就是我把断点作为brks
放入数组的brks
)。
Your breaks have to be the same type as your aes(x=
, ie scale_x_discrete(breaks=x_output$timestamp[brks])
works. 你的休息时间必须与aes(x=
相同aes(x=
,即scale_x_discrete(breaks=x_output$timestamp[brks])
有效。
However be aware that converting your timestamp to categorical like this can be inaccurate on the timescale then - if a timestamp skipped by 2 minutes and the rest skipped by 1 this wouldn't be reflected on your graph. 但请注意,将时间戳转换为类似的分类在时间刻度上可能不准确 - 如果时间戳跳过2分钟而其余时间跳过1则不会反映在图表上。
I think you're better off keeping X as a datetime, and using + scale_x_datetime(breaks=date_breaks("10 mins"))
. 我认为你最好将X保持为日期时间,并使用+ scale_x_datetime(breaks=date_breaks("10 mins"))
。 If you have multiple windows of time separated by expanses of no data, you could use a variable to indicate which 'window' each row belongs to, and facet_wrap
to plot the windows side-by-side, which would let you skip the gaps while preserving x-axis scale. 如果你有多个时间窗口被无数据扩展分隔,你可以使用一个变量来指示每行所属的“窗口”,并使用facet_wrap
绘制窗口,这样可以跳过间隙保留x轴刻度。 Eg you could facet_wrap
by weekday
if your data was only for a particular window each day. 例如,如果您的数据仅适用于每天的特定窗口,那么您可以在weekday
使用facet_wrap
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.