Để vẽ hai histogram cạnh nhau (side by side) bằng Matplotlib:
- Thiết lập kích thước figure và padding
- Tạo 2 DataFrame
df1,df2 - Tạo figure và subplots (1 hàng, 2 cột)
- Vẽ histogram cho
df1trên axes[0],df2trên axes[1] - Hiển thị bằng
show()
Ví dụ mã nguồn
from matplotlib import pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df1 = pd.DataFrame(dict(a=[1, 1, 1, 1, 3]))
df2 = pd.DataFrame(dict(b=[1, 1, 2, 1, 3]))
fig, axes = plt.subplots(1, 2)
df1.hist('a', ax=axes[0])
df2.hist('b', ax=axes[1])
plt.show()
Kết quả
Hai histogram cạnh nhau: bên trái cột 'a' (giá trị 1,3), bên phải cột 'b' (giá trị 1,2,3).

Cách khác: Dùng plt.subplot(121), plt.subplot(122) hoặc fig, (ax1, ax2) = plt.subplots(1, 2). Để so sánh trực tiếp hơn, có thể dùng plt.hist([data1, data2], bins=..., label=..., alpha=0.5) chồng nhau.