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

查看:78
本文介绍了如何将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函数可以在图1中呈现,但有时在其他并行生成的图中也可以呈现.太烦人了.有什么方法可以将轮廓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天全站免登陆