问题
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?
回答1:
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
colorsaesthetic, should becolor. - Aesthetics should not be passed as strings to
aes. Useaes_stringfor 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))
来源:https://stackoverflow.com/questions/40588050/plotting-a-line-for-each-row-in-a-dataframe-with-ggplot2-in-r