本文介绍了在R中使用ggplot2在数据框中为每一行绘制一条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I got the following dataframe describing the age structure in different german districts:

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

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

产生:

但是它如何与ggplot一起工作.我了解,我必须将数据框转换为平面形式:

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

哪个给我:

我认为通过ggplot的解决方案应该类似于:

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?

推荐答案

您的示例不可复制,所以我做了自己的事情:

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

在您的代码中:

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

有很多问题:

  • 没有 colors 美学,应该是 color .
  • 美学不应作为字符串传递给 aes .为此使用 aes_string .
  • 在这种情况下,您需要额外的aes, group .
  • 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.

此代码有效:

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

这篇关于在R中使用ggplot2在数据框中为每一行绘制一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 10:31