Reputation: 4938
I got the following dataframe describing the age structure in different german districts:
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:
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:
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?
Upvotes: 2
Views: 9617
Reputation: 60924
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:
colors
aesthetic, should be color
.aes
. Use aes_string
for that.group
.This code works:
ggplot(df_melted, aes(x = variable, y = value)) + geom_line(aes(color = cat, group = cat))
Upvotes: 7