如何在R中绘制数据框的所有列 [英] How to plot all the columns of a data frame in R
问题描述
数据框有 n 列,我想得到 n 个图,每列一个图.
The data frame has n columns and I would like to get n plots, one plot for each column.
我是新手,R 不太流利,无论如何我找到了两个解决方案.
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")
有没有更好的(从 R 语言的角度来看)解决方案?
Is there any better (from the R language point of view) solutions?
推荐答案
ggplot2
包需要一点学习,但结果看起来非常不错,你得到了不错的图例,以及许多其他不错的功能,无需编写大量代码.
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(reshape2)
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屋!