Plotting to a file from a function in R

2019-07-18 17:44发布

问题:

Background

Hey everyone!

I'm new to using R, and became interested in using it after having a team member give a tutorial of how useful it can be in an academic setting.

I am trying to write a script to automatically read my data from multiple files and then plot the resultant graphs to multiple files, so that they can be easily added to a manuscript (PowerPoint, latex, etc.)

Problem

I have found that the following code will allow me to produce a graph

p = qplot(factor(step), y, data=x, colour=c))
p = p + theme_bw()
# etc...

wrapping this around a png call will allow me to output the plot to a PNG:

png("test.png")
p = qplot(factor(step), y, data=x, colour=c))
p = p + theme_bw()
# etc...
p
dev.off()

I wanted to put the graph creation into a function so that I can create graphs and consequent seperate PNGs. So I put everything into a function:

func <- function()
{
    png("test.png")
    p = qplot(factor(step), y, data=x, colour=c))
    p = p + theme_bw()
    # etc...
    p
    dev.off()
}

If I call func() A PNG is created, but it is empty. Is there any specific reason why I can do this without the function but can't when I'm calling it from a function?

回答1:

When using ggplot2 or lattice non-interactively (i.e. not from the command-line), you need to explicitly print() plots that you've constructed. So just do print(p) in the final line of your code, and all should be fine.

This is unintuitive enough that it's one of the most frequent of all FAQs.



标签: r plot ggplot2