Marc Wildi
Marc Wildi

Reputation: 21

Possible issue when plotting an xts-object from within a function

I up-graded to the latest R,xts,Rstudio versions today, Friday 8-March-2019. Here is a very simple example demonstrating a possible issue when plotting an xts object from a function. To demo the problem I have two cases: the 'working as it should' and the 'does not work' cases:

Here is the 'working as it should' case:

library(xts)
function_plot1<-function()
{
  data(sample_matrix)
  plot(as.xts(sample_matrix))
}

function_plot1()

I can see a plot in the plot-panel, as it should be.

And now the 'does not work' case:

function_plot<-function()
{

  data(sample_matrix)
  plot(as.xts(sample_matrix))
  print("")

}

function_plot()

In this example the plot does not appear anymore. The only difference between both functions above is that 'I do something' after the plot-call in the latter function (a print-order). The same problem would happen if I introduced some other commands (instead of the print). The issue appears when plotting an xts object in a function.

Upvotes: 2

Views: 44

Answers (1)

Clemsang
Clemsang

Reputation: 5481

Use print around your plot.

function_plot<-function()
{

  data(sample_matrix)
  print(plot(as.xts(sample_matrix)))
  print("")

}

function_plot()

A function return only the last evaluated exression, that is why the plot did not render.

Upvotes: 2

Related Questions