如何使用matplotlib.pyplot在条形图和数据表之间创建空间?

时间:2020-03-23 19:15:38

标签: python-3.x matplotlib

我一直在寻找几个小时,如何使用matplotlib.pyplot在条形图和表格之间添加空间,但是我还没有找到如何正确显示布局的解决方案。当前,表格的顶部与条形图x轴标题冲突,表格的底部不在图中。我尝试使用figsize来放大图形,尝试使用bboxsubplots_adjustplt.tight_layout(),但没有一个可行。任何帮助表示赞赏。

enter image description here

def plot_bar(df, *args):
    df = pd.DataFrame([{'OPEN': 4, 'CLOSED': 139, 'DATE': '2019-01-01'}, {'OPEN': 0, 'CLOSED': 139, 'DATE': '2019-02-01'}, {'OPEN': 1, 'CLOSED': 124, 'DATE': '2019-03-01'}, {'OPEN': 4, 'CLOSED': 127, 'DATE': '2019-04-01'}, {'OPEN': 1, 'CLOSED': 84, 'DATE': '2019-05-01'}, {'OPEN': 6, 'CLOSED': 113, 'DATE': '2019-06-01'}, {'OPEN': 0, 'CLOSED': 123, 'DATE': '2019-07-01'}, {'OPEN': 2, 'CLOSED': 109, 'DATE': '2019-08-01'}, {'OPEN': 0, 'CLOSED': 107, 'DATE': '2019-09-01'}, {'OPEN': 7, 'CLOSED': 119, 'DATE': '2019-10-01'}, {'OPEN': 2, 'CLOSED': 82, 'DATE': '2019-11-01'}, {'OPEN': 4, 'CLOSED': 83, 'DATE': '2019-12-01'}, {'OPEN': 12, 'CLOSED': 112, 'DATE': '2020-01-01'}, {'OPEN': 10, 'CLOSED': 89, 'DATE': '2020-02-01'}, {'OPEN': 31, 'CLOSED': 64, 'DATE': '2020-03-01'}])
    df["DATE"] = pd.to_datetime(df["DATE"])
    df['DATE'] = df['DATE'].apply(lambda x: [x.month, x.year])
    df['DATE'] = df['DATE'].apply(lambda x: f'{calendar.month_abbr[x[0]]}-{x[1]}')

    ax = df.plot.bar(x=args[0]['x'], y=args[0]['y'], figsize=(15, 7))
    for i, v in enumerate(df['OPEN']):
        ax.text(i - .20, v + 1, str(v), color='blue', fontweight='bold')
    for i, v in enumerate(df['CLOSED']):
        ax.text(i - .20, v + 1, str(v), color='orange', fontweight='bold')

    plt.title('Open vs Closed Tickets')
    plt.xlabel('Time')
    plt.ylabel('Tickets')

    table_columns = df['DATE'].values.tolist()
    open = df['OPEN'].values.tolist()
    closed = df['CLOSED'].values.tolist()
    table_data = [open, closed]
    table_rows = df.columns.values.tolist()[0:2]
    plt.table(cellText=table_data, rowLabels=table_rows, colLabels=table_columns, loc='bottom',
              bbox=[0, -0.250, 1, 0.2])

    plt.tight_layout()

    plt.show()

    return

正在回答Diziet Asahi:我进行了这2次更改,但是我的桌子仍然被切成两半,这真令人沮丧。

enter image description here

1 个答案:

答案 0 :(得分:0)

一个可能的问题是,您必须在tight_layout()之后使用plt.subplots_adjust(bottom=xxx) (否则,tight_layout将撤消对subplots_adjust所做的操作)。这将改变地块的大小,并为下表提供更多空间。增加xxx的值以满足您的需要,该值以图形的分数给出,因此bottom=0.2会将图形的底部定位在图形高度的20%处。

另一个问题是您正在使用plt.table(),它使表格“粘”在轴上。如果将表格放置在轴下方,则基本上应该替换x轴标签。但是您必须在使用loc=(自动放置)或bbox=(手动放置)之间进行选择。您不能同时使用两者。

这是做这两件事的结果:

import calendar
df = pd.DataFrame([{'OPEN': 4, 'CLOSED': 139, 'DATE': '2019-01-01'}, {'OPEN': 0, 'CLOSED': 139, 'DATE': '2019-02-01'}, {'OPEN': 1, 'CLOSED': 124, 'DATE': '2019-03-01'}, {'OPEN': 4, 'CLOSED': 127, 'DATE': '2019-04-01'}, {'OPEN': 1, 'CLOSED': 84, 'DATE': '2019-05-01'}, {'OPEN': 6, 'CLOSED': 113, 'DATE': '2019-06-01'}, {'OPEN': 0, 'CLOSED': 123, 'DATE': '2019-07-01'}, {'OPEN': 2, 'CLOSED': 109, 'DATE': '2019-08-01'}, {'OPEN': 0, 'CLOSED': 107, 'DATE': '2019-09-01'}, {'OPEN': 7, 'CLOSED': 119, 'DATE': '2019-10-01'}, {'OPEN': 2, 'CLOSED': 82, 'DATE': '2019-11-01'}, {'OPEN': 4, 'CLOSED': 83, 'DATE': '2019-12-01'}, {'OPEN': 12, 'CLOSED': 112, 'DATE': '2020-01-01'}, {'OPEN': 10, 'CLOSED': 89, 'DATE': '2020-02-01'}, {'OPEN': 31, 'CLOSED': 64, 'DATE': '2020-03-01'}])
df["DATE"] = pd.to_datetime(df["DATE"])
df['DATE'] = df['DATE'].apply(lambda x: [x.month, x.year])
df['DATE'] = df['DATE'].apply(lambda x: f'{calendar.month_abbr[x[0]]}-{x[1]}')

ax = df.plot.bar(x='DATE', y=['OPEN','CLOSED'], figsize=(15, 7))
for i, v in enumerate(df['OPEN']):
    ax.text(i - .20, v + 1, str(v), color='blue', fontweight='bold')
for i, v in enumerate(df['CLOSED']):
    ax.text(i - .20, v + 1, str(v), color='orange', fontweight='bold')

plt.title('Open vs Closed Tickets')
plt.ylabel('Tickets')

#remove all x-labels since the table will be used instead
plt.xlabel('')
plt.xticks([])


table_columns = df['DATE'].values.tolist()
open = df['OPEN'].values.tolist()
closed = df['CLOSED'].values.tolist()
table_data = [open, closed]
table_rows = df.columns.values.tolist()[0:2]
plt.table(cellText=table_data, rowLabels=table_rows, colLabels=table_columns, loc='bottom')

plt.tight_layout()
plt.subplots_adjust(bottom=0.1)

plt.show()

enter image description here