如何绘制R中数据帧的所有列 [英] how to plot all the columns of a data frame in R

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

问题描述

我在R中有一个数据框
数据框有n列,我想得到n个图,每列一个图。



我是一个新手,我不会流利的R,反正我找到两个解决方案。



第一个工作,但它不打印列名称(和我需要他们!):

  data<  -  read.csv(sample.csv,header = T,sep = ,)
(c在数据中)图(c,type =l)

第二个功能更好,因为它打印列名称:

  data < -  read.csv(sample.csv (header = T,sep =,)
for(i in seq(1,length(data),1))plot(data [,i],ylab = names(data [i] type =l)

有没有更好的(从R语言的角度来看)解决方案?



谢谢。
Alessandro

解决方案

ggplot2 包需要一点点的学习,但结果看起来真的很好,你会得到好的传说,还有许多其他很好的功能,所有这些都不需要编写太多的代码。

  require(ggplot2)
require(reshape)
df< - data.frame(time = 1:10,
a = cumsum(rnorm(10)),
b = cumsum(rnorm(10)),
c = cumsum(rnorm(10)))
df< - melt(df,id.vars ='time',variable.name ='series')

#在同一个网格上,每个系列颜色不同 -
#如果系列具有相同的缩放比例,
ggplot(df,aes(time,value))+ geom_line aes(color = series))

#或不同图上的曲线
ggplot(df,aes(时间,值))+ geom_line()+ facet_grid(系列〜)



I have a data frame in R. The data frame has n columns and I would like to get n plots, one plot for each column.

I'm a newbie and I am not fluent in R, anyway I found two solutions.

The first one works but it does not print the column name (and I need them!):

data <- read.csv("sample.csv",header=T,sep=",")
for ( c in data ) plot( c, type="l" )

The second one works better because it prints the column name:

data <- read.csv("sample.csv",header=T,sep=",")
for ( i in seq(1,length( data ),1) ) plot(data[,i],ylab=names(data[i]),type="l")

Is there any better (from the R language point of view) solutions?

Thank you. Alessandro

解决方案

The ggplot2 package takes a little bit of learning, but the results look really nice, you get nice legends, plus many other nice features, all without having to write much code.

require(ggplot2)
require(reshape)
df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))
df <- melt(df ,  id.vars = 'time', variable.name = 'series')

# plot on same grid, each series colored differently -- 
# good if the series have same scale
ggplot(df, aes(time,value)) + geom_line(aes(colour = series))

# or plot on different plots
ggplot(df, aes(time,value)) + geom_line() + facet_grid(series ~ .)

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

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