Domanda

I'm trying to create a plot of temperatures but I can't aggregate the data by year. My data comes in this form:

02-2012 7.2
02-2013 7.2
02-2010 7.9
02-2011 9.8
03-2013 10.7
03-2010 13.1
03-2012 18.5
03-2011 13.7
02-2003 9.2
...

containing all the months between Jan 2000 and Dec 2013. I've loaded the data with zoo:

f <- function(x) as.yearmon(format(x), "%m-%Y")
temp <- read.zoo(file="results.tsv", FUN = f)

Plotting the temp var I obtain a plot with X axis going from Jan 2000 to Dec 2013, but what I'd like to have is a plot where the X axis goes from Jan to Dec and the temperatures of every year are plotted as a separate line. Any hint?

Thanks, Andrea

È stato utile?

Soluzione

First you'll want to separate out the date into it's year and month components:

names(temp) <- c("date","temperature")
tmpSplit <- strsplit(temp$date, "-")
temp$month <- sapply(tmpSplit, "[", 1)
temp$year <- sapply(tmpSplit, "[", 2)

Then, my preference would be to use the ggplot2 package to plot your data:

library(ggplot2)
ggplot(temp, aes(x=month, y=temperature, group=year)) + geom_line()

Altri suggerimenti

Here are several approaches. First set up the data. Note the simplification in read.zoo.

library(zoo)
temp <- read.zoo("results.tsv", FUN = as.yearmon, format = "%m-%Y")

In addition to the plots below there is monthplot in the base of R (stats package). It does not appear to work with as.ts(temp) if temp is the subset of data provided in the question but if the actual data looks more like those in the examples of ?monthplot then it would work.

1) ggplot2

Create a data.frame DF with columns for the month, year and value. cycle can get the month numbers and format with a format of %Y can give the years. Note that we want the years to be a factor which data frame makes them as the result of format being character. Finally create the plot using ggplot2 or lattice:

library(ggplot2)
DF <- data.frame(Month = coredata(cycle(temp)), 
                 Year = format(index(temp), "%Y"),
                 Value = coredata(temp))

ggplot(DF, aes(Month, Value, col = Year)) + 
           geom_line() + 
           scale_x_continuous(breaks = 1:12)

ggplot2 screenshot

2) lattice With DF from 2) this would work:

library(lattice)
xyplot(Value ~ Month, DF, group = Year, type = "l", auto = TRUE)

xyplot screenshot

REVISED Added solutions and additional commentary.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top