使用lubridate和ggplot2有效地处理日期轴 [英] Using lubridate and ggplot2 effectively for date axis

查看:165
本文介绍了使用lubridate和ggplot2有效地处理日期轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:

  library(ggplot2)
library(lubridate)

set.seed(4)
date < - seq(from = as.POSIXct(2012-01-01),to = as.POSIXct(2014-12-31),by = (rnorm(274,50,1),rnorm(274,55,1),rnorm(274,55,2),rnorm(274,60,2))
值< b $ b df< - data.frame(日期,值)

头(df)
#日期值
#1 2012-01-01 50.21675
#2 2012-01-02 49.45751
#3 2012-01-03 50.89114
#4 2012-01-04 50.59598
#5 2012-01-05 51.63562
#6 2012-01-06 50.68928

ggplot(df,aes(x = yday(date),y = value,color = factor(year(date))))+
geom_line()

产生这种情节:

< img src =https://i.stack.imgur.com/j2rrU.pngalt =情节>



有什么方法可以让轴格式化作为逐月的日期?如果可能,我试图确定一个干净的方式来利用 lubridate scale_x_date

也许有更好的方法来创建这种类型的图表?也就是说,按年份创造因素并将它们打在一起? (注意:本例中我不想使用 facet_wrap facet_grid )。

$ b

解决方案

一个解决方案可能是将一列添加到您的数据框中,该列将包含一天中的每一行和另一年中的月份(对于所有行都是相同的) ,例如2015年。

  df $天< -as.Date(格式(df $ date,%d-% m-2015),format =%d-%m-%y)

您可以然后使用此列作为 x

 库(比例)
ggplot(df,aes(x = days,y = value,color = factor(year(date))))+
geom_line()+ scale_x_date(labels = date_format(%b))


编辑:简化 df $天


Consider this example:

library(ggplot2)
library(lubridate)

set.seed(4)
date   <- seq(from = as.POSIXct("2012-01-01"), to = as.POSIXct("2014-12-31"), by = "days")
value  <- c(rnorm(274, 50, 1), rnorm(274, 55, 1), rnorm(274, 55, 2), rnorm(274, 60, 2))
df     <- data.frame(date, value)

head(df)
#         date    value
# 1 2012-01-01 50.21675
# 2 2012-01-02 49.45751
# 3 2012-01-03 50.89114
# 4 2012-01-04 50.59598
# 5 2012-01-05 51.63562
# 6 2012-01-06 50.68928

ggplot(df, aes(x=yday(date), y=value, color=factor(year(date)))) +
  geom_line()

Which generates this plot:

What are some ways to make the axis formatted as a date by month? I am trying to determine a clean way to leverage both lubridate and scale_x_date if possible?

Perhaps there are better ways to create this type of graph? That is, creating factors by year and plotting them on top of each other? (NOTE: I do not want to use facet_wrap or facet_grid for this example).

解决方案

One solution could be to add a column to your dataframe that will contain for each row the day and the month in another year (the same for all rows), for example year 2015.

df$days<-as.Date(format(df$date,"%d-%m-2015"),format="%d-%m-%y")

You can then plot using this column as x

library(scales)
ggplot(df, aes(x=days, y=value, color=factor(year(date)))) +
  geom_line()+scale_x_date(labels = date_format("%b"))

Edit: simplified the df$days line

这篇关于使用lubridate和ggplot2有效地处理日期轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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