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

วิธีระบุสีต่างกันสำหรับแท่งต่างๆ ใน histogram matplotlib

ในการระบุสีต่างกันสำหรับแท่งต่างๆ ใน matplotlib histogram สามารถทำตามขั้นตอนดังนี้:

ขั้นตอน

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots

  • สร้าง figure และชุด subplots

  • วาด histogram ด้วยข้อมูลสุ่ม 100 ตัวอย่าง

  • วนลูปในช่วงจำนวน bins ตั้งค่า facecolor สุ่มสำหรับแต่ละแท่ง

  • แสดงรูปด้วยเมธอด show()

ตัวอย่าง

import numpy as np
import matplotlib.pyplot as plt
import random
import string
# ตั้งค่าขนาดรูป
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Figure และ subplots
fig, ax = plt.subplots()
# ข้อมูลสุ่ม
data = np.random.rand(100)
# วาด histogram
N, bins, patches = ax.hist(data, edgecolor='black', linewidth=1)
# สีสุ่มสำหรับแต่ละแท่ง
for i in range(len(N)):
    patches[i].set_facecolor("#" + ''.join(random.choices("ABCDEF" + string.digits, k=6)))
# แสดง plot
plt.show()

ผลลัพธ์

จะแสดง histogram 10 bins แต่ละแท่งสีสุ่มต่างกัน ขอบสีดำ

วิธีระบุสีต่างกันสำหรับแท่งต่างๆ ใน histogram matplotlib