LoginSignup
9
8

More than 5 years have passed since last update.

herokuでmatplotlibでSVGなグラフを書く

Last updated at Posted at 2014-11-29

はじめに

前にも似たようなことを書きましたが改めて。

pyenv環境の準備

pyenv, pyenv-virtualenvをhomebrewでインストールしておきます。

$ mkdir qiita-sin
$ cd qiita-sin
$ pyenv virtualenv 2.7.8 qiita-sin
$ pyenv local qiita-sin

必要なライブラリのインストールとHerokuで動かす準備

$ pip install flask
$ pip install gunicorn
$ pip install matplotlib
$ echo python-2.7.8 > runtime.txt
$ pip freeze > requirements.txt
$ echo web: gunicorn app:app --log-file=- > Procfile
$ mkdir templates

テンプレート、アプリの準備

テンプレート

sin.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <title>sinカーブテスト</title>
    </head>
    <body>
        <h1>sinカーブテスト</h1>
        {% autoescape false %}{{svgstr}}{% endautoescape %}
    </body>
</html>

アプリ

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
import numpy as np

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 = plt.figure()
    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"))

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

デプロイ

gitに追加

$ git init
$ echo .python-version > .gitignore
$ git add .
$ git commit -m "initial commit" .

herokuにデプロイ

$ heroku create
$ git push heroku master

numpyやmatplotlibのコンパイルがあるのでしばしコーヒーブレイク

完成

確認

$ heroku open

https://limitless-garden-3527.herokuapp.com/ が開く

ポイント

  • SVGの処理(strio.buf.find("<svg")decode("utf-8")あたりがポイント
  • 日本語の表示はあとでまた

コメント

なんかいつの間にかCeder-14スタックとhttpsがデフォルトになってたんですね

9
8
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
9
8