从模块中使用matplotlib绘图
这是我第一次用Python来画图,我想我还不太明白matplotlib中对象之间的互动。我有以下这个模块:
import numpy as np
import matplotlib.pyplot as plt
def plotSomething(x,y):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')
ax.scatter(x,y) #(1)
plt.scatter(x,y) #(2)
当我调用这个函数(给定x和y)时,它可以正常绘图。
a) 如果我只注释掉(1)或(2),那么只会绘制坐标轴,而散点图就不会显示了。
b) 不过,如果我同时取消注释(1)和(2),并且在(1)或(2)中添加s=5和marker='+',那么图形中会显示两个标记(一个叠在另一个上),一个是默认的'o',另一个是'+',这意味着我实际上是把散点图绘制了两次。
但是——如果我在同时取消注释(1)和(2)的情况下绘制了两次,为什么我实际上需要同时保留(1)和(2)才能看到散点图呢?为什么在(a)的情况下我根本看不到散点图?
我很困惑。有人能帮我解答吗?
2 个回答
1
(我对不同对象之间是如何相互作用的不是很专业)
你应该加上 plt.show(),然后你可以选择(1)或者(2)。比如:
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
def plotSomething(x,y):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')
#ax.scatter(x,y) #(1)
plt.scatter(x,y) #(2)
plt.show()
x=[1,2,3]
y=[5,6,7]
plotSomething(x,y)
2
发生的事情可能和Python的垃圾回收有关。具体情况我不能告诉你,因为你提供的代码示例并没有显示图表。我猜测你是在函数外面显示图表,这样的话,你实际上是在绘制之前就执行了del fig
,也就是删除了图表的引用。
这样做应该是可以的:
def plotSomething(x,y):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')
ax.scatter(x,y)
fig.savefig('test.png')
如果你想延迟绘制图表,可以传递一个引用:
def plotSomething(x,y):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')
ax.scatter(x,y)
return fig