Matplotlib: using a color table for a color table

I have a Pandas dataframe and I want to build it as a matplotlib table. So far, I have this part working with the 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 color palette, but how can I find it in the clm array without an index?

Another question: can I somehow transfer the format string to the table so that it formats the text to two decimal places?

Any hints, Andy

+6
source share
2 answers

You can use plt.Normalize() to normalize your data and pass normalized data to a Colormap object , for example plt.cm.hot() .

plt.table() is the argument cellColours , which will be used to set the background color of the cells accordingly.

Since cm.hot maps black to its minimum value, I increased the range of values ​​when creating the normalization object.

Here is the code:

 from matplotlib import pyplot as plt import numpy as np randn = np.random.randn from pandas import * idx = Index(np.arange(1,11)) df = DataFrame(randn(10, 5), index=idx, columns=['A', 'B', 'C', 'D', 'E']) vals = np.around(df.values,2) norm = plt.Normalize(vals.min()-1, vals.max()+1) colours = plt.cm.hot(normal(vals)) 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', cellColours=colours) plt.show() 

enter image description here

+11
source

Andy code works:

 #!/usr/bin/env python # -*- coding: utf-8 -*- # sudo apt-get install python-pandas # sudo apt-get install python-matplotlib # # python teste.py from matplotlib import pyplot from matplotlib import cm import numpy from pandas import * idx = Index(numpy.arange(1, 11)) df = DataFrame( numpy.random.randn(10, 5), index=idx, columns=['A', 'B', 'C', 'D', 'E'] ) vals = numpy.around(df.values, 2) normal = pyplot.normalize(vals.min()-1, vals.max()+1) fig = pyplot.figure(figsize=(15, 8)) ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[]) the_table = pyplot.table( cellText=vals, rowLabels=df.index, colLabels=df.columns, colWidths = [0.03]*vals.shape[1], loc='center', cellColours=pyplot.cm.hot(normal(vals)) ) pyplot.show() 
0
source

Source: https://habr.com/ru/post/921168/


All Articles