Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R package lattice won't plot if run using source()

I started using the lattice graphic package but I stumbled into a problem. I hope somebody can help me out. I want to plot a histogram using the corresponding function.

Here is the file foo.r:

library("lattice")

data <- data.frame(c(1:2),c(2:3))
colnames(data) <- c("RT", "Type")

pdf("/tmp/baz.pdf")
histogram( ~ RT | factor(Type), data = data)
dev.off()

When I run this code using R --vanilla < foo.r it works all fine.

However, if I use a second file bar.r with

source("bar")

and run R --vanilla < bar.r the code produces an erroneous pdf file. Now I found out that source("bar", echo=TRUE) solves the problem. What is going on here? Is this a bug or am I missing something?

I'm using R version 2.13.1 (2011-07-08) with lattice_0.19-30

like image 421
woobert Avatar asked Jul 21 '11 21:07

woobert


People also ask

Why won't my plots show up in RStudio?

Tools->Global options->R Mark down In that phase select "window" from that list in the "show output preview in:" then apply. Tools > Global Options > Pane Layout, "Plots" is checked. Update the RStudio.

Which function used to create scatter plot in lattice package?

The xyplot() function can be used to create a scatter plot in R using the lattice package.


2 Answers

It is in the FAQ for R -- you need print() around the lattice function you call:

7.22 Why do lattice/trellis graphics not work?

The most likely reason is that you forgot to tell R to display the graph. Lattice functions such as xyplot() create a graph object, but do not display it (the same is true of ggplot2 graphics, and Trellis graphics in S-Plus). The print() method for the graph object produces the actual display. When you use these functions interactively at the command line, the result is automatically printed, but in source() or inside your own functions you will need an explicit print() statement.

like image 133
Dirk Eddelbuettel Avatar answered Oct 05 '22 02:10

Dirk Eddelbuettel


Example of the case

  1. visualise.r
    • calls plot2this.r
      • calls ggplot2 and returns p object

Here the fix in the function plot2this.r from return(p) to return(print(p)).

Initial plot2this.r

p <- ggplot(dat.m, aes(x = Vars, y = value, fill=variable)) 
return(p)

Fix

p <- ggplot(dat.m, aes(x = Vars, y = value, fill=variable)) 
return(print(p))

Output now: expected output with the wanted plot.

like image 27
Léo Léopold Hertz 준영 Avatar answered Oct 05 '22 01:10

Léo Léopold Hertz 준영