Selecting and plotting months in ggplot2

2019-09-03 15:24发布

问题:

I have a time series dataset in this format with two columns date (e.g Jan 1980, Feb 1980...Dec 2013) and it's corresponding temperature. This dataset is from 1980 to 2013. I am trying to subset and plot time series in ggplot for the months separately (e.g I only want all Feb so that I can plot it using ggplot). Tried the following, but the Feb1 is empty

Feb1 <- subset(temp, date ==5)

The structure of my dataset is:

'data.frame':   408 obs. of  2 variables:
$ date   :Class 'yearmon'  num [1:359] 1980 1980 1980 1980 1980 ...
$ temp: int  16.9 12.7 13 6 6.0 5 6 10.9 0.9 16 ...

回答1:

What about this?:

library(zoo)

# Generating some data:
df <- data.frame(date = as.yearmon("1980-01") + 0:407/12, val = rnorm(408))

# Subsetting to get a specific month:
df.sub <- subset(df, format(df$date,"%b")=="Jan")

# The actual plot:
ggplot(df.sub) + geom_line(aes(x = as.Date(date), y = val))



回答2:

I believe your column being in a 'yearmon' class comes in the format "mm YY". I'm a little confused by how you are subsetting the data by 'date==5'. Below I try a method.

temp$month<-substr(temp$date,1,3)
Feb1<-subset(temp,month=='Feb')

#more elegant

Feb1<-subset(temp,substr(temp$date,1,3)=='Feb')


回答3:

You can also directly plot the subset in ggplot2 without creating a new data frame.

Based on RStudent's solution:

library(zoo)

# Generating some data:
df <- data.frame(date = as.yearmon("1980-01") + 0:407/12, val = rnorm(408))

library(ggplot2)
ggplot(df[format(df$date,"%b")=="Jan", ], aes(x = as.Date(date), y = val))+
   geom_line()


回答4:

Convert the data to zoo, use cycle to split into months and autoplot.zoo to plot. Below we show four different ways to plot. First we plot just January. Then we plot all the months with each month in a separate panel and then we plot all months with each month as a separate series all in the same panel. Finally we use monthplot (not ggplot2) to plot them all in a single panel in a different manner.

library(zoo)
library(ggplot2)

# test data
set.seed(123)
temp <- data.frame(date = as.yearmon(1980 + 0:479/12), value = rnorm(480))

z <- read.zoo(temp, FUN = identity) # convert to zoo

# split into 12 series and cbind them together so zz480 is 480 x 12
# Then aggregate to zz which is 40 x 12

zz480 <- do.call(cbind, split(z, cycle(z)))
zz <- aggregate(zz480, as.numeric(trunc(time(zz480))), na.omit)

### now we plot this 4 different ways
#####################################

# 1. plot just January
autoplot(zz[, 1]) + ggtitle("Jan")

# 2. plot each in separate panel
autoplot(zz)

# 3. plot them all in a single panel
autoplot(zz, facet = NULL)

# 4. plot them all in a single panel in a different way (not using ggplot2)
monthplot(z)

Note that an alternative way to calculate zz would be:

zz <- zoo(matrix(coredata(z), 40, 12, byrow=TRUE), unique(as.numeric(trunc(time(z)))))

Update: Added plot types and improved the approach.



标签: r ggplot2 subset