Để vẽ errorbar khoảng tin cậy 95% từ DataFrame Pandas, chúng ta có thể thực hiện các bước sau:
- Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
- Lấy instance dataframe dữ liệu bảng hai chiều, kích thước có thể thay đổi, có thể hétérogène.
- Tạo dataframe với hai cột: category và number.
- Tìm mean và std của category và number.
- Vẽ y versus x dưới dạng lines và/hoặc markers với errorbars đính kèm.
- Để hiển thị figure, dùng phương thức show().
Ví dụ
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame()
df['category'] = np.random.choice(np.arange(10), 1000, replace=True)
df['number'] = np.random.normal(df['category'], 1)
mean = df.groupby('category')['number'].mean()
std = df.groupby('category')['number'].std()
plt.errorbar(mean.index, mean, xerr=0.5, yerr=2*std,
linestyle='--', c='red')
plt.show()
Kết quả
