我得到了以下数据框,描述了不同德国地区的年龄结构:
我想用R中的ggplot每行绘制一行。通过R中的matplot的简单解决方案是:
matplot(t(df61[,-c(1,2)], type="l"))
产生:
但是如何使用ggplot。我明白了,我必须将数据帧转换为平面形式:
library("reshape2")
df61_long <- melt(df61[,-2], id.vars = "NAME")
这给了我:
我认为通过ggplot的解决方案应该是这样的:
ggplot(df61_long, aes(x = "variable", y = "value")) + geom_line(aes(colors = "NAME"))
然而,产生一个空坐标系。我做错了什么?
答案 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
。group
。此代码有效:
ggplot(df_melted, aes(x = variable, y = value)) + geom_line(aes(color = cat, group = cat))