用ggplot绘制数据帧的所有行 [英] Plot all rows of a data frame with ggplot

查看:70
本文介绍了用ggplot绘制数据帧的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R很陌生,在这里可能会有一个愚蠢的问题".

I ham fairly new to R and I might have a rather "stupid question" here.

我有一个数据框,其中包含10个传感器(名为X1,X2,... X10)的多个测量值.每行编号表示试用编号.因此,例如,假设我们有7次试验,则数据框如下所示:

I have a data frame that consists multiple measurements of 10 sensors (named X1,X2,...X10). Each row number indicates the the trial number. So for example if we assume we have 7 trials then the data frame looks something like this:

    X1  X2  X3  X4  X5  X6  X7  X8  X9  X10
1   5   2   6   0   10  10  3   1   8   9
2   1   2   2   10  1   0   8   2   5   5
3   9   0   0   8   7   9   10  3   3   5
4   10  9   5   6   7   9   0   9   8   6
5   1   4   2   4   3   10  8   0   1   7
6   5   2   10  7   6   0   4   1   8   7
7   10  2   2   1   4   3   2   4   6   2

我想将所有行绘制在一起.例如,对于第一次试用,x将为1:10,而y是数据帧的第一行.

I want to plot all the rows together. For example for the first trial x will be 1:10 and y is the first row of the data frame.

我知道执行此操作的一些方法,但是如何使用ggplot执行此操作? 谢谢

I know some ways to do this but how can I use ggplot to do this ? Thanks

推荐答案

您需要做的是将数据帧重组为长格式.有很多方法可以做到这一点.一种快速的方法可能是使用reshape2软件包,例如

What you need to do is restructure the dataframe into a long format. There are many ways to do it. A quick one could be to use reshape2 package e.g.

您的数据:

df <- read.table(text="    X1  X2  X3  X4  X5  X6  X7  X8  X9  X10
1   5   2   6   0   10  10  3   1   8   9
2   1   2   2   10  1   0   8   2   5   5
3   9   0   0   8   7   9   10  3   3   5
4   10  9   5   6   7   9   0   9   8   6
5   1   4   2   4   3   10  8   0   1   7
6   5   2   10  7   6   0   4   1   8   7
7   10  2   2   1   4   3   2   4   6   2", header=T)


library(reshape2)
df <- melt(df)  #the function melt reshapes it from wide to long
df$rowid <- 1:7  #add a rowid identifying variable

您的数据框现在看起来像这样:

your dataframe now looks like this:

head(df, 10)

#   variable value rowid
#1        X1     5     1
#2        X1     1     2
#3        X1     9     3
#4        X1    10     4
#5        X1     1     5
#6        X1     5     6
#7        X1    10     7
#8        X2     2     1
#9        X2     2     2
#10       X2     0     3

然后您可以绘制此图

library(ggplot2)

散点图:

ggplot(df, aes(variable, value, group=factor(rowid))) + geom_point(aes(color=factor(rowid)))

折线图:

ggplot(df, aes(variable, value, group=factor(rowid))) + geom_line(aes(color=factor(rowid)))

变量是您的x轴, 值是您的y轴. 我已经将变量"rowid"作为一个因素,我们也通过该因素进行着色

variable is your x-axis, value is your y-axis. I've made the variable 'rowid' a factor and we color by this factor also

看起来像这样:

然后您可以尝试使用ggplot主题,使其看起来更好.

You can then play around with ggplot themes to make it look much nicer.

这篇关于用ggplot绘制数据帧的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆