gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:38:23 24 4
gpt4 key购买 nike

我正在尝试将 Python 中的大型(pandas)数据帧可视化为热图。该数据框有两种类型的变量:字符串(“不存在”或“未知”)和 float 。

我希望热图以黑色显示“不存在”,以红色显示“未知”的单元格,并将数据框的其余部分显示为普通热图,并以绿色比例显示 float 。

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

感谢您的宝贵时间。

最佳答案

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

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 (https://stackoverflow.com/a/18195921/190597)
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()
<小时/>

数据框

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

变成了

enter image description here

关于Python 绘图 : Heatmap from dataframe with fixed colors in case of strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40048702/

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