Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การสร้าง Treemap ด้วย Pygal ใน Python


บทนำ

การแสดงข้อมูล (Visualization) สำคัญช่วยเข้าใจข้อมูลโดยไม่ต้องคำนวณซับซ้อน

Pygal เป็นแพ็กเกจ Python โค้ดเปิด สร้างกราฟโต้ตอบ และภาพ SVG (Scalable Vector Graphics) SVG = กราฟแอนิเมชันไดนามิก สามารถปรับแต่งได้ ดาวน์โหลดคุณภาพสูง ฝังในเว็บ/โปรเจกต์ได้ สร้าง Bar chart, Histogram, Line plot ฯลฯ ได้ง่าย

Treemap

ใช้แสดงข้อมูลแบบ Nested (ซ้อนกัน) เป็นรูปสี่เหลี่ยม ขนาดแทนค่าในชุดข้อมูล ขนาดใหญ่ = ค่าสูง

การติดตั้ง

pip install Pygal

ตัวอย่าง: สร้าง Treemap

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()

ผลลัพธ์

การสร้าง Treemap ด้วย Pygal ใน Python

คำอธิบาย

  • นำเข้า pygal และ Style
  • สร้าง Treemap กำหนด height, width, style
  • กำหนดสี custom style
  • ตั้งค่า title และเพิ่มข้อมูลด้วย add
  • เรียก render_in_browser() แสดงบนเบราว์เซอร์