如何绘制R中的时间序列数据,根据因子数据改变背景? [英] How to plot time series data in R, changing background according to factor data?

查看:369
本文介绍了如何绘制R中的时间序列数据,根据因子数据改变背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  df<  -  data.frame(Month = seq(1,12),
Value = rnorm(12,0,1),
Season = c('Winter','Winter','Spring',
'Spring', 'Spring','Summer',
'Summer','Summer','Fall',
'Fall','Fall','Winter'))

我想随时间绘制价值图,并显示它与季节的关系。 Plotting Value很容易,如下所示:

  ggplot(data,aes(Month,Value))+ geom_line()

在ggplot或基本图形中:

  plot(Value〜Month,data = df,type ='l')

我想要做的是令人信服地覆盖一个因素。我想根据哪个月在x轴上更改背景颜色。所以,在我的例子中,左边的1/6会是白色的冬天,接下来的第三个右边的是春天的黄色,接下来是夏天的第三个红色等,直到最右边的1/12会再次变成白色。

这些对于时间序列数据来说应该是简单而容易的,但在任何图形包中,我找不到任何帮助。任何建议或见解,将不胜感激!

解决方案

在基地R你可以做到以下几点:

  plot(Value〜Month,type =n)
rect(df $ Month-0.5,min(df $ Value),df $ Month $ value = Month,data = df,type ='l',col =orange,lwd = 2)+0.5,max(df $ Value),col = df $ Season,lty = 0)

为可怕的底色配色方案道歉,我会在这里说明:





要在 ggplot2 中执行相同操作,您可以执行以下操作:

  ggplot(df,aes(Month,Value,Season))+ 
geom_rect(aes(NULL,NULL,
xmin = Month-0.5,xmax = Month + 0.5,
ymin = min(Value),ymax = max(Value),
fill = Season
))+
geom_line()

产生以下结果:


Lets say I have some time series data that looks like this:

df <- data.frame(Month=seq(1,12),
                 Value = rnorm(12,0,1),
                 Season = c('Winter', 'Winter', 'Spring',
                            'Spring', 'Spring', 'Summer',
                            'Summer', 'Summer', 'Fall',
                            'Fall', 'Fall', 'Winter'))

I want to plot Value over time and show how it relates to Season. Plotting Value is easy, something like:

ggplot(data, aes(Month, Value)) + geom_line()

in ggplot or in base graphics:

plot(Value~Month, data=df, type='l')

What I'd like to do is compellingly overlay a factor. I would like to change the background color according to which month is on the x-axis. So, in my example, the left 1/6th would be, say white for winter, then the next third moving right would be yellow for spring, then the next third red for summer, etc, until rightmost 1/12th would be white again.

These seems like it should be something simple and easy for time series data, but I can't find any help on how to do this, in any graphics package. Any suggestions or insight would be appreciated!

解决方案

In base R you can do the following:

plot(Value~Month, type="n")
rect(df$Month-0.5, min(df$Value), df$Month+0.5, max(df$Value), col=df$Season, lty=0)
lines(Value~Month, data=df, type='l', col="orange", lwd=2)

And apologizing for the horrific base color schemes I'll put this here to illustrate:

And to do the same in ggplot2 you can do the following:

ggplot(df, aes(Month, Value, Season)) + 
  geom_rect(aes(NULL, NULL, 
    xmin=Month-0.5, xmax=Month+0.5, 
    ymin=min(Value), ymax=max(Value), 
    fill=Season
  )) + 
  geom_line()

Yielding the following:

这篇关于如何绘制R中的时间序列数据,根据因子数据改变背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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