使用Matplotlib進行 Python 資料視覺化

學習用 Python 繪製資料。在瀏覽器中建立清晰的散佈圖,調整標籤、圖例和本機樣式。

在編輯器中嘗試

概述

數據視覺化是資訊和數據的圖形表示。透過使用圖表、圖形和地圖等視覺元素,資料視覺化工具提供了一種查看趨勢、異常值和模式的便捷方式。

Matplotlib是 Python 中繪圖的核心函式庫。它提供了物件導向的 API,可讓您自訂圖形的每個像素,從軸顏色到字體樣式。

在此範例中,我們產生合成成長曲線並將它們繪製在同一張圖上,顯示如何為可發佈的圖表定義線條粗細、標記、圖例和軸限制。

程式碼和執行輸出

使用 matplotlib 渲染數學函數比較圖表的腳本。

import matplotlib.pyplot as plt
import numpy as np

# Generate points along the X axis
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create figure
fig, ax = plt.subplots(figsize=(8, 5))

# Plot lines
ax.plot(x, y1, label='Sine Wave', color='#0D9488', linewidth=2.5)
ax.plot(x, y2, label='Cosine Wave', color='#EF4444', linewidth=2, linestyle='--')

# Style axis and frame
ax.set_title('Trigonometric Waveforms', fontsize=14, fontweight='bold', pad=15)
ax.set_xlabel('X Axis (Radians)', fontsize=11)
ax.set_ylabel('Amplitude', fontsize=11)
ax.grid(True, linestyle=':', alpha=0.6)
ax.legend(loc='upper right', frameon=True)
ax.spines[['top', 'right']].set_visible(False)

plt.tight_layout()
plt.show()
端子輸出
Rendered visualization in the Graphs tab...

逐步實施

  • 科學研究繪圖與遙測輸出
  • 為分析 Web 應用程式建立儀表板圖表元素
  • 機器學習任務期間的探索性資料分析

常見問題解答

我可以將seaborn 與PyRun一起使用嗎?

是的,seaborn 是一個建構在 matplotlib 之上的包裝器。如果導入,PyRun會將其繪圖重新導向至相同瀏覽器圖形視窗。

如何將 matplotlib 圖儲存到 Python 中的檔案中?

您可以執行 plt.savefig('my_chart.png', dpi=300)` 將映像直接寫入檔案系統工作區,而不是呼叫 `plt.show()`。

相關主題