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

拈花ヽ惹草 提交于 2021-02-05 07:12:07

问题


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 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))



来源:https://stackoverflow.com/questions/40588050/plotting-a-line-for-each-row-in-a-dataframe-with-ggplot2-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!