LoginSignup
3
3

More than 5 years have passed since last update.

matplotlibを用いたグラフ描画

Posted at

グラフ描画はよく使うので、個人的に必要最低限のものを作成しました。
基本的なmatplotlibにあるの関数の説明はおそらく、他の方が説明しているので省きます。
import matplotlib.pyplotのインポートは省きます。


plot_graph.py
def plot_graph(x, y=[], graph_name='graph.png', \
    save_flag=True, show_flag=False, label_x='', label_y='', label='',title=''):
    if label: pyplot.plot(x, y, label=label)
    else: pyplot.plot(x, y)
    if title: pyplot.title(title)
    if label_x: pyplot.xlabel(label_x) 
    if label_y: pyplot.ylabel(label_y)
    if save_flag: pyplot.savefig(graph_name)
    if show_flag: pyplot.show()

デフォルト設定として、x, yを引数に与えれば、graph.pngファイルに書き込んでくれる。
x, yは数列入力です。
optionとして、ファイルネーム、保存のするかしないか、showに変更可、各軸ラベル、グラフのラベル、タイトルをいれました。
save_flagshow_flag分けた方がいいと思ったのですが、後で見たときにわかりやすいかと思い分割。

下記にそれぞれ部分的に関数化


plotの部分

plot_only.py
def plot_only(x, y=[], label=''):
    if label: 
        if y: pyplot.plot(x, y, label=label)
        else: pyplot.plot(x, label=label)
    else: 
        if y: pyplot.plot(x, y)
        else: pyplot.plot(x)

ラベル有無、引数が一つの場合の対応


ラベル付けの部分

add_label.py
def add_label(label_x='', label_y='', title=''):
    if title: pyplot.title(title)
    if label_x: pyplot.xlabel(label_x) 
    if label_y: pyplot.ylabel(label_y)

出力の部分

output_graph.py
def output_graph(save_flag=True, show_flag=False, graph_name='graph.png'):
    if save_flag: pyplot.savefig(graph_name)
    if show_flag: pyplot.show()


関数ができたので、plot_graph.pyをスマートに

new_plot_graph.py
def new_plot_graph(x, y=[], graph_name='graph.png', \
    save_flag=True, show_flag=False, label_x='', label_y='', label='',title=''):
    plot_only(x, y, label)
    add_label(label_x, label_y, title)
    output_graph(save_flag, show_flag, graph_name)

legendとか、表示範囲、xtrickとかはあんまり使わないので、今回は書いてません。
こんな感じで、自分的に必要な関数でした。

3
3
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
3
3