简体   繁体   English

seaborn 配对图旁边的颜色条

[英]Colorbar next to seaborn pairplot

from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
from pandas import DataFrame

# generate 2d classification dataset
X, y = make_blobs(n_samples=100, centers=3, n_features=2)
# scatter plot, dots colored by class value
df1 = DataFrame(dict(x=X[:,0], y=X[:,1], label=y))


norm = plt.Normalize(df1.x.min(), df1.x.max())
sm = plt.cm.ScalarMappable(cmap=sns.cubehelix_palette(df1['x'].max(), start=.5, rot=-.75,as_cmap=True), norm=norm)
sm.set_array([])

ax=sns.pairplot(df1,vars=['x','y'], 
            hue='label',
            palette=sns.cubehelix_palette(df1['x'].max(), start=.5, rot=-.75),
            diag_kind=None,plot_kws={"s": 50})

ax._legend.remove()

# ax.set_ylabel('WT04: Pairplot for features')
cbar=ax.fig.colorbar(sm)
m0=int(np.floor(df1.x.min()))            # colorbar min value
m4=int(np.ceil(df1.x.max()))             # colorbar max value
m1=int(1*(m4-m0)/4.0 + m0)               # colorbar mid value 1
m2=int(2*(m4-m0)/4.0 + m0)               # colorbar mid value 2
m3=int(3*(m4-m0)/4.0 + m0)               # colorbar mid value 3
cbar.set_ticks([m0,m1,m2,m3,m4])
cbar.set_ticklabels([m0,m1,m2,m3,m4])

ax.fig.suptitle('WT04: Pairplot for features',y=0.99)
plt.subplots_adjust(top=0.94)
plt.show()

plt.savefig('result.png')

Generates this plot生成此 plot 在此处输入图像描述

However, I would like to have the colorbar to the right of the pairplot, and not the bottom right.但是,我希望将颜色条放在配对图的右侧,而不是右下角。 How can this be done?如何才能做到这一点? Some of my pairplots have other dimensions, so something scalable would be nice.我的一些pairplots有其他维度,所以一些可扩展的会很好。

You can try adding the colorbar with plt :您可以尝试使用plt添加颜色栏:

ax._legend.remove()

# remove this colorbar
# cbar=ax.fig.colorbar(sm)

m0=int(np.floor(df1.x.min()))            # colorbar min value
m4=int(np.ceil(df1.x.max()))             # colorbar max value
m1=int(1*(m4-m0)/4.0 + m0)               # colorbar mid value 1
m2=int(2*(m4-m0)/4.0 + m0)               # colorbar mid value 2
m3=int(3*(m4-m0)/4.0 + m0)               # colorbar mid value 3

ax.fig.suptitle('WT04: Pairplot for features',y=0.99)

# use this colorbar
cbar = plt.colorbar(sm, ax=ax.axes)

cbar.set_ticks([m0,m1,m2,m3,m4])
cbar.set_ticklabels([m0,m1,m2,m3,m4])

Output: Output:

在此处输入图像描述

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

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