这是我第一次使用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) 都未注释,并且我将 vars s=5,marker='+' 添加到 (1) XOR (2) 中,则该图将显示两个标记(一个在另一个之上) - 默认的“o”和“+”,这意味着我实际上绘制了两次散点图。
但是 - 如果通过将 (1) 和 (2) 都取消注释,我会绘制两次,为什么我实际上需要同时具有 (1) 和 (2) 才能看到任何分散?为什么在情况(a)中我根本没有得到散点图?
我很困惑。有人可以指导我吗?
最佳答案
发生的事情可能与 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
关于python - 从模块中使用 matplotlib 进行绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5089994/