0

I am trying to display a plot with matplotlib and django following this and this questions, however it seems not working, I tried both solutions and only while using IO i get an empty canvas, but when I try to plot a 'real' plot I get the error in the title.

This is my view:

import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as 
FigureCanvas
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt
import io


def mplimage(request):
    fig = Figure()
    canvas = FigureCanvas(fig)
    x = np.arange(-2, 1.5, .01)
    y = np.sin(np.exp(2 * x))
    plt.plot(x, y)
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(fig)
    response = django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

and here the link in urls.py:

    import mpl.views
    url(r'mplimage.png', mpl.views.mplimage)
sanna
  • 1,398
  • 5
  • 16
  • 24

2 Answers2

0

This works if you save the file objects as JPEG (requires PIL) instead of PNG using print_jpg() method instead of print_png().

Change:

response = django.http.HttpResponse(content_type='image/png') canvas.print_png(response)

To:
response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response)

jredd
  • 170
  • 6
  • Curious why it works, because indeed it does work. It seems https://stackoverflow.com/questions/49542459/error-in-django-when-using-matplotlib-examples has some answers. –  Oct 14 '19 at 13:56
0
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np
import django
def showimage(request):
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    x = np.arange(-2,1.5,.01)
    y = np.sin(np.exp(2*x))
    ax.plot(x, y)
    response = HttpResponse(content_type='image/jpg')
    canvas.print_jpg(response)
    return response
U13-Forward
  • 69,221
  • 14
  • 89
  • 114