下面是一个使用Seaborn库的sns.barplot按列或行划分的示例代码:
import seaborn as sns
import matplotlib.pyplot as plt
# 创建示例数据
data = {
'Category': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
'Value': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'Group': ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
}
# 创建一个DataFrame
df = pd.DataFrame(data)
# 按列划分
plt.figure(figsize=(8, 6))
sns.barplot(x='Group', y='Value', hue='Category', data=df)
plt.xlabel('Group')
plt.ylabel('Value')
plt.title('Bar Plot by Column')
# 按行划分
plt.figure(figsize=(8, 6))
sns.barplot(x='Category', y='Value', hue='Group', data=df)
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Bar Plot by Row')
plt.show()
解释: