phynfo phynfo - 25 days ago 8
R Question

Plotting a line for each row in a Dataframe with ggplot2 in R

I got the following dataframe describing the age structure in different german districts:

enter image description here

I would like to plot one line per row with ggplot in R. An easy solution via matplot in R is:

matplot(t(df61[,-c(1,2)], type="l"))


which yields:

enter image description here

But how is it working with ggplot. I understood, that I have to transform the dataframe into a flat form:

library("reshape2")
df61_long <- melt(df61[,-2], id.vars = "NAME")


Which gives me:

enter image description here

I thought that the solution via ggplot should be something like:

ggplot(df61_long, aes(x = "variable", y = "value")) + geom_line(aes(colors = "NAME"))


which, however, yields an empty coordinate system. What did I do wrong?

Answer

Your example is not reproducible, so I made my own:

library(reshape2)
library(ggplot2)

df = data.frame(cat = LETTERS[1:6], VAR1 = runif(6), VAR2 = runif(6), VAR3 = runif(6), VAR4 = runif(6))
df_melted = melt(df, id.vars = 'cat')

In your code:

ggplot(df_melted, aes(x = 'variable', y = 'value')) + geom_line(aes(color = 'cat'))

there are a number of issues:

  • There is no colors aesthetic, should be color.
  • Aesthetics should not be passed as strings to aes. Use aes_string for that.
  • You need an additional aes in this case, group.

This code works:

ggplot(df_melted, aes(x = variable, y = value)) + geom_line(aes(color = cat, group = cat))

enter image description here