Reputation: 11
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.
Upvotes: 1
Views: 3319
Reputation: 1
I have the same problem, but with Flask. Simply insert plt.close(), after plt.save. The problem is solved.
Upvotes: 0
Reputation: 3845
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
Upvotes: 1
Reputation: 1594
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:
Upvotes: 0