5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

herokuでmatplotlibでSVGなグラフを作る(日本語表示)

Posted at

はじめに

日本語の入らないグラフ作成は過去記事参照のこと

日本語フォントの準備

適当な日本語フォントファイルを準備して、gitに追加する。GoogleのNotoとか。

$ cd qiita-sin
$ mkdir fonts
$ cp .../NotoSansCJKjp-Medium.otf fonts/

アプリの修正

app.py
# !/bin/env python
# coding: utf-8

import os
import StringIO

from flask import Flask, render_template
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np

fontprop = FontProperties(fname='./fonts/NotoSansCJKjp-Medium.otf', size=10)

app = Flask(__name__)
app.debug = True

@app.route('/')
def do_sin():
    x = np.arange(-np.pi, np.pi, 0.1)
    y = np.sin(x)

    fig, ax = plt.subplots(1)
    plt.plot(x, y, label="sin")
    plt.legend(loc="best")

    strio = StringIO.StringIO()
    fig.savefig(strio, format="svg")
    plt.close(fig)

    strio.seek(0)
    svgstr = strio.buf[strio.buf.find("<svg"):]

    return render_template("sin.html", svgstr=svgstr.decode("utf-8"))

@app.route('/sin-jp')
def do_sin_jp():
    x = np.arange(-np.pi, np.pi, 0.1)
    y = np.sin(x)

    fig, ax = plt.subplots(1)
    plt.plot(x, y, label=u"sinカーブ")
    plt.legend(loc="best", prop=fontprop)
    ax.set_title(u"テスト", font_properties=fontprop)
    ax.set_xlabel(u"x軸", font_properties=fontprop)
    ax.set_ylabel(u"y軸", font_properties=fontprop)

    strio = StringIO.StringIO()
    fig.savefig(strio, format="svg")
    plt.close(fig)

    strio.seek(0)
    svgstr = strio.buf[strio.buf.find("<svg"):]

    return render_template("sin.html", svgstr=svgstr.decode("utf-8"))

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(port=port)

出来上がったアプリは https://limitless-garden-3527.herokuapp.com/sin-jp 参照

ポイント

フォントファイルを自前で用意して、fontpropを作っておくことと、描画の際にそのfontpropを指定すること

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?