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

วิธีพล็อตแท่งแบบมีรูปแบบหน้าตัด (Hatched Bars) ด้วย Pandas และ Matplotlib


ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้าง DataFrame ด้วย Pandas 2 คอลัมน์
  • เพิ่ม axes ลงใน figure ปัจจุบันเป็น subplot arrangement
  • พล็อตกราฟด้วย kind="bars"
  • สร้างรายการรูปแบบหน้าตัด (hatches)
  • ดึง patches ของแท่งด้วย bars.patches
  • วนลูป patches และตั้งค่า hatch ให้แต่ละ patch
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

ตัวอย่างโค้ด

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
ax = plt.figure().add_subplot(111)
bars = df.plot(ax=ax, kind='bar')
hatches = ["*", "/", "o", "x"]
for patch in bars.patches:
    patch.set_hatch(hatches[np.random.randint(10)%len(hatches)])
plt.show()

ผลลัพธ์

วิธีพล็อตแท่งแบบมีรูปแบบหน้าตัด (Hatched Bars) ด้วย Pandas และ Matplotlib