如何使用 matplotlib 显示两个图形?

我在同一时间画两个人物时遇到了一些麻烦,而不是在一个情节中显示出来。但是根据文档,我编写了代码,并且只显示了图1。我觉得我可能丢了什么重要的东西。有人能帮我弄清楚吗?谢谢。(代码中使用的 * tlist _ first * 是一个数据列表。)

plt.figure(1)
plt.hist(tlist_first, bins=2000000, normed = True, histtype ="step", cumulative = True, color = 'g',label = 'first answer')
plt.ylabel('Percentage of answered questions')
plt.xlabel('Minutes elapsed after questions are posted')


plt.axvline(x = 30, ymin = 0, ymax = 1, color = 'r', linestyle = '--', label = '30 min')
plt.axvline(x = 60, ymin = 0, ymax = 1, color = 'c', linestyle = '--', label = '1 hour')
plt.legend()
plt.xlim(0,120)
plt.ylim(0,1)
plt.show()
plt.close() ### not working either with this line or without it


plt.figure(2)
plt.hist(tlist_first, bins=2000000, normed = True, histtype ="step", cumulative = True, color = 'g',label = 'first answer')


plt.ylabel('Percentage of answered questions')
plt.xlabel('Minutes elapsed after questions are posted')


plt.axvline(x = 240, ymin = 0, ymax = 1, color = 'r', linestyle = '--', label = '30 min')
plt.axvline(x = 1440, ymin = 0, ymax = 1, color = 'c', linestyle = '--', label = '1 hour')
plt.legend(loc= 4)
plt.xlim(0,2640)
plt.ylim(0,1)
plt.show()
261069 次浏览

You should call plt.show() only at the end after creating all the plots.

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()


g = plt.figure(2)
plt.hist(........
................
g.show()


raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

Alternatively, I would suggest turning interactive on in the beginning and at the very last plot, turn it off. All will show up, but they will not disappear as your program will stay around until you close the figures.

import matplotlib.pyplot as plt
from matplotlib import interactive


plt.figure(1)
... code to make figure (1)


interactive(True)
plt.show()


plt.figure(2)
... code to make figure (2)


plt.show()


plt.figure(3)
... code to make figure (3)


interactive(False)
plt.show()

I had this same problem.


Did:

f1 = plt.figure(1)


# code for figure 1


# don't write 'plt.show()' here




f2 = plt.figure(2)


# code for figure 2


plt.show()


Write 'plt.show()' only once, after the last figure. Worked for me.