Skip to main content
 首页 » 编程设计

python之Matplotlib 不适用于 OSX 上的 Python 2.7 和 Django

2024年09月07日37telwanggs

我正在尝试使用 matplotlib 和 mpld3 在我的 Django 报告应用程序上生成一些 html 图。

基本上我有一个如下图的 Controller :

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) 

reports/CPFReport.html 的代码是:

 {% 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 %} 

代码正确执行并且绘图正确显示,但几秒钟后应用程序终止并出现以下错误:

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.

我发现,如果我注释所有代码,则在调用任何 matplotlib 库时都会抛出此异常。

有人对此问题有解决方法或解决方案吗?

请您参考如下方法:

在我的例子中,我不得不避免导入:

import matplotlib.pyplot as plt 
 
fig,ax = plt.subplots(figsize=(8,9)) 
l      = plt.plot(x,s, 'y-', label="line") 

并将其替换为:

from matplotlib.figure import Figure 
 
fig = Figure() 
ax  = fig.add_subplot(111)) 
l   = ax.plot(x,s, 'y-', label="line")