LoginSignup
0
0

matplotlibを使ってグラフを作成してみた!〜その1〜

Posted at

Python学習を始めて結構な時間を費やしました。そのおかげで基礎的なことは身についたので、今後は実践的な内容を投稿していきたいと思います。まず手始めにmatplotlibを使い、基本的なグラフ作成を行っていこうと思います。

まずは散布図で3点プロットするコードを投稿します。

import matplotlib.pyplot as plt

# プロットする点
X = [1,2,3]
Y = [1,1,1]

# figureオブジェクトを生成する


fig = plt.figure()


# axesオブジェクトをfigureオブジェクトに設定する
ax = fig.add_subplot(1,1,1)

# axesオブジェクトに対して散布図を設定する
ax.scatter(X,Y,color='b',label='test_data')

# axesオブジェクトに対して凡例設定
ax.set_title('sample1')

# 表示する
plt.show()

実行結果
image.png

上記の実行結果のように、3点プロットした散布図が出来上がりました。

次に単一のグラフ描画を作成していきたいと思います。

import matplotlib.pyplot as plt

# 1.figureを生成する
fig = plt.figure()

# 2.生成したfigureにaxesを生成、配置する
ax1 = fig.add_subplot(1,1,1)

# 3.axesに描画データを設定する
X = [0,1,2]
Y = [0,1,2]
ax1.plot(X,Y)

# 4.表示する
plt.show()

実行結果

image.png

単一のグラフ描画が表示されました。次は複数のグラフ描画を表示させていきます。

import matplotlib.pyplot as plt

# figureを生成する
fig = plt.figure()

# 2x3の1番目
ax1 = fig.add_subplot(2, 3, 1)
ax1.set_title('1')  # グラフタイトル
# 2x3の2番目
ax2 = fig.add_subplot(2, 3, 2)
ax2.set_title('2')  # グラフタイトル
# 2x3の3番目
ax3 = fig.add_subplot(2, 3, 3)
ax3.set_title('3')  # グラフタイトル
# 2x3の4番目
ax4 = fig.add_subplot(2, 3, 4)
ax4.set_title('4')  # グラフタイトル
# 2x3の5番目
ax5 = fig.add_subplot(2, 3, 5)
ax5.set_title('5')  # グラフタイトル
# 2x3の6番目
ax6 = fig.add_subplot(2, 3, 6)
ax6.set_title('6')  # グラフタイトル

# 表示する
plt.show()

実行結果

image.png

2行×3列のグラフが描画されました。

次はグラフの汎用要素について、掲載します。グラフやチャートには散布図、棒グラフ、円グラフ等、様々な種類があります。これらのグラフは目的に応じて異なる形状をしていますが、一方で種類によらず共通する要素も多々あります。例えば以下のようなものがあげられます。

・グラフのタイトル
・グリッド
・X軸、Y軸の範囲
・X軸、Y軸のラベル
・凡例

こういった要素については、matplotlibでは、axesオブジェクトに対して設定を行います。以下、サンプルコードを記載します。

import matplotlib.pyplot as plt

# figureを生成会社
fig1 = plt.figure()

# グラフ描画設定
ax = fig1.add_subplot(1, 1, 1)
x1 = [-2, 0, 2]
y1 = [-2, 0, 2]
ax.plot(x1, y1)

x2 = [-2, 0, 2]
y2 = [-4, 0, 4]
ax.plot(x2, y2)

ax.grid(True)  # grid表示ON
ax.set_xlim(left=-2, right=2)  # x範囲
ax.set_ylim(bottom=-2, top=2)  # y範囲
ax.set_xlabel('x')  # x軸ラベル
ax.set_ylabel('y')  # y軸ラベル
ax.set_title('ax title')  # グラフタイトル
ax.legend(['f(x)=x', 'g(x)=2x'])  # 凡例を表示
plt.show()

実行結果

image.png

以上で、その1は終了します。次回のその2ではさまざまな種類のグラフを作成していきます。

エンジニアファーストの会社 株式会社CRE-COエンジニアリングサービス H.M

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