更新时间:2023-02-26 19:59:36
在基地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: