カンテラの光の下で

dNaga392's memorandom

【matplotlib】散布図を描画する

要点

使用例

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('iris')
x = df['sepal_length']
y = df['sepal_width']

fig = plt.figure()

ax = fig.add_subplot(1, 1, 1)

ax.scatter(x, y)
ax.set_title('Matplot scatter plot')  # タイトル
ax.set_xlabel('sepal_length')  # X軸ラベル
ax.set_ylabel('sepal_width')  # Y軸ラベル

plt.show()

mpl-ax-scatter.png

特定のグループごとに描画する場合

fig = plt.figure()

ax = fig.add_subplot(1, 1, 1)

hue = 'species'
labels = set(df[hue])
dataset = [(df[df[hue]==x]['sepal_length'], df[df[hue]==x]['sepal_width']) for x in labels]
for data, label in zip(dataset, labels):
    x, y = data
    ax.scatter(x, y, label=label)
ax.set_title('Matplot scatter plot')  # タイトル
ax.set_xlabel('sepal_length')  # X軸ラベル
ax.set_ylabel('sepal_width')  # Y軸ラベル
ax.legend(loc='best', title='legend', shadow=True)  # 凡例

plt.show()

mpl-ax-scatter-hue.png