简体   繁体   中英

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

Using matplotlib lib, I am plotting the plots and rendering the plots to HTML pages.

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. 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 ".

If you want them to be split, either:

I have the same problem, but with Flask. Simply insert plt.close(), after plt.save. The problem is solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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