【问题标题】:Matplotlib not working with Python 2.7 and Django on OSXMatplotlib 无法在 OSX 上使用 Python 2.7 和 Django
【发布时间】:2018-08-23 12:19:47
【问题描述】:

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

基本上,我有一个控制器用于以下情节:

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

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

断言失败:(NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentBuildingLayerTree), 函数 NSViewSetCurrentlyBuildingLayerTreeForDisplay,文件 /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1561.20.106/AppKit.subproj/NSView.m, 第 14480 行。

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

有没有人有这个问题的解决方法或解决方案?

【问题讨论】:

  • 我在 python 3.6 上遇到了同样的问题。
  • 您找到解决方案了吗?也有这个问题

标签: python django macos python-2.7 matplotlib


【解决方案1】:

为了完成 mapp mapp 的回答,在这种情况下,它与使用 matplotlib 和网络服务器相关联。 matplotlib documentation 推荐的解决方案是使用 Agg 后端:

import matplotlib
matplotlib.use('Agg')
# then import pyplot and mpld3
import mpld3
from matplotlib.pyplot import figure, title, bar

【讨论】:

    【解决方案2】:

    使用 fig.savefig('../static/images/something.png') 保存图形后添加 plt.close() 对我有帮助。

    【讨论】:

      【解决方案3】:

      就我而言,我不得不避免导入:

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

      【讨论】:

        【解决方案4】:

        也许我找到了解决办法, 只需在顶部添加以下代码即可。

        import matplotlib
        matplotlib.use('Agg')
        

        就我而言,我使用 python3、flask 和 matplotlib。

        参考: https://gist.github.com/tebeka/5426211

        【讨论】:

          猜你喜欢
          • 2016-12-27
          • 2013-08-27
          • 2012-06-29
          • 1970-01-01
          • 2016-11-29
          • 1970-01-01
          • 1970-01-01
          • 2013-08-31
          • 2011-08-23
          相关资源
          最近更新 更多