I want to use Matplotlib to create tables to be exported to a pdf.
I struggle with the following.
To in a automated fashion create a list of list for the colorization of the cells. The first columns should be white, the second green, and so on.
To set an alpha value for rows I color with green, to increase transparancy.
df = pd.DataFrame({'Name':['Z', 'S', 'H'],
'Category':['A', 'A', 'A'],
'Number':[2,1,3],
'P':[0,0,0]})
col_col=[]
blue = '#00005A'
green = '#95C13E'
for i in range(len(df.columns)):
col_col.append(blue)
fig, ax = plt.subplots()
plt.rcParams['font.family'] = 'Arial'
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')
# Can I use a for loop to create the list of list colo in smart way?
colo = [["w",green,"w", green],["w",green,"w", green],["w",green,"w", green]]
table=ax.table(cellText=df.values, colLabels=df.columns, loc='center',
colColours=col_col,
cellColours=colo)
table=ax.table(cellText=df.values, colLabels=df.columns, loc='center',
colColours=col_col,
cellColours=colo)
for i, j in zip(table.properties()['celld'], table.properties()['children']):
if i[0]==0:
j.get_text().set_color('white')
j.get_text().set_weight('bold')
fig.tight_layout()
plt.show()
CodePudding user response:
The easiest way to do this is to convert the green color you are specifying to RGBA format and specify the transparency.
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors #import
df = pd.DataFrame({'Name':\['Z', 'S', 'H'\],
'Category':\['A', 'A', 'A'\],
'Number':\[2,1,3\],
'P':\[0,0,0\]})
col_col=\[\]
blue = '#00005A'
green = '#95C13E'
green = mcolors.to_rgba(green, alpha=0.5) #update and set alpha value
for i in range(len(df.columns)):
col_col.append(blue)
fig, ax = plt.subplots()
plt.rcParams\['font.family'\] = 'Arial'
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')
# Can I use a for loop to create the list of list colo in smart way?
colo = \[\["w",green,"w", green\],\["w",green,"w", green\],\["w",green,"w", green\]\]
table=ax.table(cellText=df.values, colLabels=df.columns, loc='center',
colColours=col_col,
cellColours=colo)
for i, j in zip(table.properties()\['celld'\], table.properties()\['children'\]):
if i\[0\]==0:
j.get_text().set_color('white')
j.get_text().set_weight('bold')
fig.tight_layout()
plt.show()