lattice plots not working inside a function

2020-07-20 03:34发布

问题:

I have this R code, which works perfectly and i get the bitmap with the plot if i run it in R console or as a RScript

library(DBI);
library(RMySQL);
library(brew);
library(lattice);
con <- dbConnect(MySQL(),server credentials)
x <- dbGetQuery(con,"SELECT name, distance FROM distances")
bitmap("/tmp/dist_6078.bmp")
dotplot(x$distance~x$name, col='red', xlab='name', ylab='distance', main='Distance plot')
dev.off()

Issue is, i am getting a blank image if i enclose everything between <% and %> and use brew library. Everything works fine if i use basic R plots, issue is only when i use lattice.

回答1:

From the R FAQ 7.22

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

Working code

library(DBI);
library(RMySQL);
library(brew);
library(lattice);
con <- dbConnect(MySQL(),server credentials)
x <- dbGetQuery(con,"SELECT name, distance FROM distances")
bitmap("/tmp/dist_6078.bmp")
plot_obj <- dotplot(x$distance~x$name, col='red', xlab='name', ylab='distance', main='Distance plot')
print(plot_obj)
dev.off()