Python 绘图:在字符串的情况下,来自具有固定颜色的数据框的热图

Python Plotting: Heatmap from dataframe with fixed colors in case of strings

我正在尝试将 Python 中的大型 (pandas) 数据框可视化为热图。此数据框有两种类型的变量:字符串("Absent" 或 "Unknown")和浮点数。

我希望热图显示带有 "Absent" 黑色和 "Unknown" 红色的单元格,并将数据框的其余部分显示为普通热图,浮点数为绿色。

我可以在 Excel 中使用单元格的条件格式轻松完成此操作,但我无法在线找到任何帮助来使用 Python 使用 matplotlib、seaborn、ggplot 来执行此操作。我错过了什么?

感谢您的宝贵时间。

您可以使用 cmap_custom.set_under('red')cmap_custom.set_over('black') 将自定义颜色应用于低于和高于 vminvmax 的值(参见 1, ):

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1 as axes_grid1
import pandas as pd

# make a random DataFrame
np.random.seed(1)
arr = np.random.choice(['Absent', 'Unknown']+list(range(10)), size=(5,7))
df = pd.DataFrame(arr)

# find the largest and smallest finite values
finite_values = pd.to_numeric(list(set(np.unique(df.values))
                                   .difference(['Absent', 'Unknown'])))
vmin, vmax = finite_values.min(), finite_values.max()

# change Absent and Unknown to numeric values
df2 = df.replace({'Absent': vmax+1, 'Unknown': vmin-1})
# make sure the values are numeric
for col in df2:
    df2[col] = pd.to_numeric(df2[col])

fig, ax = plt.subplots()
cmap_custom = plt.get_cmap('Greens')
cmap_custom.set_under('red')
cmap_custom.set_over('black')
im = plt.imshow(df2, interpolation='nearest', cmap = cmap_custom, 
           vmin=vmin, vmax=vmax)
# add a colorbar (
divider = axes_grid1.make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax, extend='both')
plt.show()

DataFrame

In [117]: df
Out[117]: 
        0        1  2        3  4        5       6
0       3        9  6        7  9        3  Absent
1  Absent  Unknown  5        4  7        0       2
2       3        0  2        9  8        0       2
3       5        5  7  Unknown  5   Absent       4
4       7        7  5        4  7  Unknown  Absent

变成