繁体   English   中英

将第二个颜色条添加到Seaborn热图/群集图

[英]Add Second Colorbar to a Seaborn Heatmap / Clustermap

我试图帮助某人在下图中为垂直的蓝色条添加颜色条。 我们尝试了plt.colorbar(row_colors)许多变体(如sns.clustermap()上方和下方),并在网上环顾了2小时,但没有运气。 我们只想为蓝调添加颜色条,请帮忙!

import pickle
import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

feat_mat, freq, label = pickle.load(open('file.pkl', 'rb'))

feat_mat_df = pd.DataFrame(feat_mat[4])

freq_df = pd.DataFrame(freq)
freq_df_transposed = freq_df.transpose()

my_palette = dict(zip(set(freq_df_transposed[int('4')]), sns.color_palette("PuBu", len(set(freq_df_transposed[int('4')]))))))
row_colors = freq_df_transposed[int('4')].map(my_palette)

sns.clustermap(feat_mat_df, metric="euclidean", standard_scale=1, method="complete", cmap="coolwarm", row_colors = row_colors)

plt.show()

图片

这是他基于以下代码的地方: #405具有热图和彩色叶子的树状图

我认为类似这样的东西应该可以满足您的目的-我没有可用的clustermap示例,但是执行您想做的事情的逻辑是相同的。 基本上,您将获取制作的颜色列表并进行显示,然后隐藏显示效果图,并在其位置上绘制颜色栏。 在我的例子中,我使用make_axes_locatable放置轴与您的数据的情节旁边把里面的颜色条- https://matplotlib.org/2.0.2/mpl_toolkits/axes_grid/users/overview.html 我发现为其他对象(传奇色彩映射或其他)放置新轴比尝试在相同轴上绘制轴更容易。

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)
import seaborn as sns
from mpl_toolkits.axes_grid1 import make_axes_locatable
import random


uniform_data = np.random.rand(10, 12)

fig, ax = plt.subplots(1,1, figsize = (5,5))
divider = make_axes_locatable(ax)

axDivY = divider.append_axes( 'right', size=0.2, pad= 0.1)
axDivY2 = divider.append_axes( 'right', size=0.2, pad= 0.2)

# we will use this for the colorscale bar
axDivY3 = divider.append_axes( 'right', size=0.2, pad= 0.2)
ax1 = sns.heatmap(uniform_data, ax=ax, cbar_ax=axDivY)


# the palette you were using to make the label column on the clustermap

# some simulated labels for your data with values
color_label_list =[random.randint(0,20) for i in range(20)]

pal =  sns.color_palette("PuBu", len(set(color_label_list)))
n = len(pal)
size = 1

# plot the colors with imshow to make a colormap later
ax2 = axDivY2.imshow(np.array([color_label_list]),
              cmap=mpl.colors.ListedColormap(list(pal)),
              interpolation="nearest", aspect="auto")
# turn off the axes so they aren't visible- note that you need ax.axis('off) if you have older matplotlib
axDivY2.set_axis_off()
axDivY2.set_visible(False)
# plot the colorbar on the other axes (which is on top of the one that we turned off)
plt.colorbar(ax2, cax = axDivY3) ;

产量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM