Reputation: 109
I am trying to use matplotlib
and mpld3
to produce some html plots on my Django
report app.
Basically I have a controller for the plot that is the following:
from django.shortcuts import render
import mpld3
from matplotlib.pyplot import figure, title, bar
def cpfLogin(request):
mpl_figure = figure(1)
xvalues = (1,2,3,4,5)
yvalues = (1,2,3,4,5)
width = 0.5 # the width of the bars
title(u'Custom Bar Chart')
bar(xvalues, yvalues, width)
fig_html = mpld3.fig_to_html(mpl_figure)
context = {
'figure': fig_html,
}
return render(request, 'reports/CPFReport.html', context)
The code for reports/CPFReport.html is:
{% load i18n %}
{% block extrahead %}
<style type="text/css">
.chart_title {
font-weight: bold;
font-size: 14px;
}
</style>
{% endblock %}
{% block content %}
<div id="content-main">
<div class="chart_title">
{% trans "Custom Bar Chart" %}
</div>
{{ figure|safe }}
</div>
{% endblock %}
The code is executed right and the plot is displayed correctly but after a couple of seconds the app terminates with the following error:
Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree), function NSViewSetCurrentlyBuildingLayerTreeForDisplay, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1561.20.106/AppKit.subproj/NSView.m, line 14480.
I found out that if I comment all the code this exception is thrown when any of the matplotlib
libraries are called.
Does anyone has a workaround or solution for this problem?
Upvotes: 2
Views: 746
Reputation: 11
To complete mapp mapp's answer, in this case it's linked to using matplotlib with a webserver. The solution recommended by matplotlib documentation is to use the Agg backend :
import matplotlib
matplotlib.use('Agg')
# then import pyplot and mpld3
import mpld3
from matplotlib.pyplot import figure, title, bar
Upvotes: 0
Reputation: 91
Adding plt.close() after saving the figure using fig.savefig('../static/images/something.png') helped me.
Upvotes: 0
Reputation: 1002
In my case I had to avoid importing :
import matplotlib.pyplot as plt
fig,ax = plt.subplots(figsize=(8,9))
l = plt.plot(x,s, 'y-', label="line")
and substitute it with:
from matplotlib.figure import Figure
fig = Figure()
ax = fig.add_subplot(111))
l = ax.plot(x,s, 'y-', label="line")
Upvotes: 2
Reputation: 11
Maybe I find the solution, just add the follow code in top.
import matplotlib
matplotlib.use('Agg')
For my case, I use python3, flask and matplotlib.
reference: https://gist.github.com/tebeka/5426211
Upvotes: 0