我有一个程序/函数可以绘制这样的图表-
我想做的是把同一年的条形图并排放起来,然后在中间留一些空隙,然后再把另一年的条形图并排放起来。我不能解决这个问题。
这是绘制图形的代码/函数(供参考)-
def plot_monthly_multiple_store2():
df = order_merged.multi_store_monthly_count([2020,2021], [1,2,3,4], ['Crizac','Ucol'])
df['year'] = df['date_added'].dt.year
df['month'] = df['date_added'].dt.month
# Calculate count by year and month
count_df = df.groupby(['year', 'month', 'store_type'])['order_id'].count().reset_index()
# Pivot the count data by year and month
pivot_df = pd.pivot_table(count_df, values='order_id', index=['year', 'month'], columns=['store_type'], fill_value=0)
print(pivot_df,"\n")
print(pivot_df.index.levels[1],"\n")
print(pivot_df.index[:(len(pivot_df.index)//2)])
# Plot the stacked bar chart
fig, ax = plt.subplots(figsize=(10, 5))
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
width = 0.8 / len(pivot_df.index.levels[0])
print(pivot_df.loc[2020,1])
# print(pivot_df.loc[2021].index)
for i, year in enumerate(pivot_df.index.levels[0]):
x_pos = np.arange(len(pivot_df.loc[year].index)) + i*len(pivot_df.loc[year].index)
print(x_pos,"\n")
for j, store_type in enumerate(pivot_df.columns):
ax.bar(x_pos, pivot_df.loc[year, store_type], width=width, align='edge', color=colors[j], alpha = 0.7, edgecolor='black', linewidth = 0.5, label=store_type if i==0 else None)
for x, y in zip(x_pos, pivot_df.loc[year, store_type]):
ax.text(x + width / 2, y, str(y), ha='center', va='bottom', fontsize=8)
ax.set_xticks(np.arange(len(pivot_df.index)))
ax.set_xticklabels([f"{calendar.month_abbr[month]}\n{year}" for year, month in pivot_df.index], fontsize=8)
ax.set_xlabel('Year', fontsize=12)
ax.set_ylabel('Count', fontsize=12)
ax.set_title('Order Count by Month and Store Type', fontsize=14)
ax.legend(loc='upper left', bbox_to_anchor=(1.0, 1.0))
plt.tight_layout()
plt.show()
1条答案
按热度按时间bogh5gae1#
我不太了解Pandas,但我希望这能有所帮助。
我的虚拟数据: