问题
I'm still new to IPython Notebooks, Jupyter, and Python in general.
I'm creating a scatter plot in a Jupyter notebook using the following code:
import numpy as np
import matplotlib.pyplot as plt
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
plt.axes([0.025, 0.025, 0.95, 0.95])
plt.scatter(X, Y, s=50)
plt.show()
My question is, how can I get a reference to the plot object so I can use it in a different cell later on in the notebook? Additionally, I may need to modify the plot before showing it again.
Also, I have %matplotlib inline
at the top of my notebook.
Here are some info about my environment:
- Python: 3.5.2 64bit [MSC v.1900 64 bit (AMD64)]
- IPython: 4.2.0
- numpy: 1.11.1
- scipy: 0.17.1
- matplotlib: 1.5.1
- sympy: 1.0
- OS: Windows 7 6.1.7601 SP1
回答1:
I have found a solution! Basically you create a figure and the axis with fig, ax = plt.subplots()
and then use the ax
variable to draw (potentially in multiple cells). In any of the cells you want to replot the figure, just write fig
as the last line of the cell, resulting in the cell using the updated figure as output.
See my answer here for more details.
回答2:
Try the object-oriented interface of matplotlib - matplotlib.figure; you can use the reference of the Figure object created, as required.
- Create a figure object -
fig = plt.figure()
- Add axes to it -
ax = fig.add_axes([0.025, 0.025, 0.95, 0.95])
- Plot on the axis created -
ax.plot(X, Y)
来源:https://stackoverflow.com/questions/38754107/ipython-how-to-show-the-same-plot-in-different-cells