【问题标题】:how to do colormap to color table-cell background using matplotlib?如何使用 matplotlib 对表格单元格背景进行颜色映射?
【发布时间】:2021-07-08 05:04:59
【问题描述】:

我正在使用 pycharm 使用 matplotlib 库输出此表。但是我想根据值为单元格着色。

我目前的代码是

import matplotlib.pyplot as plt
import pandas as pd
fig, ax =plt.subplots(1,1)
ax.axis('tight')
ax.axis('off')
table_data = pd.read_csv("test.csv")

table_data =table_data.astype({"Runs":int, "HS":int})
table_data =table_data.sort_values(by='HS')
df = table_data


table = ax.table(cellText=df.values,
        colLabels=df.columns,
        loc="center",
        cellLoc="left")
table.auto_set_column_width(col=list(range(len(df.columns))))
plt.show()

我的数据集的“HS”列和“S/R”列的输出应类似于“BasePay”列和“OtherPay”列(请参阅下图)。

我尝试在 python 上使用样式库,但它们不会在 pycharm 上本地打印,因此我需要它作为 plt.show()

【问题讨论】:

    标签: python pandas matplotlib visualization


    【解决方案1】:

    对于单元格的背景色,可以使用对应的想要装饰的颜色列表,也可以使用色图按照数据值创建颜色列表进行装饰。对于后一种方法,我尝试了 seaborn 的调色板和 matplotlib 的方法。由于数据按升序排列,因此将 seaborn 的调色板应用于 HS 列。在新列中并按原始顺序重新排序。然后用重新排序的列表装饰目标列。

    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns
    
    fig, ax =plt.subplots(1,1)
    ax.axis('tight')
    ax.axis('off')
    table_data = pd.read_csv("test.csv")
    
    table_data =table_data.astype({"Runs":int, "HS":int})
    table_data =table_data.sort_values(by='HS')
    df = table_data
    
    table = ax.table(cellText=df.values,
            colLabels=df.columns,
            loc="center",
            cellLoc="left")
    table.auto_set_column_width(col=list(range(len(df.columns))))
    
    # sns color palette use(data:ascending)
    bcmap = sns.mpl_palette("Blues", len(table_data['HS'].unique()))
    for idx,b in enumerate(bcmap):
        table[(idx+1, 6)].set_facecolor(b)
    
    # matplotlib colormap
    from matplotlib import cm
    vals = table_data['S/R']
    normal = cm.colors.Normalize(vals.min(), vals.max())
    bcmap2 = plt.cm.Blues(normal(vals))
    
    for idx, bb in enumerate(bcmap2):
        table[(idx+1, 10)].set_facecolor(bb)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      • 2019-03-28
      相关资源
      最近更新 更多