3

I tried to reproduce this example on how to use grid.arrange with two plots, with the sole adjustment that I change some of my data in between. The strange thing is that this changes the first plot that I stored. An example:

require(data.table)
require(ggplot2)

dt <- data.table(x=1:200, y=rnorm(200)) # Sample data

t1 <- qplot(y, data=dt) # Histogram of y
t1 # Show plot

dt[, y := x] # Change y to x
t1 # t1 changed...

I'm assuming that this is somehow intended behavior of ggplot2. Hence, my question is whether it is somehow possible to make t1 persistent to this change, i.e., to store the plot in a way that it doesn't change if the underlying data is changed.

My use case is an rmarkdown file in which I want to show the unchanged and changed variable side by side.

Plot before and after y has been changed, respectively

altabq
  • 1,322
  • 1
  • 20
  • 33
  • There must be something different about your actual code because I get an error when I run the above commands because `y` is not defined outside of `dt`. Somehow you are connecting the two. Please try to make sure your example is [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Feb 07 '18 at 17:03
  • 5
    Because pointers and assign by reference for data.table – Clayton Stanley Feb 07 '18 at 17:11
  • You don't get this behavior with ```tibbles``` from the ```tidyverse```. – rsmith54 Feb 07 '18 at 19:10
  • @MrFlick I was missing the `data=dt` in qplot(...). – altabq Feb 07 '18 at 21:36
  • @ClaytonStanley, you're right, `data.table` causes this. When creating t1 as `t1 <- qplot(y, data=as.data.frame(dt))`, the problem does not occur. I guess that's the solution then. – altabq Feb 07 '18 at 21:38
  • 1
    You can also use the copy command if you want a more data.table idiomatic way to show that you want a fresh mem allocation of that table. – Clayton Stanley Feb 08 '18 at 20:57
  • Thanks! That's the right solution for me actually. If you post it as an answer, I'll accept it – altabq Feb 11 '18 at 19:46

0 Answers0