我想创建twp子图,顶部是箱线图,底部是条形图。箱形图涵盖了过去10年中12个月的数据,而条形图仅涵盖了今年的5个月,因为没有更多可用数据。
我的代码:
#Visualise the data
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
f, axes = plt.subplots(2, 1, sharey=True, sharex=True)
ax.plot= sns.boxplot(x="Month", y='application_number', data=results_df_groupby_truncated_monthly_dataframe, fliersize=5, ax=axes[0])
ax.plot= sns.barplot(x="Month", y='application_number', data=results_df_groupby_truncated_pandemic_monthly_dataframe, ax=axes[1])
输出-A
我使用了sharex=True
,因为共享相同的x轴有助于比较两个图形。但是,箱线图不会显示全部12个月,而仅显示5个月。条形图的颜色与箱形图不匹配。
输出-B
我使用了sharex=False
。箱线图显示了全部12个月,但要在两个图表之间进行比较并不容易。条形图的颜色与箱形图不匹配。
所需的输出:
关于如何1)将两个图表以相同的x轴对齐,2)匹配两个图表的颜色,3)显示12个月的想法?非常感谢。
您可以通过使用order
和sns.boxplot
的sns.barplot
参数来实现全部三个目标。这具有对齐调色板的颜色并调整x轴以显示传递给order
的所有级别的效果:
# df1 contains mock data for 12 months and df2 contains mock data for 5 months
f, ax = plt.subplots(2, 1, sharex=True)
sns.boxplot(x="month", y="data", order=range(1, 12), ax=ax[0], data=df1)
sns.barplot(x="month", y="data", order=range(1, 12), ax=ax[1], data=df2)