I would like to add to an existing plot `p0`

without mutating it.

Currently I have to repeat code

```
using Plots;
xg = 0.01:0.01:10.0;
p0 = plot(xg, sin, legend=:topleft)
p0 = plot!(p0, xg, cos)
p1 = plot!(p0, xg, log)
p0 = plot(xg, sin, legend=:topleft)
p0 = plot!(p0, xg, cos)
p2 = plot!(p0, xg, sqrt)
```

I want:

```
using Plots;
xg = 0.01:0.01:10.0;
p0 = plot(xg, sin, legend=:topleft)
plot!(p0, xg, cos)
p1 = plot(p0, xg, log)
p2 = plot(p0, xg, sqrt)
```

Just add more `plot`

commands

```
using Plots;
xg = 0.01:0.01:10.0;
p0 = plot(xg, sin, legend=:topleft)
plot!(p0, xg, cos)
p1 = plot(p0, plot(xg, log))
p2 = plot(p0, plot(xg, sqrt))
```

1 Like

@pdeffebach that creates a subplot.

I want to add a curve to `p0`

without mutating it.

Oh sorry, I see.

Only thing I could think of was `deepcopy`

. Maybe thatâ€™s wrong in some way, though.

```
julia> begin
using Plots;
xg = 0.01:0.01:10.0;
p0 = plot(xg, sin, legend=:topleft)
plot!(p0, xg, cos)
p1 = plot!(deepcopy(p0), xg, log)
end
```

2 Likes

Can I ask why it is nice to do it this way compared with just mutating it?

Out of curiosity.

Kind regards

The one use case immediately came to my mind is creating a bunch of plots with the same â€śbackgroundâ€ť. (As in the OP) One could wrap the background plot generation into a function but recalculation might be more expensive than just copying the plot and using it later.

Edit: typo

2 Likes