การสร้างสีสุ่มจำนวนมากสำหรับ Pie Chart
สร้างสี hex สุ่มจำนวน n สี สำหรับ pie chart ที่มี slice เยอะ
ขั้นตอนหลัก
- ตั้งค่าขนาดรูปและ padding
- กำหนด n = จำนวน slice
- สร้างข้อมูลสุ่ม a ด้วย numpy
- สร้างรายการสี hex สุ่ม color
- สร้าง figure และ axes กำหนด aspect='equal'
- พล็อต pie chart ด้วย plt.pie(a, colors=color)
- แสดงผลด้วย show()
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import random
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
n = 40
color = ["#" + ''.join([random.choice('0123456789ABCDEF')
for j in range(6)]) for i in range(n)]
a = np.random.random(n)
f = plt.figure()
ax = f.add_subplot(111, aspect='equal')
p = plt.pie(a, colors=color)
plt.show()
คำอธิบาย
list comprehension สร้างสี hex 6 หลักสุ่ม n สี aspect='equal' ทำให้ pie เป็นวงกลม