萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python ReportLab 繪製統計圖表完整教學:折線圖、中文支援、座標軸標籤與輸出

前言:ReportLab Graphics 套件

reportlab.graphics 提供向量繪圖基礎設施,charts 子模組內建折線圖、長條圖、餅圖等。**純 Python、無系統相依、輸出 PDF/PNG/SVG/GIF**,適合伺服器端自動生成報表。

環境準備

pip install reportlab
# 中文字體:需 .ttc/.ttf 檔 (如 simsun.ttc、msjh.ttc),放入專案目錄或系統字體資料夾

完整可執行範例:雙折線圖 + 中文標題 + 座標軸標籤

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import traceback
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF, renderPM
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# ===== 1. 資料準備 =====
# 格式:[ ( (x1,y1), (x2,y2), ... ),  # 線條 1
#         ( (x1,y1), (x2,y2), ... ) ] # 線條 2
data = [
    ((1, 100), (2, 200), (3, 300), (4, 400), (5, 500)),
    ((1, 50),  (2, 80),  (3, 400), (4, 40),  (5, 70))
]

# ===== 2. 建立繪圖區 =====
drawing = Drawing(500, 300)  # 寬、高 (points, 1pt=1/72 inch)

# ===== 3. 設定折線圖 =====
lp = LinePlot()
lp.x = 50          # 圖表左下角 X
lp.y = 30          # 圖表左下角 Y
lp.width = 400     # 繪圖區寬
lp.height = 250    # 繪圖區高
lp.data = data
lp.joinedLines = 1 # 連線
lp.lines.symbol = makeMarker('FilledCircle')  # 資料點標記

# X 軸
lp.xValueAxis.valueMin = 1
lp.xValueAxis.valueMax = 5
lp.xValueAxis.valueStep = 1

# Y 軸
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 500
lp.yValueAxis.valueStep = 100

drawing.add(lp)

# ===== 4. 中文標題 (需註冊字體) =====
# 字體檔需存在:專案目錄或系統字體路徑
FONT_PATH = 'simsun.ttc'  # 請確認路徑
FONT_NAME = 'SimSun'

try:
    pdfmetrics.registerFont(TTFont(FONT_NAME, FONT_PATH))
except Exception as e:
    print(f"字體註冊失敗:{e},將使用預設字體 (中文會顯示方塊)")
    FONT_NAME = 'Helvetica'

title = Label()
title.fontName = FONT_NAME
title.fontSize = 14
title._text = '銷售趨勢圖示範'  # 直接指定 unicode 字串
title.x = 250
title.y = 280
title.textAnchor = 'middle'
drawing.add(title)

# ===== 5. 座標軸標籤 =====
x_label = Label()
x_label._text = '月份'
x_label.fontName = FONT_NAME
x_label.fontSize = 10
x_label.x = 450
x_label.y = 20
x_label.textAnchor = 'middle'
drawing.add(x_label)

y_label = Label()
y_label._text = '營業額 (萬元)'
y_label.fontName = FONT_NAME
y_label.fontSize = 10
x_label.x = 30
x_label.y = 280
x_label.textAnchor = 'middle'
drawing.add(y_label)

# ===== 6. 輸出多格式 =====
try:
    # PDF (向量、最佳品質)
    renderPDF.drawToFile(drawing, 'chart.pdf', 'Sales Chart')
    print("PDF 已輸出:chart.pdf")

    # PNG (位圖、需 Pillow)
    renderPM.drawToFile(drawing, 'chart.png', fmt='PNG')
    print("PNG 已輸出:chart.png")

    # GIF
    renderPM.drawToFile(drawing, 'chart.gif', fmt='GIF')
    print("GIF 已輸出:chart.gif")

except Exception:
    traceback.print_exc()

關鍵 API 速查

類別/方法用途
Drawing(w, h)畫布容器
LinePlot()折線圖核心
lp.data資料序列:list of tuple of (x,y)
lp.joinedLines1=連線, 0=散點
lp.lines[i].strokeColor第 i 條線顏色
lp.lines[i].strokeWidth線寬
makeMarker('FilledCircle')資料點形狀:Circle, Square, Diamond, Dash...
Label()文字標籤 (標題、軸標、圖例)
pdfmetrics.registerFont(TTFont(name, path))註冊 TTF/TTC 字體
renderPDF.drawToFile輸出 PDF
renderPM.drawToFile輸出位圖 (PNG/GIF/JPEG),需 pip install pillow

進階客製化

  • 多線條樣式:lp.lines[0].strokeColor = colors.red; lp.lines[1].strokeDashArray = [4,2]
  • 圖例:from reportlab.graphics.charts.legends import Legend 手動建立對應標籤。
  • 網格線:lp.xValueAxis.gridEnd = lp.width; lp.yValueAxis.gridEnd = lp.height + strokeColor = colors.grey。
  • 對數/日期軸:使用 LogScale 或自訂 labelTextFormat。
  • 互動式 PDF:搭配 reportlab.pdfgen.canvas 加入超連結、書籤。

常見坑與解法

問題原因解法
中文顯示方塊/亂碼未註冊中文字體pdfmetrics.registerFont(TTFont('SimSun', 'simsun.ttc')),確認字體檔路徑
輸出 PNG 失敗缺少 Pillowpip install pillow
座標軸刻度擠在一起valueStep 過小或範圍過大調整 valueMin/Max/Step 或啟用 labelTextFormat 科學記號
圖表超出畫布x/y/width/height 設定錯誤留白邊距:x=50, y=30, width=W-100, height=H-80

結語

ReportLab Graphics 以**宣告式 API** 構建專業級統計圖表,**純 Python、無系統相依、輸出多格式**。掌握 Drawing → LinePlot → Label → renderPDF/PM 流程,並解決**中文字體註冊**這一關鍵點,即可在伺服器端自動化生成高品質圖表報表。

copyright © 萬盛學電腦網 all rights reserved