3

I am creating a matplotlib table with Total calculated. However, I would like to merge 2 adjacent cell and show 'Total' in the merged cell.

import matplotlib.backends.backend_pdf
import pandas as pd

pdf = matplotlib.backends.backend_pdf.PdfPages("test.pdf")

fig = plt.figure(figsize=(20, 20))
grid = plt.GridSpec(1, 2, wspace=0.2,width_ratios=[14, 6])
plt.autoscale()
ax0 = fig.add_subplot(grid[0 ,0])
ax1 = fig.add_subplot(grid[0, 1])
df = pd.DataFrame({'country': ['ABC','PQR','XYZ','ABC','PQR'], 'region': ['D','E','F','D','F'], 'month_day':[1,1,1,2,3],'sales' : [100,200,300,500,100]})
table=pd.pivot_table(df, values='sales', index=['country','region'], columns=['month_day'], aggfunc=sum, fill_value=0, margins=True, margins_name='TOTAL').drop(['TOTAL'],axis=1)
table.reset_index(inplace=True)
the_table = ax0.table(cellText=table.values,colLabels=table.columns,colWidths=[0.07,0.06,0.04,0.04,0.04],loc='center')
ax0.axis("off")
ax1.axis("off")
plt.axis("off")
pdf.savefig(fig, bbox_inches='tight')
pdf.close()  

I am getting output as below: enter image description here

Expected output is: enter image description here

Vishal
  • 41
  • 1
  • 5
  • 1
    Matplotlib does not know about the concept of "merged cells". See [this](https://stackoverflow.com/questions/53573121/plot-table-along-chart-using-matplotlib/53573651#53573651) – ImportanceOfBeingErnest Apr 10 '20 at 16:52
  • This question has been answer here: [https://stackoverflow.com/questions/53783087/double-header-in-matplotlib-table](https://stackoverflow.com/questions/53783087/double-header-in-matplotlib-table) – Jorge Jun 18 '22 at 23:16

0 Answers0