python - 为函数指定 matplotlib 图形和轴的惯用方法是什么?

标签 python matplotlib

我想做的可以这样写:

import pylab
class GetsDrawn(object):
    def __init__(self):
        self.x=some_function_that_returns_an_array()
        self.y=some_other_function_that_returns_an_array()

    # verison 1: pass in figure/subplot arguments
    def draw(self, fig_num, subplot_args ):
        pylab.figure(fig_num)
        pylab.subplot( *subplot_args )
        pylab.scatter( self.x, self.y)

即我可以通过图形编号和子图配置告诉对象“在哪里”绘制自己。

我怀疑传递 pylab 对象的版本在以下方面会更灵活 从长远来看,但不知道要向函数提供什么类型的对象。

最佳答案

对于脚本来说,通常首选使用面向对象的 API。

例如,您可以让您的函数接收一个数字:

def draw(fig, sub_plot_args,x,y):
    ax = fig.subplot(*sub_plot_args)
    ax.scatter(x,y)

如果您的函数实际上仅在一个轴上绘制,您甚至可以将其作为对象传递:

def draw(ax,x,y):

    ax.scatter(x,y)

要创建图形,请使用:

import matplotlib.pyplot as plt
fig = plt.figure()

要创建一个带有子图的图形,请使用:

fig, ax = plt.subplots()

如果我没记错的话,最后一个命令只存在于最近的版本中。

关于python - 为函数指定 matplotlib 图形和轴的惯用方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13290277/

相关文章:

python - 重构代码以便使用 3 个值来制作绘图和元组索引必须是整数,而不是 float

python - 如何在 Python 直方图中有对数 bin

python - 3D 旋转

python - 在 matplotlib imshow 函数中更改像素形状

python - jupyter 按顺序打印图和数据框,for 循环

python-3.x - python 3.6.1 中的运行时错误 : Failed to open TrueType font in matplotlib. backends_pdf

python - 如何在 ArtistAnimation 中显示更改子图标签 (plt.text) 的进度以及颜色变化

java - 如何使用 ANTLR 获取 Python 中每个函数的 ast

Python网络机器人: How can I tell him to push this button?

python - 程序包只能在IDLE或解释器中正常工作,而不能独立运行吗?