使用颜色映射来对表格单元格背景进行颜色

使用颜色映射来对表格单元格背景进行颜色

本文介绍了matplotlib:使用颜色映射来对表格单元格背景进行颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas数据框架,我想绘制为matplotlib表。到目前为止,我有这部分使用下面的代码:

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

这个我想根据颜色设置单元格的背景颜色 - 但我怎么查找在没有索引的clm数组?

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?

另一个问题:我可以以某种方式传递一个格式字符串到表,以便它格式化文本到2个小数位?

Another question: can i somehow pass a format string to the table, so that it formats the text to 2 decimal places?

任何提示,
Andy

Any hints appreciated,Andy

推荐答案

您可以使用plt.normalize()创建一个Normalize对象来规范化数据,并将标准化数据传递给Colormap对象获取颜色。

You can use plt.normalize() to create a Normalize object to normalize your data, and pass the normalize data to the Colormap object to get the colors.

plt.table()有一个cellColours参数,用于设置每个单元格的背景颜色。

plt.table() has a cellColours argument which set every cell's background color.

因为cm.hot色彩映射使用黑色作为最小值,所以我在创建normalize对象时增加了值的范围。

Because the cm.hot colormap use black color for minimal value, I increased the value range when create the normalize object.

这里是代码:

from matplotlib import pyplot as plt
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)
normal = plt.normalize(vals.min()-1, vals.max()+1)

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=plt.cm.hot(normal(vals)))

>

这篇关于matplotlib:使用颜色映射来对表格单元格背景进行颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:48