[Python3] Matplotlib —— (三) 簡易散點圖


[ Matplotlib version: 3.1.3 ]


四、簡易散點圖

散點圖(scatter plot),不由線段連接,而是由獨立的點、圓圈或其他形狀構成。

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np

(一)用plt.plot畫散點圖

簡易散點圖

x = np.linspace(0, 10, 30)
y = np.sin(x)

plt.plot(x, y, 'o', color='black')
# 第三個參數爲圖形符號縮寫形式

在這裏插入圖片描述

不同的圖形標記

plt.figure(figsize=(12,8))
rng = np.random.RandomState(0)
for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
    plt.plot(rng.rand(5), rng.rand(5), marker, 
             label="marker='{0}'".format(marker))
    plt.legend(numpoints=1)
    plt.xlim(0, 1.8)

在這裏插入圖片描述

組合線條與散點

plt.plot(x, y, '-ok')

在這裏插入圖片描述

自定義線條和散點屬性

plt.plot(x, y, '-p', color='gray', markersize=15, linewidth=4,
         markerfacecolor='white', markeredgecolor='gray', markeredgewidth=2)

在這裏插入圖片描述

(二)用plt.scatter畫散點圖

簡易散點圖

plt.scatter(x, y, marker='o')

在這裏插入圖片描述

改變散點圖中散點的大小、顏色和透明度

  • plt.scatterplt.plot的主要差別在於,前者在創建散點圖時具有更高靈活性,可以單獨控制每個散點與數據匹配,也可以讓每個散點具有不同的屬性(大小、表面顏色、邊框顏色等)
  • 可以用alpha參數調整透明度,以便更好顯示重疊部分
  • 顏色自動映射成顏色條(color scale,通過colorbar()顯示),散點的大小以像素爲單位。這樣散點的顏色與大小就可以顯示多維數據的信息了
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)

plt.scatter(x, y, c=colors, s=sizes, alpha=0.3, cmap='viridis')
plt.colorbar()

在這裏插入圖片描述

# 用散點屬性對鳶尾花的特徵編碼
from sklearn.datasets import load_iris
iris = load_iris()
features = iris.data.T

plt.scatter(features[0], features[1], alpha=0.2, s=100*features[3], c=iris.target, cmap='viridis')
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1])

在這裏插入圖片描述

  • 散點圖可以讓我們同事看到不同維度的數據:每個點的座標值(x, y)分別表示花萼的長度和寬度,而點的大小表示花瓣的寬度,三種顏色對應三種不同類型的鳶尾花。

  • 更多詳見:matplotlib.pyplot.scatter - Matplotlib 3.2.1 documentation

(三)plot與scatter效率對比

在數據量較小的時候,兩者在效率上差異不大。

當大型數據集(數據變大到幾千個散點)時,plt.plot的效率將大大高於plt.scatter

  • plt.scatter會對每個散點進行單獨的大小與顏色的渲染,渲染器會消耗更多資源
  • plt.plot中,散點基本都彼此複製,因此整個數據集中所有點的顏色、尺寸只需要配置一次

Matplotlib 相關閱讀:

[Python3] Matplotlib —— (一) 入門基礎
[Python3] Matplotlib —— (二) 簡易線形圖


總結自《Python數據科學手冊》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章