Pygal中的折線圖
Pygal 在不同的 Python 資料視覺化工具中脫穎而出。Pygal 生成的 SVG (可縮放向量圖形) 輸出在優雅和自定義之間取得了極好的平衡。本文致力於構建 Pygal 中的折線圖,幷包含相關的示例以幫助理解。
本書主要重點是折線圖的開發,但是 Pygal 還有許多其他功能和各種圖表樣式,可以滿足各種資料視覺化需求。
Pygal:快速回顧
Pygal 是一個開源的 Python 包,用於生成令人驚歎的 SVG 圖表,這些圖表既具有互動性又易於在瀏覽器中使用。使用 Pygal 圖表,使用者可以輕鬆更改設計、標籤、工具提示和其他功能。
開始使用 Pygal 中的折線圖
折線圖是資料視覺化中的一種常用工具,可用於比較多個類別、顯示隨時間變化的趨勢等等。Pygal 建立折線圖的方法簡單且靈活。
安裝
在建立折線圖之前,請確保已安裝 Pygal。否則,請使用 pip
pip install pygal
建立基本的折線圖
在 Pygal 中,建立折線圖需要初始化一個 Line 物件並用資料填充它。使用 add() 方法新增資料,該方法接受 y 值列表和資料的標籤。預設情況下,x 值是索引值。
Pygal 中折線圖的實際示例
現在讓我們使用 Pygal 建立一些有用的折線圖。
示例 1:具有一個數據系列的基本折線圖
在我們的第一個示例中,我們將建立一個簡單的折線圖來顯示一週的溫度讀數。
import pygal
# Create a new line chart
line_chart = pygal.Line()
# Set the title
line_chart.title = 'Weekly Temperature'
# Add data
line_chart.add('Temperature', [20, 22, 23.5, 25, 27, 29.5, 30])
# Render the chart
line_chart.render_to_file('line_chart.svg')
上面的程式碼使用 Line_chart.title 設定圖表的標題,並使用 add() 方法新增資料。使用 render_to_file() 函式將圖表儲存到 SVG 檔案。
示例 2:具有多個數據系列和自定義 X 軸標籤的折線圖
考慮一下我們想要比較兩個城市之間每週溫度趨勢的情況。就是這樣
import pygal
# Create a new line chart
line_chart = pygal.Line()
# Set the title
line_chart.title = 'Weekly Temperature Comparison'
# Set x-labels
line_chart.x_labels = map(str, range(1, 8))
# Add data
line_chart.add('London', [20, 22, 23.5, 25, 27, 29.5, 30])
line_chart.add('Paris', [23, 25, 27, 28, 30, 31, 33])
# Render the chart
line_chart.render_to_file('line_chart_comparison.svg')
此例中的 line_chart。使用 x_labels 函式指定表示一週中每天的 x 軸標籤。正在新增另外兩個資料系列,每個城市一個。
示例 3:包含空值的折線圖
來自現實世界的資料集經常包含缺失值或空值。在折線圖中,Pygal 會平滑地處理這些值。
import pygal
# Create a new line chart
line_chart = pygal.Line()
# Set the title
line_chart.title = 'Weekly Temperature (With Missing Data)'
# Set x-labels
line_chart.x_labels = map(str, range(1, 8))
# Add data
line_chart.add('Temperature', [20, None, 23.5, 25, None, 29.5, 30])
# Render the chart
line_chart.render_to_file('line_chart_missing_data.svg')
在此示例中,我們使用 None 表示缺失資料。在空值處,Pygal 會自動斷開線條。
示例 4:樣式自定義的折線圖
也可以使用 Pygal 自定義圖表樣式。這是一個具有獨特樣式的折線圖示例。
import pygal
from pygal.style import DarkStyle
# Create a new line chart with custom style
line_chart = pygal.Line(style=DarkStyle)
# Set the title
line_chart.title = 'Weekly Temperature (Dark Style)'
# Set x-labels
line_chart.x_labels = map(str, range(1, 8))
# Add data
line_chart.add('Temperature', [20, 22, 23.5, 25, 27, 29.5, 30])
# Render the chart
line_chart.render_to_file('line_chart_dark_style.svg')
在此示例中,我們透過從 pygal.style 匯入 DarkStyle 來將其應用於我們的折線圖。Pygal 提供各種預構建樣式,您甚至可以建立自己的樣式。
結論
折線圖只是 Pygal 在 Python 中構建動態、可靠且美觀的 SVG 圖表方法的開始。您可以利用 Pygal 的功能設計各種互動式圖表,以使您的資料栩栩如生。
雖然 Pygal 使建立折線圖變得簡單,但掌握資料視覺化的藝術需要理解您的資料、辨別最適合您的資料的視覺化表示型別以及學習如何使用它。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP