ในการระบุสีที่แตกต่างกันสำหรับแถบต่างๆ ในฮิสโตแกรมของ matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้ -
ขั้นตอน
-
กำหนดขนาดรูปและปรับช่องว่างภายในระหว่างและรอบๆ แผนผังย่อย
-
สร้างร่างและชุดแผนย่อย
-
พล็อตฮิสโตแกรมด้วยข้อมูลสุ่มพร้อมข้อมูลตัวอย่าง 100 รายการ
-
วนซ้ำในช่วงของจำนวนถังขยะและตั้งค่าสีแบบสุ่มสำหรับแต่ละแถบ
-
หากต้องการแสดงรูป ให้ใช้ show() วิธีการ
ตัวอย่าง
import numpy as np
import matplotlib.pyplot as plt
import random
import string
# Set the figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Figure and set of subplots
fig, ax = plt.subplots()
# Random data
data = np.random.rand(100)
# Plot a histogram with random data
N, bins, patches = ax.hist(data, edgecolor='black', linewidth=1)
# Random facecolor for each bar
for i in range(len(N)):
patches[i].set_facecolor("#" + ''.join(random.choices("ABCDEF" + string.digits, k=6)))
# Display the plot
plt.show() ผลลัพธ์
มันจะสร้างผลลัพธ์ต่อไปนี้ -
