ggplot scale_x_datetime的轴标签和限制 [英] Axis labels and limits with ggplot scale_x_datetime

查看:168
本文介绍了ggplot scale_x_datetime的轴标签和限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得带有日期,工作日和时间作为x轴标签的漂亮图表.

I would like to get nice graphs with date, weekdays, and time as x-axis labels.

test <- data.frame(date=seq(as.POSIXct("2012-02-09 00:00:00",tz="CET"),as.POSIXct("2012-02-11 00:00:00",tz="CET"),"hours" ),
value= runif(49) )

ggplot() + geom_line(data=test, aes(x=as.POSIXct(date), y=value)) +
theme(text=element_text(size=16),
legend.text=element_text(size=16), 
axis.text=element_text(size=16, colour="black"),
panel.background = element_rect(fill = 'white', colour = 'black'),
axis.title.y = element_text(size=16, vjust = 0.3), 
axis.title.x = element_text(size=16, vjust = 0),
legend.key=element_rect(fill="white")) +
scale_x_datetime( breaks = date_breaks("1 days"), labels = date_format("%a-%d\n%H:%M", tz="CET"),
,limits = c(as.POSIXct("2012-02-09 00:00:00 CET"),as.POSIXct("2012-02-11 00:00:00 CET")))

包括MWE中包含的scale_x_datetime,它看起来像这样:

Including scale_x_datetime as included in the MWE it looks like this:

有几个问题/问题:

1)如何删除左侧和右侧的空格?定义limits()失败.

1) How can I remove the blank spaces on the left- and right-hand side? Defining limits() was not successful.

2)如何设置显示的时间(小时),换句话说,设置标签放置在哪个时间戳上?

2) How can I set the time (hour) that is shown, or in other words, at which timestamp the labels are placed?

3)当我像这样更改时间戳记

3) When I change the timestamp like this

test <- data.frame(date=seq(as.POSIXct("2012-02-09 00:59:00",tz="CET"),as.POSIXct("2012-02-11 00:59:00",tz="CET"),"hours" ),
value= runif(49) )

生成的图仍显示带有00分钟的时间戳.有办法改变吗?

the resulting plot(s) still show the timestamp with 00 minutes. Is there a way to change this?

推荐答案

如果您创建日期时间向量并将其赋予breaks参数,则可以完全控制中断.下面我用seq完成了此操作.

You have complete control of the breaks if you make a vector of date-times and give that to the breaks argument. Below I've done this with seq.

设置expand = c(0, 0)会停止ggplot,以提供更多空间.

Setting expand = c(0, 0) stops ggplot giving extra space.

ggplot(data = test, aes(x = as.POSIXct(date), y = value)) +
  geom_line() +
  scale_x_datetime(
    breaks = seq(as.POSIXct("2012-02-09 00:59:00 CET"),
                 as.POSIXct("2012-02-11 00:59:00 CET"), "8 hours"),
    labels = date_format("%a-%d\n%H:%M", tz = "CET"),
    expand = c(0, 0),
    limits = c(
      as.POSIXct("2012-02-09 00:00:00 CET"),
      as.POSIXct("2012-02-11 00:00:00 CET")
    )
  )

这篇关于ggplot scale_x_datetime的轴标签和限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆