gpt4 book ai didi

python - matplotlib:使用颜色图为表格单元格背景着色

转载 作者:太空狗 更新时间:2023-10-29 21:29:40 25 4
gpt4 key购买 nike

我有一个 Pandas 数据框,我想将其绘制为 matplotlib 表。到目前为止,我已经使用了以下代码:

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 数组中查找它?

另一个问题:我能否以某种方式将格式字符串传递给表格,以便将文本格式化为小数点后两位?

任何提示表示赞赏,安迪

最佳答案

您可以使用 plt.Normalize()规范化您的数据,并将规范化的数据传递给 Colormap object ,例如 plt.cm.hot() .

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

因为 cm.hot 将黑色映射到最小值,所以我在创建归一化对象时增加了取值范围。

代码如下:

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

关于python - matplotlib:使用颜色图为表格单元格背景着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11623056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com