【问题标题】:How to plot a table with colors depending on the values in a dataframe?如何根据数据框中的值绘制带有颜色的表格?
【发布时间】:2019-05-22 07:21:08
【问题描述】:

假设我有这个数据帧 df 从矩阵转移:

    1   2   3   4   5   6   7   8

1   1399    17  4   3   0   0   0   0
2   11  374     2   3   1   4   0   1
3   7   0   187     4   0   0   1   1
4   2   3   4   308     0   0   0   3
5   2   0   0   0   280     3   0   1
6   0   2   0   0   2   81  0   3
7   1   0   2   0   2   0   154     4
8   0   0   1   2   1   1   8   552

我想将此绘制为一个表格,其中较高的值颜色较深,而较小的值颜色较浅,具体取决于它们的标量值。但我不确定这是否可能。所有的绘图技术似乎都不包括带有颜色的表格。有任何想法吗?

谢谢

【问题讨论】:

标签: python pandas dataframe matplotlib plot


【解决方案1】:

使用matplotlib.pyplot.subplots:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.matshow(df, cmap=plt.cm.Greys)

输出:

【讨论】:

  • 网格的内容呢?如何让它也打印值?
【解决方案2】:

这是另一种方式:

import matplotlib.pyplot as plt
import numpy as np

a = df.to_numpy()
fig, ax = plt.subplots()

for i in range(df.shape[0]):
    for j in range(df.shape[1]):
         text = ax.text(j, i, a[i, j],
                        ha="center", va="center", color="w")

ax.set_title("Your title")
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()

更多详情您可以查看this URL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2023-03-06
    相关资源
    最近更新 更多