2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Matlabのscatter/scatter3をPythonで

Last updated at Posted at 2021-01-29

これができないと話にならない、2D / 3D 散布図。
MATLABでいうところのscatterやscatter3相当のもの。

matplotlibを使ってやる。
2D/3Dの差はaxisを2Dで作るか3Dで作るかを変えるだけで、あとはほとんど一緒。

#2次元の場合

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt

x = np.random.rand(500, 2)
y=((x-0.5)**2).sum(axis=1)**0.5

fig = plt.figure(figsize=(6.4,4.8),dpi=72)
    # figsizeはインチ単位。デフォルト(6.4,4.8) 
    # dpiはデフォルト 100

#2d散布図
ax = fig.add_subplot(1, 1, 1, title='Title', xlabel='X', ylabel='Y')
    #titleなどはあとからax.set_title() ax.set_xlabel などで変更可
sc = ax.scatter(x[:, 0], x[:, 1], vmin=0, vmax=1, c=y, cmap=cm.jet)

#カラーバー
cb=fig.colorbar(sc)
plt.show()
fig.savefig('2d.png')

結果
2d.png

#3次元の場合

#カラーバー
cb=fig.colorbar(sc)
plt.show()
fig.savefig('/Users/miyawaki/Desktop/2d.png')


import numpy as np
import matplotlib.cm as cm
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D

x = np.random.rand(500, 3)
y=((x-0.5)**2).sum(axis=1)**0.5

fig = plt.figure(figsize=(6.4,4.8),dpi=72)
    # figsizeはインチ単位。デフォルト(6.4,4.8) 
    # dpiはデフォルト 100

#3D散布図
ax = Axes3D(fig)
sc=ax.scatter(x[:, 0], x[:, 1], x[:, 2], c=y, cmap=cm.jet)

#タイトルと軸ラベル
ax.set_title("Title", fontsize=8)
ax.set_xlabel("X", fontsize=7)
ax.set_ylabel("Y", fontsize=7)
ax.set_zlabel("Z", fontsize=7)
#tick labelのフォントサイズ
plt.tick_params(labelsize = 6)

#カラーバー 0.6倍に縮小
cb=fig.colorbar(sc,shrink = 0.6)
    #水平にするときはorientationにhorizontalを追加
    #cb=fig.colorbar(sc,shrink = 0.6, orientation="horizontal")

#カラーバーのlabel、tick label
cb.set_label("Color", fontsize=7)
cb.ax.tick_params(labelsize=6)

plt.show()
fig.savefig('3d.png')

結果
3d.png

…微調整はおいおい調べましょう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?