使用R中的ggplot2为Dataframe中的每一行绘制一条线

时间:2016-11-14 11:48:43

标签: r ggplot2

我得到了以下数据框,描述了不同德国地区的年龄结构:

enter image description here

我想用R中的ggplot每行绘制一行。通过R中的matplot的简单解决方案是:

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

产生:

enter image description here

但是如何使用ggplot。我明白了,我必须将数据帧转换为平面形式:

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

这给了我:

enter image description here

我认为通过ggplot的解决方案应该是这样的:

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

产生一个空坐标系。我做错了什么?

1 个答案:

答案 0 :(得分:5)

你的例子不可复制,所以我自己做了:

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

在您的代码中:

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

有很多问题:

  • 没有colors美学,应该是color
  • 美学不应该作为字符串传递给aes。请使用aes_string
  • 在这种情况下,您需要额外的aes group

此代码有效:

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

enter image description here