python - 从模块中使用 matplotlib 进行绘图

标签 python 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) 都未注释,并且我将 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/

相关文章:

python - scala:具有可变长度参数的函数对象的特征?

python - 如何在 matplotlib 散点图中标准化颜色图?

Python:Matplotlib Surface_plot

python - 用于 patchcollection 的带有颜色的图例

python 将字符串数字拆分为数字

python - 使用径向基函数在球体上插值函数

python - 占位符类方法 Python 3

python - Django + SQLite 如何在发生 "database is locked"错误时增加 SQLite 超时

python - 随机图Python networkx读取文件并绘制图表

python - 从 Pandas 数据框创建多个图