pandas 在循环的子图中去除不需要的面板图

rsaldnfx  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(109)

我有一个名为data_link的每日数据,并在此共享。我已经完成了所有必要的操作,我想使用面板图(3x4)从需要的十一(11)列分别绘制条形图。我的代码工作正常,直到我在子图中绘制我所需的结果。由于我在3x4面板图中绘制十一列的结果,我得到了“”索引错误:索引11超出了大小为11''的轴0的范围。我的问题是如何删除不需要的最后一个空面板,如下图所示。这是我一直在使用的代码:

import matplotlib.pyplot as plt
import pandas as pd
from math import ceil
csv_path_cont = 'path_to_my_data/data.csv'
fname = pd.read_csv(csv_path_cont)

fname['time'] = pd.to_datetime(fname['time'])
fname['month'] = fname['time'].dt.strftime('%b')

fname.set_index('time')

#=== setting 3x4 pannel plot
fname_col=fname.columns[1:-2]
month_name=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']

# fixed number of columns
cols = 4
# number of rows, based on cols
rows = ceil(len(fname_col) / cols)

fig, ax = plt.subplots(rows, cols, figsize=(45,24))
#plt.figure(j)

m=0
for i in range (3):
    for j in range (4):
        event_occurrence = fname[[fname_col[m],'month']][fname[fname_col[m]]>0]
        num_event = event_occurrence.groupby('month').count().reindex(month_name)
        num_event = num_event.fillna(0)
        ax[i,j].bar(num_event.index,num_event[fname_col[m]])
        plt.title(m)
        m+=1
        print(m)
    
fig.savefig('bar_chart',dpi=300)

bar_chart_plot

p8ekf7hl

p8ekf7hl1#

您可以使用matplotlib.axes.Axes.set_axis_off

for i in range (3):
    for j in range (4):
        try:
            event_occurrence = fname[[fname_col[m],'month']][fname[fname_col[m]]>0]
            num_event = event_occurrence.groupby('month').count().reindex(month_name)
            num_event = num_event.fillna(0)
            ax[i,j].bar(num_event.index,num_event[fname_col[m]])
            plt.title(m)
            m+=1
            # print(m)
        except IndexError:
            ax[i,j].set_axis_off()

相关问题