这是我的熊猫DataFrame:
Area Gender Amount
XXX Men 23495
YYY Men 9336
ZZZ Men 8828
TTT Men 11546
XXX Women 19798
YYY Women 8235
ZZZ Women 9122
TTT Women 10800
这是我绘制多个图表的代码:
import pandas as pd
import bumpy as np
import seaborn as sns
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt
df_men = df[df["Gender"]=="Men"].drop("Gender", axis=1)
df_women = df[df["Gender"]=="Women"].drop("Gender", axis=1)
men_labels = df_men.Area.values
men_counts = df_men.Quantity.values
women_labels = df_women.Area.values
women_counts = df_women.Quantity.values
plt.figure(1, figsize=(20,10))
the_grid = GridSpec(2, 2)
cmap = plt.get_cmap('coolwarm')
colors = [cmap(i) for i in np.linspace(0, 1, 8)]
plt.subplot(the_grid[0, 0], aspect=1, title='Men')
_ = plt.pie(men_counts, labels=men_labels, autopct='%1.1f%%', shadow=True, colors=colors)
plt.subplot(the_grid[0, 1], aspect=1, title='Women')
_ = plt.pie(women_counts, labels=women_labels, autopct='%.0f%%', shadow=True, colors=colors)
plt.subplot(the_grid[1, 0], aspect=1, title='Men')
sns.barplot(x='Quantity', y='Area', data=df_men, palette='coolwarm')
plt.subplot(the_grid[1, 1], aspect=1, title='Women')
sns.barplot(x='Quantity', y='Area', data=df_women, palette='coolwarm')
plt.show()
问题是第二行的图未正确显示。它们似乎变平,没有条形可见。如果我分别绘制这些图表,它们绘制得很好。 我的代码有什么问题?
这不起作用:
plt.subplot(the_grid[1, 1], aspect=1, title='Women')
sns.barplot(x='Quantity', y='Area', data=df_women, palette='coolwarm')
但这可行:
sns.barplot(x='Quantity', y='Area', data=df_women, palette='coolwarm')
更新:
这是df.to_dict()
的输出。
{'Amount': {0: 23495,
1: 9336,
2: 8828,
3: 11546,
4: 19798,
5: 8235,
6: 9122,
7: 10800},
'Gender': {0: 'Men',
1: 'Men',
2: 'Men',
3: 'Men',
4: 'Women',
5: 'Women',
6: 'Women',
7: 'Women'},
'Area': {0: 'XXX',
1: 'YYY',
2: 'ZZZ',
3: 'TTT',
4: 'XXX',
5: 'YYY',
6: 'ZZZ',
7: 'TTT'}}
答案 0 :(得分:-1)
我自己找到了答案。
解决方法是删除aspect=1
:
plt.subplot(the_grid[1, 1], aspect=1, title='Women')
这有效:
plt.subplot(the_grid[1, 1], title='Women')
sns.barplot(x='Quantity', y='Area', data=df_women, palette='coolwarm')