matplotlib.pyplotを用いて散布図作成

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x = np.random.rand(100)
>>> y = np.random.rand(100)
>>> plt.scatter(x,y)
>>>plt.show()



 上記はよくある散布図を描いたものです。
正直これじゃxとyの関係性がわかりにくいと思うので、もう少し簡単にしたものを下に例を挙げていきます。

>>> import matplotlib.pyplot as plt
>>> x = [2,5,7,4]
>>> y = [0,1,7,7]
>>> plt.scatter(x,y)
>>> plt.show()
xとyの関係性は理解できましたでしょうか。
xとyはリストで表され、インデックスごとに関係を持っているのです。
散布図作成において、plt.scatter(x,y)でxとyのインデックスごとに散布図を作成しているんだと覚えておいてください。

構成が理解できたら、ラベルを付けていきましょう

>>> import matplotlib.pyplot as plt
>>> x = [0,1,2,1,1,7]
>>> y = [0,1,2,3,4,5]
>>> plt.scatter(x,y)
>>> plt.title("example")
>>> plt.xlabel("x label")
>>> plt.ylabel("y axis")
>>> plt.show()
散布図を使う上で異なる複数データを用いると思います。
そのために次はデータごとに色を付けて表示していきます。

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x1 = np.random.rand(10)
>>> y1 = np.random.rand(10)
>>> x2 = np.random.rand(10)*2
>>> y2 = np.random.rand(10)/2
>>> x3 = np.random.rand(10)/2
>>> y3 = np.random.rand(10)*2
>>> plt.scatter(x1,y1, c="red")
>>> plt.scatter(x2,y2, c="blue")
>>> plt.scatter(x3,y3, c="green")
>>> plt.xlabel("x")
>>> plt.ylabel("y")
>>> plt.show()


カラーでデータ分けできましたら、そのデータがどのデータか分かるようにラベルをつけましょう。

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x1 = np.random.rand(10)
>>> y1 = np.random.rand(10)
>>> x2 = np.random.rand(10)*2
>>> y2 = np.random.rand(10)/2
>>> x3 = np.random.rand(10)/2
>>> y3 = np.random.rand(10)*2
>>> x4 = np.random.rand(10)*2
>>> y4 = np.random.rand(10)*2
>>> plt.scatter(x1,y1,c="red",label="red")
>>> plt.scatter(x2,y2,c="blue",label="blue")
>>> plt.scatter(x3,y3,c="green",label="green")
>>> plt.scatter(x4,y4,c="yellow",label="yellow")
>>> plt.xlabel("x")
>>> plt.ylabel("y")
>>> plt.show()



マーカーの基本設定は"o"だが、これを変更することもできます。

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x1 = np.random.rand(10)
>>> y1 = np.random.rand(10)
>>> x2 = np.random.rand(10)*2
>>> y2 = np.random.rand(10)/2
>>> x3 = np.random.rand(10)/2
>>> y3 = np.random.rand(10)*2
>>> plt.scatter(x1,y1,marker=".",c="red",label="red")
>>> plt.scatter(x2,y2,marker="*",c="blue",label="blue")
>>> plt.scatter(x3,y3,marker="+",c="green",label="green")
>>> plt.xlabel("x")
>>> plt.ylabel("y")
>>> plt.show()



少しでも参考になれば、嬉しいです。

0 件のコメント :

コメントを投稿