Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overlay plots from different cells?

In one of the cells in my notebook, I already plotted something with

myplot = plt.figure() plt.plot(x,y)

Now, in a different cell, I'd like to plot the exact same figure again, but add new plots on top of it (similar to what happens with two consecutive calls to plt.plot()). What I tried was adding the following in the new cell:

myplot plt.plot(xnew,ynew)

However, the only thing I get in the new cell is the new plot, without the former one.

How can one achieve this?

like image 418
JLagana Avatar asked Aug 18 '17 15:08

JLagana


People also ask

How do I overlay multiple plots in R?

To draw multiple plots in the R Language, we draw a basic plot and add an overlay line plot or scatter plot by using the lines() and the points() function. This line and scatter plot overlay can be drawn on top of any layer in the R Language.

How do you overlap two graphs in Matlab?

Combine Plots in Same Axes By default, new plots clear existing plots and reset axes properties, such as the title. However, you can use the hold on command to combine multiple plots in the same axes. For example, plot two lines and a scatter plot. Then reset the hold state to off.

What does it mean to overlay a plot?

Overlay plots are different plots (like vectors and contours) that are drawn on top of each other, and possibly on top of a map. There are many different ways that one can create overlay plots: Use the overlay procedure (this is the best method)


1 Answers

There are essentially two ways to tackle this.

A. Object-oriented approach

Use the object-oriented approach, i.e. keep handles to the figure and/or axes and reuse them in later cells.

import matplotlib.pyplot as plt
%matplotlib inline

fig, ax=plt.subplots()
ax.plot([1,2,3])

Then in a later cell,

ax.plot([4,5,6])

Suggested reading:

  • How to keep the current figure when using ipython notebook with %matplotlib inline?

  • How to add plot commands to a figure in more than one cell, but display it only in the end?

  • How do I show the same matplotlib figure several times in a single IPython notebook?

B. Keep figure in pyplot

The other option is to tell the matplotlib inline backend to keep the figures open at the end of a cell.

import matplotlib.pyplot as plt
%matplotlib inline

%config InlineBackend.close_figures=False # keep figures open in pyplot

plt.plot([1,2,3])

Then in a later cell

plt.plot([4,5,6])

Suggested reading:

  • '%matplotlib inline' causes error in following code

  • Manipulate inline figure in IPython notebook

like image 195
ImportanceOfBeingErnest Avatar answered Sep 28 '22 03:09

ImportanceOfBeingErnest