0
import pandas
import numpy as np
import matplotlib.pyplot as plt

df = pandas.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
df=df[:15]


fig, ax = plt.subplots()
ax.axis('off')
ax.axis('tight')
tab=ax.table(cellText=df.values, colLabels=df.columns, loc='center',cellLoc='center')

tab.auto_set_font_size(False)
tab.auto_set_column_width(col=list(range(len(df.columns))))


for k, cell in tab._cells.items():
    cell.set_linewidth(0)
    if k[0] == 0:
        cell.set_text_props(weight='bold', color='w')
        cell.set_facecolor('#222B35')
    elif k[0]%2==0:
        cell.set_facecolor('#D9D9D9')

plt.tight_layout()

Out Plot

But I wanted, for example, to merge and center the columns headers for sepal_width and petal_length, which would give me something like:

Excel made objective table

tfaulhaber
  • 11
  • 2
  • 1
    This is not a good practice. The point of tabular data is for each column to be uniquely identifiable. This results in a visually confusing table. – Trenton McKinney Dec 11 '21 at 01:09
  • I don't think you can even do that... –  Dec 11 '21 at 01:09
  • You could do this: `df.set_index(['sepal_width', 'petal_length']).rename_axis(['sepal', 'width'])` –  Dec 11 '21 at 01:10
  • Although very very hacky, it might be an option for you... –  Dec 11 '21 at 01:11
  • @TrentonMcKinney I used an example dataset, the one actually want to use this code makes sense doing the merge. – tfaulhaber Dec 11 '21 at 01:35
  • I can't quite imagine which dataset make sense with this sort of merge. Maybe you mean MultiIndex column, where your columns actually has two (level) names? Something akin to pictures shown in [this quesion](https://stackoverflow.com/questions/18470323/selecting-columns-from-pandas-multiindex)? – Quang Hoang Dec 11 '21 at 05:02
  • 1
    @QuangHoang probably for autogenerating tables for automatic reports and not for analysing data – Simon Chemnitz-Thomsen Dec 11 '21 at 10:44
  • @SimonChemnitz-Thomsen Exactly! That's why I'm using matplotlib.pyplot, the goal is to go on and export this image for a daily report. – tfaulhaber Dec 11 '21 at 17:22
  • @QuangHoang Thanks! That's also pretty useful for a couple of other tables i want, I'll test it out and check if the "merged" header will maintain itself on the matplotlib table. – tfaulhaber Dec 11 '21 at 17:24

0 Answers0