简体   繁体   English

使用 mathplotlib 重叠多个图

[英]Overlapping of multiple plots with mathplotlib

两个图应该看起来相似,但不同请求的内容与左侧的图重叠 I am building a web application using Django that has an option of plotting plots like histograms, scatterplots, bar charts etc我正在使用 Django 构建一个 Web 应用程序,它可以选择绘制直方图、散点图、条形图等图

Using matplotlib lib, I am plotting the plots and rendering the plots to HTML pages.使用 matplotlib lib,我正在绘制绘图并将绘图渲染到 HTML 页面。

plt.figure()
plt.title("xyz")
plt.tight_layout()
plt.plot(x,y, 'b')   
plt.plot(x,z, 'r')    
buf = BytesIO()
fig = plt.gcf()
fig.set_size_inches(12,8, forward=True)
fig.savefig(buf, format='png')
plt.clf()

# Get Image
image_base64 = base64.b64encode(
    buf.getvalue()).decode('utf-8').replace('\n', '')

img_src = 'data:image/png;base64, {}'.format(image_base64)

When a user sends two different requests to plot different plots, the content like legend and data points are mixing with other plots and results in an overlap of plots.当用户发送两个不同的请求来绘制不同的图时,图例和数据点等内容与其他图混合并导致图重叠。 In the attached image, the plot on the left side should be similar to the plot on the right side.在附图中,左侧的图应与右侧的图相似。 But the content of different plot request is appended to this response and being displayed in this response.但是不同绘图请求的内容附加到此响应并显示在此响应中。

Its because the plt is resused multiple times.这是因为plt被多次重用。 Something like this should help..像这样的东西应该有帮助..

def simple(request):
    import random
    import django
    import datetime

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig=Figure()
    ax=fig.add_subplot(111)
    x=[]
    y=[]
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now+=delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

Source 来源

It's because you're plotting both graphs on the same figure .这是因为你在同一个绘制了两个 For matplotlib, this means: " Here is ONE canvas, please draw TWO graphs on it ".对于 matplotlib,这意味着:“这是一张画布,请在其上绘制两张图”。

If you want them to be split, either:如果您希望将它们拆分,请执行以下任一操作:

I have the same problem, but with Flask.我有同样的问题,但使用 Flask。 Simply insert plt.close(), after plt.save.只需在 plt.save 之后插入 plt.close()。 The problem is solved.问题已经解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM