Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot all the columns of a data frame in R

Tags:

dataframe

plot

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?

like image 855
Alessandro Jacopson Avatar asked Feb 02 '11 16:02

Alessandro Jacopson


People also ask

How do I select all columns in R?

To pick out single or multiple columns use the select() function. The select() function expects a dataframe as it's first input ('argument', in R language), followed by the names of the columns you want to extract with a comma between each name.


2 Answers

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 ~ .) 

enter image description hereenter image description here

like image 83
Prasad Chalasani Avatar answered Oct 11 '22 22:10

Prasad Chalasani


There is very simple way to plot all columns from a data frame using separate panels or the same panel:

plot.ts(data) 

Which yields (where X1 - X4 are column names):

enter image description here

Have look at ?plot.ts for all the options.

If you wan't more control over your plotting function and not use a loop, you could also do something like:

par(mfcol = c(ncol(data), 1)) Map(function(x,y) plot(x, main =y), data, names(data)) 
like image 21
Matti Pastell Avatar answered Oct 11 '22 22:10

Matti Pastell