python热图_python – 绘制2D数据:使用不同颜色图的热图

使用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()

一些细节:

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 2D数组开始:

>> data

array([[10, 0, 2],

[ 0, 1, 3],

[ 1, 10, 5],

[ 2, 3, 10]])

并使用数据(2D数组)替换所有df和df.values,标记部分除外.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值