LoginSignup
0
0

More than 1 year has passed since last update.

【Python】Matplotlibの基本のキ

Posted at

Pythonでグラフを描くためのライブラリーMatplotlibの基本的な使い方について説明します。

目次

1.ライブラリのインポート
2.描画オブジェクトの設定
3.タイトルの設定
4.軸ラベルの設定
5.凡例の設定

ライブラリのインポート

Matplotlibの描画モジュールpyplotをpltとしてインポートします。
JupyterNotebookなどを使っている場合、%matplotlib inlineを入れることによって、インライン(埋め込み)で表示できます。

インポート
import matplotlib.pyplot as plt
%matplotlib inline

描画オブジェクトの設定

グラフを描画するための下準備について見ていきます。
描画オブジェクト(figure)という大きなキャンバスに、いくつかのサブプロット(ax)を配置し、サブプロットの中でグラフを配置していきます。

描画オブジェクトの設定
figure,axes = plt.subplots(2,2) #2×2のサブプロットを配置

以下の通り2×2のサブブロットが配置されました
ダウンロード.png
グラフの数が1つの場合は、subplots()と引数を渡さないでおけばOKです。

タイトルの設定

サブプロット.set_title('タイトル名')で、サブプロットにタイトルを設定できます。
fig.tight_layout()はタイトルが軸ラベルと重ならないようにするためのものです。

タイトルの設定
fig,axes =plt.subplots(2)
axes[0].set_title('subplot0')
axes[1].set_title('subplot1')

fig.tight_layout()

ダウンロード (1).png

軸ラベルの設定

サブプロット.set_xlabel('ラベル名')で、サブブロットのx軸にラベル名を設定できます。
y軸はset_ylabel(’ラベル名’)です

軸ラベルの設定
fig,ax =plt.subplots()
ax.set_xlabel('x_label')
ax.set_ylabel('y_label');

ダウンロード (2).png

凡例の設定

引数label='凡例名'とし、ax.legend()を実行することで凡例を設定できます。legendは凡例という意味です。(伝説という意味もありますが)

凡例の設定
fig, ax = plt.subplots()
ax.plot([1, 2, 3], label='legend 1')
ax.plot([3, 2, 1], label='legend 2')
ax.legend();

ダウンロード (3).png

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