- The correct way to get subplots using pandas, is to reshape the dataframe. pandas.crosstab https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html is used to shape the dataframe
-
pandas.DataFrame.pivot https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html and pandas.DataFrame.pivot_table https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot_table.html是重塑数据以进行绘图的其他选项。
- 然后使用绘图pandas.DataFrame.plot https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html with
kind='pie'
and subplots=True
.
- Extra code has been added for formatting
- 旋转 pclass 标签
- 情节标题
- custom legend instead of a legend for each subplot
- 测试于
python 3.8.12
, pandas 1.3.4
, matplotlib 3.4.3
import seaborn as sns # for titanic data only
import pandas as pd
from matplotlib.patches import Patch # to create the colored squares for the legend
# load the dataframe
df = sns.load_dataset('titanic')
# reshaping the dataframe is the most important step
ct = pd.crosstab(df.survived, df.pclass)
# display(ct)
pclass 1 2 3
survived
0 80 97 372
1 136 87 119
# plot and add labels
colors = ['tab:blue', 'tab:orange'] # specify the colors so they can be used in the legend
labels = ["not survived", "survived"] # used for the legend
axes = ct.plot(kind='pie', autopct='%.1f%%', subplots=True, figsize=(12, 5),
legend=False, labels=['', ''], colors=colors)
# flatten the array of axes
axes = axes.flat
# extract the figure object
fig = axes[0].get_figure()
# rotate the pclass label
for ax in axes:
yl = ax.get_ylabel()
ax.set_ylabel(yl, rotation=0, fontsize=12)
# create the legend
legend_elements = [Patch(fc=c, label=l) for c, l in zip(colors, labels)]
fig.legend(handles=legend_elements, loc=9, fontsize=12, ncol=2, borderaxespad=0, bbox_to_anchor=(0., 0.8, 1, .102), frameon=False)
fig.tight_layout()
fig.suptitle('pclass survival', fontsize=15)
格式化图
未格式化的图
axes = ct.plot(kind='pie', autopct='%.1f%%', subplots=True, figsize=(12, 5), labels=["not survived", "survived"])