Печать графика matplot в django?

Views.py:-

from django.shortcuts import render, HttpResponse
from tweetanalysis import tweety
import matplotlib.pyplot as plt
import pandas as pd
import base64
from io import BytesIO
# Create your views here.


def index(request):
    return render(request, 'index-search.html')


def result(request):
    if request.method == 'POST':
        query = request.POST.get('hashtage')
        df = tweety.Analyzer(query)
        plt.figure(figsize=(8, 6))
        for i in range(0, df.shape[0]):
            plt.scatter(df.loc[i, 'Polarity'],
                        df.loc[i, 'Subjectivity'], color='Blue')

        plt.title('Sentiment Analysis')
        plt.xlabel('Polarity')
        plt.ylabel('Subjectivity')
        buffer = BytesIO()
        plt.savefig(buffer, format='png')
        buffer.seek(0)
        image_png = buffer.getvalue()
        ans1 = base64.b64encode(image_png)
        ans1 = ans1.decode('utf-8')
        buffer.close()

        plt.title('Sentiment Analysis')
        plt.xlabel('Polarity')
        plt.ylabel('Subjectivity')
        df['Analysis'].value_counts().plot(kind='bar')
        buffer = BytesIO()
        plt.savefig(buffer, format='png')
        buffer.seek(0)
        image_png = buffer.getvalue()
        ans2 = base64.b64encode(image_png)
        ans2 = ans2.decode('utf-8')
        buffer.close()
        return render(request, 'result.html', {'chart': ans1, 'plot': ans2})
    else:
        return HttpResponse("Error!")

result.html:-

{% extends 'base.html' %} {% block content %} 
    {% if chart %}
        <img src="data:image/png;base64, {{chart|safe}}" />
    {% endif %}
<br />
    {% if plot %}
        <img src="data:image/png;base64, {{plot|safe}}" />
    {% endif %}
{% endblock %}

здесь df в dataframe. Я делаю веб-приложение для анализа настроений твитов. Для этого я хочу вывести свои графики matplot во фронтенде как результат в django, но возникает ошибка name 'posts' is not defined. Здесь в моем коде код анализа настроений возвращает dataframe, содержащий субъективность полярности твитов. Я хочу показать график рассеяния и гистограмму.

Вернуться на верх