Marian
Marian

Reputation: 97

How to plot panel data in R?

I have the following csv file:


  id year  item valuesound growtharea
1 16 2005 Wheat   9784.490         NA
2 16 2006 Wheat  10020.720  0.0241437
3 16 2007 Wheat   9232.796 -0.0786298
4 16 2008 Wheat   8567.893 -0.0720154
5 16 2009 Wheat  10292.670  0.2013073
6 16 2010 Wheat   9274.589 -0.0989134

After the plm, the panel looks like this:

> library(plm)
> panel <- pdata.frame(data, index = c("id", "year"), drop.index = TRUE)
> head(panel)
         item valuesound growtharea
16-2005 Wheat   9784.490         NA
16-2006 Wheat  10020.720  0.0241437
16-2007 Wheat   9232.796 -0.0786298
16-2008 Wheat   8567.893 -0.0720154
16-2009 Wheat  10292.670  0.2013073
16-2010 Wheat   9274.589 -0.0989134

I have problems in graphing this panel. I would like to create a line graph with ggplot2, so it would show a line of each "id" across the "year" the values of "valuesound".

I've tried with ggplot2

ggplot(panel, mapping = aes(x = year, y = value, group = id)) +
   geom_line()

But always I have errors such as "Error in FUN(X[[i]], ...) : object 'year' not found". I don't know where the mistake is. I've changed drop.index=FALSE, but still I cannot create a nice graph with colors for each line. Could you please help me to create a graph using this panel data?

Upvotes: 0

Views: 10298

Answers (1)

monarque13
monarque13

Reputation: 578

The original dataset has the separate id and year variables that you need to plot changes to valuesound over time. There is no need to change to pdata.frame as doing so indexes the id and year variables.

I think this is what you're looking for:

library(ggplot2)

# where object df is your original dataset
ggplot(df, mapping = aes(x = year, y = valuesound)) +
  geom_line(aes(linetype = as.factor(id)))

enter image description here

Upvotes: 1

Related Questions