Issue
I am working on jupyter notebook and I am using matplotlib.pyplot.subplot()
inside a for loop. In the same cell of the for loop, I called plt.show()
to show the graphs. However, they are too small, so I am looking to replot them on another notebook cell without having to repeat the loop, which is time-consuming.
So basically I ran the cell with a code that looks like this:
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(5,1)
for ii in range(5):
#some time consuming operations
axs[ii].plot(np.random.randn(10))
plt.show()
I realise that the figure is too small so in the subsequent cell I would like to reshow the previous plots on a larger figure. Since all the information is contained in fig
and axs
I am assuming that I do not have to repeat the loop but just to tell matplotlib to show again the plots whose information should already be in the axs
variable.
Solution
You can extract matplotlib artists from the original Figure and Axes and create new Figures and Axes using Matplotlib's oop features.
This mre creates a new Figure and Axes; gets the x and y data from each Line2D of the original axes and uses it to plot with the new Axes.
fig, ax = plt.subplots() # Create a figure containing a single axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes.
ax.plot([1, 2, 3, 4], [2,4,6,8]) # Plot some data on the axes.
plt.show()
fig1,ax1 = plt.subplots()
for line in ax.get_lines():
x,y = line.get_data()
ax1.plot(x,y)
fig1.show()
whose information should already be in the axs variable
There is indeed a lot of stuff in those objects. It is informative to see what is in there. Try:
>>> from pprint import pprint
>>> pprint(fig.properties())
and
>>> pprint(ax.properties())
and
>>> for line in ax.get_lines():
... pprint(line.properties())
I recommend working through the Matplotlib Tutorials, sometimes using the OOP features are the best/easiest way to really fine-tune your plots. Even after that you'll need to consult the documentation for the Artists to look for specific methods and attribute.
Answered By - wwii
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.