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

วิธีเปลี่ยน Figsize สำหรับ matshow() ใน Jupyter Notebook ด้วย Matplotlib


ภาพรวม

ใช้ plt.figure(figsize=...) ก่อน plt.matshow() และระบุ fignum ให้ตรงกับ Figure Number

ขั้นตอน

  1. สร้าง Figure พร้อม Figsize: plt.figure(figsize=(10, 8))
  2. สร้าง DataFrame
  3. พลอต Correlation Matrix ด้วย plt.matshow(df.corr(), fignum=1)
  4. แสดงผล

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

import pandas as pd
from matplotlib import pyplot as plt

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

plt.figure(figsize=(8, 6))
df = pd.DataFrame({"col1": [1, 3, 5, 7, 1], "col2": [1, 5, 7, 9, 1]})
plt.matshow(df.corr(), fignum=1)
plt.show()

พารามิเตอร์ fignum

  • None: สร้าง Figure ใหม่ (Default)
  • int > 0: ใช้ Figure หมายเลขนั้น สร้างใหม่ถ้ายังไม่มี
  • 0 หรือ False: ใช้ Axes ปัจจุบัน

หมายเหตุสำหรับ Jupyter

ใน Jupyter ใช้ %matplotlib inline และ plt.figure(figsize=...) ก่อน matshow() โดยไม่ต้องระบุ fignum