Show only selected or specific matplotlib figures

北城余情 提交于 2021-01-27 02:27:22

问题


I am generating a total of 50+ figures but I do not wish to display them all. I would like to pick out the figures that I want to display. Is there any way to do it?

For example: I have 50 plots which are generated over the course of the program. At the end, when I enter plt.show(), it shows all the figures. However, I would like to display only 3 or 4 figures (but they aren't fixed i.e, I could plot figures 1, 2, 3, 4 at one time and another time I could plot figures 10, 27, 33, 45). Also, a separate function is generating these figures and I am returning all the figures.

Sample main script:

import matplotlib.pylab as plt
import numpy as np
from sampleplotfn import *


A = 1
omega = np.linspace(10,35,50)

for i in range(len(omega)):
    fig1 = sinewave(A,omega[i])

plt.show()

samplepltfn.py

import numpy as np
import matplotlib.pylab as plt


def sinewave(A,omega):
      t = np.linspace(0,10,25)
      f = A*np.sin(omega*t)
      fig1 = plt.figure()
      plt.plot(f,t)
      return fig1

回答1:


If you really want to plot only some, you can do so by calling the show method of the individual figures, as long as you've made the figures using plt.figure. E.g. if you made fig1 and fig2, you could show only fig2 if you called fig2.show() instead of plt.show(). However, I agree with jeanrc's comment - you should weed the plots you want before making them instead of keeping a ton of non-shown plots (they still take up memory and you have to remember to clean them up!)

Additionally, I would highly recommend against using pylab, and in particular, against using "plt" as an import alias for it. "plt" is traditionally used for pyplot, not pylab. (import matplotlib.pyplot as plt). Pylab includes a ton of other stuff and is discouraged from use except for interactive work.

Lastly, you are overwriting "fig1" in your loop. Try saving the figures into a list instead of a single variable.




回答2:


According that you have created 2 figures, but you want to show only the first one:

import random

f1, a1 = plt.subplots()
a1.plot(random.sample(range(100), 20))

f2, a2 = plt.subplots()
a2.plot(random.sample(range(100), 20))

f1.show() will not work in a script.

As suggested in comments, you could instead close the figures you don't want to see before you call:

plt.close(f2)
plt.show()

A more generic solution that work for a large number of figures is to iterate over all figures and close them, except the one you want to show:

for fig_num in plt.get_fignums():
     if figure.number != fig_num:
         plt.close(figure.number)
plt.show()

Or, using generators:

[plt.close(f) for f in plt.get_fignums() if f != f1.number]
plt.show()


来源:https://stackoverflow.com/questions/31249027/show-only-selected-or-specific-matplotlib-figures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!