Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Trực quan hóa Treemap với Pygal trong Python


Trực quan hóa dữ liệu quan trọng để hiểu dữ liệu mà không cần tính toán phức tạp.

Pygal là package Python mã nguồn mở tạo biểu đồ tương tác và ảnh SVG (Scalable Vector Graphics). SVG cho phép tạo đồ họa vector động, co giãn không mất chất lượng, nhúng vào web/dự án.

Pygal hỗ trợ: bar chart, histogram, line plot, treemap...

Treemap biểu diễn dữ liệu lồng nhau (nested) bằng hình chữ nhật. Kích thước đại diện cho giá trị dữ liệu. Càng lớn = giá trị càng cao.

Cài đặt Windows: pip install Pygal

Ví dụ

import pygal
from pygal.style import Style

custom_style = Style(colors=('#E80080', '#404040', '#9BC850', '#E81190'))

treemap = pygal.Treemap(height=400, width=300, style=custom_style)
treemap.title = "Treemap"
treemap.add("label 1", [0.4, 0.5, 0.6, 0.7])
treemap.add("label 2", [1.2, 1.3, 1.4])
treemap.add("label 3", [1.5, 1.6, 1.9])
treemap.add("label 3", [1.8, 1.9, 2.0, 2.1, 2.2])
treemap.render_in_browser()

Đầu ra

Trực quan hóa Treemap với Pygal trong Python

Giải thích

  • Import pygal và Style.
  • Tạo pygal.Treemap với height, width, style tùy chỉnh.
  • Đặt title và thêm dữ liệu qua add() (nhãn + list giá trị).
  • Gọi render_in_browser() hiển thị treemap trên trình duyệt.