如何使用matplotlib显示两个图形?
我在同时绘制两个图形时遇到了一些问题,结果没有在一个图上显示出来。不过根据说明文档,我写的代码只显示了第一个图形。我觉得我可能遗漏了一些重要的东西。有没有人能帮我解决这个问题?谢谢! (代码中用到的 *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()
4 个回答
39
我也遇到过这个问题。
我做了以下操作:
f1 = plt.figure(1)
# code for figure 1
# don't write 'plt.show()' here
f2 = plt.figure(2)
# code for figure 2
plt.show()
只在最后一张图之后写一次 'plt.show()'。这样做对我有效。
65
你应该在创建完所有图表之后,再调用 plt.show()
。
108
除了在脚本最后调用 plt.show()
来显示图形之外,你还可以单独控制每个图形,方法是:
f = plt.figure(1)
plt.hist........
............
f.show()
g = plt.figure(2)
plt.hist(........
................
g.show()
raw_input()
在这种情况下,你需要调用 raw_input
来保持图形的显示状态。这样你就可以动态选择想要显示的图形。
注意:在 Python 3 中,raw_input()
被改名为 input()
。