I have a Pandas dataframe, and i want to plot it as matplotlib table. So far i have that part working with following code:
import numpy as np
randn = np.random.randn
from pandas import *
idx = Index(arange(1,11))
df = DataFrame(randn(10, 5), index=idx, columns=['A', 'B', 'C', 'D', 'E'])
vals = np.around(df.values,2)
fig = plt.figure(figsize=(15,8))
ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[])
the_table=plt.table(cellText=vals, rowLabels=df.index, colLabels=df.columns,
colWidths = [0.03]*vals.shape[1], loc='center')
table_props = the_table.properties()
table_cells = table_props['child_artists']
clm = cm.hot(vals)
for cell in table_cells:
cell.set_height(0.04)
# now i would like to set the backgroundcolor of the cell
At the end of this i would like to set the background-color of the cell according to the colormap – but how do i look it up in the clm array without an index?
Another question: can i somehow pass a format string to the table, so that it formats the text to 2 decimal places?
Any hints appreciated,
Andy
You can use
plt.Normalize()to normalize your data, and the pass the normalized data to aColormapobject, for exampleplt.cm.hot().plt.table()has an argumentcellColours, which will be used to set the cells’ background color accordingly.Because
cm.hotmaps black to the minimal value, I increased the value range when creating the normalization object.Here is the code: