如何将 pyplot 函数附加到图形实例? [英] How can I attach a pyplot function to a figure instance?

查看:28
本文介绍了如何将 pyplot 函数附加到图形实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,我遇到了多个之间的干扰问题Matplotlib 数字.最后,我发现了一个问题,即某些 pyplot 函数没有附加到它们的图形实例,但可以在其他一些并行创建的图形实例中呈现.

Previously, I had a problem with the interference between multiple Matplotlib figures. Finally i got tracked that to an issue that some pyplot functions do not attach to their figure instance but can be rendered in some other figure instances which are created in parallel.

这是一些示例代码:

from django.http import HttpResponse
from numpy import arange, meshgrid
from matplotlib.mlab import bivariate_normal

def show_chart(request):
    delta = 0.025
    x = arange(-3.0, 3.0, delta)
    y = arange(-2.0, 2.0, delta)
    X, Y = meshgrid(x, y)
    Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    Z = 10.0 * (Z2 - Z1)

    from matplotlib.pyplot import figure, contour
    fig1 = figure(figsize=(4, 4), facecolor='white')
    contour(X, Y, Z)

    response = HttpResponse(content_type='image/png')
    fig1.savefig(response, format='png')
    fig1.clear()
    return response

上例中的轮廓 pyplot 函数可以在 fig1 中呈现,但偶尔也会在其他一些并行生成的图中呈现.那很烦人.有什么办法可以将轮廓pyplot函数附加到fig1上吗?

The contour pyplot function in the example above can get rendered in fig1, but occasionally also in some other figure that is generated in parallel. That is very annoying. Is there any way to attach the contour pyplot function to fig1?

推荐答案

您可以创建一个子图,然后调用子图的 contour 方法:

You can create a subplot and than call the contour method of the subplot:

fig1 = figure(figsize=(4, 4), facecolor='white')
ax = fig1.add_subplot(111)
ax.contour(X, Y, Z)

plt.subplots 可以方便地创建图形和一次调用的子图:

plt.subplots makes it convenient to create a figure and subplots with a single call:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

这篇关于如何将 pyplot 函数附加到图形实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆