[R] xyplot with all columns of a data.frame on a single plot

Rajarshi Guha rajarshi.guha at gmail.com
Wed Jul 28 02:51:20 CEST 2010


Thanks to everybody for the solutions.

On Tue, Jul 27, 2010 at 3:47 AM, Dennis Murphy <djmuser at gmail.com> wrote:
> Hi:
>
> Another approach might be to use the melt() function in package reshape
> before creating the plot with xyplot, something along the lines of the
> following:
>
> library(reshape)
> mdat <- melt(data, id = 'X')
>
> This should create a data frame with three columns: X, variable (all the D*
> names as factor levels) and value (stacked version of the D*s). Then use
> something like
>
> xyplot(value ~ X, data = mdat, groups = 'variable', ...)
> xyplot(value ~ X | variable, data = mdat, ...)
>
> One advantage of this approach is that you'll get the same structure out of
> melt() no matter how many D* columns you have;
> another is that the code block is small and relatively easy to remember six
> months from now.  Here's a simple toy example:
>
> library(reshape)
> library(lattice)
> d <- data.frame(x = 1:20, y1 = rnorm(20), y2 = rnorm(20), y3 = rnorm(20))
>
> # Reshape the data:
> m <- melt(d, id = 'x')
>
> # xyplot with a basic legend
>
> # melted data
> xyplot(value ~ x, data = m, groups = variable,
>     auto.key = list(space = 'right', points = TRUE, lines = FALSE))
> # plot from the original data
> xyplot(y1 + y2 + y3 ~ x, data = d,
>     auto.key = list(space = 'right', points = TRUE, lines = FALSE))   #
> identical except for y label
>
> HTH,
> Dennis
>
> On Mon, Jul 26, 2010 at 7:26 PM, Rajarshi Guha <rajarshi.guha at gmail.com>
> wrote:
>>
>> Hi, I have a data.frame with columns named X, D1, D2, D3
>>
>> I know I can get a single plot with 3 curves by doing
>>
>> xyplot(D1 + D2 + D3 ~ X, data)
>>
>> but in some cases I might have columns D1 ...  D10.
>>
>> Is there a way to plot all 10 columns without having to specify each
>> individual term?
>>
>> (By analogy with formulae in lm, I thought, xyplot(. ~ X, data) would
>> work, but it didn't)
>>
>> Thanks,
>>
>> --
>> Rajarshi Guha
>> NIH Chemical Genomics Center
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>



-- 
Rajarshi Guha
NIH Chemical Genomics Center



More information about the R-help mailing list