graph panel data by group in r

To graph panel data by group in R, one option is to use ggplot2. Here is an example code:

main.r
library(ggplot2)
library(reshape2)

# example panel data
df <- data.frame(id = rep(1:5, each = 6),
                 time = rep(1:6, 5),
                 group = rep(letters[1:3], each = 10),
                 value = rnorm(30))

# reshape data 
df_long <- melt(df, id.vars = c("id", "time", "group"), variable.name = "variable")

# plot using ggplot
ggplot(df_long, aes(x = time, y = value)) +
  geom_line(aes(group = id, color = group)) +
  facet_wrap(~variable, scales = "free_y")
482 chars
17 lines

In this example, we first create an example panel data using the data.frame function. We then reshape the data using the melt function from the reshape2 package. This step is necessary to get the data in the long format required by ggplot. Finally, we use ggplot to create a line graph with separate facets for each variable, colored by group, and grouped by id. The result should be a graph with one panel per variable showing the evolution of each group over time.

gistlibby LogSnag