matplotlib: using a colormap to color table-cell background

后端 未结 2 552
情话喂你
情话喂你 2020-12-28 09:39

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.rand         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 10:29

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

    plt.table() has an argument cellColours, which will be used to set the cells' background color accordingly.

    Because cm.hot maps black to the minimal value, I increased the value range 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

提交回复
热议问题