matplotlib 每圈后同一年的棒之间的间隙

50pmv0ei  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(173)

我有一个程序/函数可以绘制这样的图表-

我想做的是把同一年的条形图并排放起来,然后在中间留一些空隙,然后再把另一年的条形图并排放起来。我不能解决这个问题。
这是绘制图形的代码/函数(供参考)-

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()
bogh5gae

bogh5gae1#

我不太了解Pandas,但我希望这能有所帮助。

from pandas import DataFrame as DF
import matplotlib.pyplot as plt
import pandas as pd

# creating dummy data
df = DF()
df['date'] = ['2020-01', '2020-02', '2020-03', '2020-04',
              '2021-01', '2021-02', '2021-03', '2021-04']

df['C'] = [10, 20, 30, 40,
           50, 60, 70, 80]

df['R'] = [100, 120, 130, 140,
           120, 150, 130, 150]

df['date'] = pd.to_datetime(df['date'])

gap = 5.0
x_labels = df['date'].dt.strftime('%b\n%Y')

df20 = df[df['date'].dt.year == 2020]
df21 = df[df['date'].dt.year == 2021]

x20 = df20['date'].dt.month
x21 = df21['date'].dt.month + gap

fig, ax = plt.subplots()
r1 = ax.bar(x20, df20['R'], align='edge', color='blue')
r2 = ax.bar(x20, df20['C'], align='edge', color='orange')

r3 = ax.bar(x21, df21['R'], align='edge', color='blue')
r4 = ax.bar(x21, df21['C'], align='edge', color='orange')

ax.set_xticks([*x20, *x21], x_labels)
ax.bar_label(r1)
ax.bar_label(r2)
ax.bar_label(r3)
ax.bar_label(r4)

我的虚拟数据:

date   C    R
0 2020-01-01  10  100
1 2020-02-01  20  120
2 2020-03-01  30  130
3 2020-04-01  40  140
4 2021-01-01  50  120
5 2021-02-01  60  150
6 2021-03-01  70  130
7 2021-04-01  80  150

相关问题