0

I am trying to attribute a plot to a variable in order to plot many graphs in the same plot. Here is the code:

hist(res.ins, breaks=500, freq=F, xlab="Residuals", main="A")
lines(x, dnorm(x, mean(res.ins, na.rm=T), sd(res.ins, na.rm=T)), col="red", lwd=2)

Resulting plot is here!

I'd like to store this graph in a variable plot1, but

plot1 <- hist(res.ins, breaks=500, freq=F, xlab="Residuals", main="A") +
lines(x, dnorm(x, mean(res.ins, na.rm=T), sd(res.ins, na.rm=T)), col="red", lwd=2)

...doesn work, I tried to use {...}, but it does not work as well.

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Note that base graphics plotting functions to not create objects. The run with "side-effects" that render images to the current plotting device. In fact, `hist()` returns a data.summary. Why are you string to save these to a variable? You could get around it using [recordPlot](https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/) but that might not always be the best solution. Note that `hist()` and `lines()` aren't two separate plots. The `lines()` draws on top of `hist()`. `recordPlot` would work fine for these. – MrFlick Jul 31 '20 at 22:22
  • Ok. I usually use ggplot2, but I created these plots and thought that the results went very well. I became just lazy to reproduce it exactly as it is in ggplot. But, listening to your comment, I think this is the best idea. Thank you. – Vitor Hugo Moreau Jul 31 '20 at 22:28
  • To use the `{...}` construct, you need to add the tilde `~` in front as so... `plot1 <- ~{...}`. – Edward Jul 31 '20 at 23:41

0 Answers0