Thursday, May 9, 2024

Djangoにmatplotlibで円グラフ表示

Amazon Linux 2023 で再度トライ

sudo yum update

sudo yum install python3-pip

pip install django

python3 -m django --version

pip3 install matplotlib

django-admin startproject mymatplotlibsite

settings.py の ALLOWED_HOSTS = ['34.229.238.162']を編集

python3 manage.py runserver 0.0.0.0:8000 疎通確認

python3 manage.py startapp myfirstplot 

この後、views.py に下記をかいて表示させて確認(チュートリアル1参考)

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

今回はグラフを表示させたいだけなのでモデルは必要ないと思うがmodels.pyをチュートリアルと同じように作成(使わない前提)

アプリケーションをプロジェクトに含める(settings.py)

INSTALLED_APPS = [
    'myfirstplot.apps.MyfirstplotConfig',

python3 manage.py makemigrations myfirstplot
python3 manage.py sqlmigrate myfirstplot 0001
python3 manage.py migrate

モデルクラスにクラスメソッドを追加

adminサイトにログインできるユーザーを作成

python3 manage.py createsuperuser

myfirstplot/admin.py を編集


views.py

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

# coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render



def simple(request):
    import django
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    import matplotlib.pyplot as plt
    # prepare for data
    datas = [20, 30, 10]
    labels = ['Wine', 'Sake', 'Beer']
    colors = ['yellow', 'red', 'green']
    # create figure
    fig = plt.figure(1,figsize=(4,4))
    ax = fig.add_subplot(111)
    ax.axis("equal")
    pie = ax.pie(datas, #データ
                 startangle=90, #円グラフ開始軸を指定
                 labels=labels, #ラベル
                 autopct="%1.1f%%",#パーセント表示
                 colors=colors, #色指定
                 counterclock=False, #逆時計回り
                 )
    # Return
    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response


urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('charts/simple.png', views.simple, name='charts'),
]


で、http://34.229.238.162:8000/myfirstplot/charts/simple.pngにアクセスしたら動いた!


Yay!


https://qiita.com/tfuruya/items/f9de3039ad2d60b09c7b

No comments:

Post a Comment