1. 程式人生 > >Python Matplotlib 散點圖的繪製

Python Matplotlib 散點圖的繪製

之前使用matplotlib繪製曲線圖直接使用的是plot()方法,其實繪製基礎的散點圖很簡單,只要使用scatter()方法就可以了,其他的設定方式與曲線圖的設定方式也是一致的。
例如:

import matplotlib.pyplot as plt
import numpy as np

x1 = [1, 2, 3, 4]
y1 = [1, 2, 3, 4]     #第一組資料

x2 = [1, 2, 3, 4]
y2 = [2, 3, 4, 5]    #第二組資料

n = 10
x3 = np.random.randint(0, 5, n)
y3 = np.random.randint(0, 5, n)   #使用隨機數產生

plt.scatter(x1, y1, marker = 'x',color = 'red', s = 40 ,label = 'First')
#                   記號形狀       顏色           點的大小    設定標籤
plt.scatter(x2, y2, marker = '+', color = 'blue', s = 40, label = 'Second')
plt.scatter(x3, y3, marker = 'o', color = 'green', s = 40, label = 'Third')
plt.legend(loc = 'best')    # 設定 圖例所在的位置 使用推薦位置

plt.show()  

效果:

順便複習一下座標軸的設定:

import matplotlib.pyplot as plt
import numpy as np

x1 = [-1, 2, -3, 4]
y1 = [-1, 2, -3, 4]

x2 = [-1, 2, -3, 4]
y2 = [-2, 3, -4, 5]

n = 10
x3 = np.random.randint(-5, 5, n)
y3 = np.random.randint(-5, 5, n)

plt.scatter(x1, y1, marker = 'x',color = 'red', s = 40 ,label = 'First')
plt.scatter(x2, y2, marker = '+', color = 'blue', s = 40, label = 'Second')
plt.scatter(x3, y3, marker = 'o', color = 'green', s = 40, label = 'Third')
plt.legend(loc = 'best')

plt.xlabel('X axis')
plt.ylabel('Y axis')             # 設定座標軸標籤

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')   #設定 上、右 兩條邊框不顯示

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')       #將下、左 兩條邊框分別設定為 x y 軸

ax.spines['bottom'].set_position(('data', 0))   # 將兩條座標軸的交點進行繫結
ax.spines['left'].set_position(('data', 0))

plt.show()  

效果:

以上~