gpt4 book ai didi

python - 绘制二维数据 : heatmap with different colormaps

转载 作者:太空狗 更新时间:2023-10-30 02:30:46 24 4
gpt4 key购买 nike

我想可视化我拥有的二维数据。例如以下是具有四个属性的数据:

       att1  att2   att3
fun1 10 0 2
fun2 0 1 3
fun3 1 10 5
fun4 2 3 10

我想为每个数据点分配不同的颜色。颜色的强度将取决于该列中属性的值,并且每列必须具有不同的颜色。

下面是想要的图片:

enter image description here

有谁知道如何用 Python 或 R 实现它?

最佳答案

使用 Python:

我找到了一个更好的方法:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm

# data loading
df = pd.read_csv("file.csv", index_col=0)


# plotting
fig,ax = plt.subplots()
ax.matshow(df.mask(((df == df) | df.isnull()) & (df.columns != "att1")),
cmap=cm.Reds) # You can change the colormap here
ax.matshow(df.mask(((df == df) | df.isnull()) & (df.columns != "att2")),
cmap=cm.Greens)
ax.matshow(df.mask(((df == df) | df.isnull()) & (df.columns != "att3")),
cmap=cm.Blues)
plt.xticks(range(3), df.columns)
plt.yticks(range(4), df.index)
plt.show()

hm

一些细节:

df.mask(((df == df) | df.isnull()) & (df.columns != "att1"))
att1 att2 att3
fun1 10 NaN NaN
fun2 0 NaN NaN
fun3 1 NaN NaN
fun4 2 NaN NaN

旧版本,带有 numpy 掩码数组:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from numpy.ma import masked_array
import numpy as np

df = pd.read_clipboard() # just copied your example

# define masked arrays to mask all but the given column
c1 = masked_array(df, mask=(np.ones_like(df)*(df.values[0]!=df.values[0][0])))
c2 = masked_array(df, mask=(np.ones_like(df)*(df.values[0]!=df.values[0][1])))
c3 = masked_array(df, mask=(np.ones_like(df)*(df.values[0]!=df.values[0][2])))

fig,ax = plt.subplots()
ax.matshow(c1,cmap=cm.Reds) # You can change the colormap here
ax.matshow(c2,cmap=cm.Greens)
ax.matshow(c3,cmap=cm.Blues)
plt.xticks(range(3), df.columns)
plt.yticks(range(4), df.index)

一些细节:

df 是一个数据框:

      att1  att2  att3
fun1 10 0 2
fun2 0 1 3
fun3 1 10 5
fun4 2 3 10

c1、c2、c3 是屏蔽数组(用于第 1、2 和 3 列):

>>> c1
masked_array(data =
[[10 -- --]
[0 -- --]
[1 -- --]
[2 -- --]],
mask =
[[False True True]
[False True True]
[False True True]
[False True True]],
fill_value = 999999)

或者,您可以从一个 numpy 二维数组开始:

>> data
array([[10, 0, 2],
[ 0, 1, 3],
[ 1, 10, 5],
[ 2, 3, 10]])

并将所有 dfdf.values 替换为 data(二维数组),标签部分除外。

关于python - 绘制二维数据 : heatmap with different colormaps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25154056/

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