【问题标题】:plotting the date and time on separate row in ggplot?在ggplot的单独行上绘制日期和时间?
【发布时间】:2020-12-14 15:36:24
【问题描述】:

如何格式化 x 轴标签,以使小时在日期下方居中(不与日期一致)?

library(lubridate)
library(scales)
library(ggplot2)

set.seed(123)

DF<- data.frame(Datetime = seq(ymd_hms("2011-01-01 00:00:00"), to= ymd_hms("2011-01-10 00:00:00"), by = "hour"),
                Var1 = runif(217, 5,10))
ggplot(DF, aes(x = Datetime, y = Var1))+
  geom_line()+
  scale_x_datetime(breaks = breaks_pretty(10), labels = date_format("%Y-%m-%d %H"))

【问题讨论】:

  • labels = date_format("%Y-%m-%d\n%H")?
  • 谢谢@Nate - 很快。
  • 快乐 ggplot-ing!
  • @Nate 这应该是一个解决方案。请张贴。

标签: r ggplot2 plot tidyverse axis


【解决方案1】:

我建议修改轴标签的主题:

library(lubridate)
library(scales)
library(ggplot2)

set.seed(123)

DF<- data.frame(Datetime = seq(ymd_hms("2011-01-01 00:00:00"), to= ymd_hms("2011-01-10 00:00:00"), by = "hour"),
                Var1 = runif(217, 5,10))
ggplot(DF, aes(x = Datetime, y = Var1))+
  geom_line()+
  scale_x_datetime(breaks = breaks_pretty(10), labels = date_format("%Y-%m-%d %H"))+
  theme(axis.text.x = element_text(angle=-90))

输出:

【讨论】:

  • 好建议,我这里有点小气。角度会占用更多空间。
  • @Hydro 这取决于标签的长度。有了这个角度,您将按照您的意愿对齐!您可以尝试其他值。希望对您有所帮助!
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多