2016-05-05 120 views
2

我刚刚创建了以下热图。 enter image description herePython - Seaborn:修改热图图例

在图例中,max(vmax)设置为0.10。我这样做是因为我想避免着色更多的“极端”价值观。但是在图例中,是否可以修改它并写入“> = 0.10”因此添加“大于或等于”?

+0

你可以制作一个可重现的例子吗? –

回答

4

所以这是一个非常冒险的解决方案,并认为几乎肯定有一个更聪明的方法来做到这一点,希望@mwaskom可以权衡,但我可以通过显式传递参数时访问颜色条对象像这样的热图功能:

import seaborn as sns; sns.set() 
import numpy as np; np.random.seed(0) 
from matplotlib import pyplot as plt 

fig, ax = plt.subplots() 
fig.set_size_inches(14, 7) 
uniform_data = np.random.rand(10, 12) 
cbar_ax = fig.add_axes([.92, .3, .02, .4]) 
sns.heatmap(uniform_data, ax=ax, cbar_ax=cbar_ax) 

生产这样的:

enter image description here

我能找到蜱自己ax.get_yticks()

In [41]: cbar_ax.get_yticks() 
Out [41]: array([ 0.19823662, 0.39918933, 0.60014204, 0.80109475]) 

标签本身是字符串:

In [44]: [x.get_text() for x in cbar_ax.get_yticklabels()] 
Out [44]: [u'0.2', u'0.4', u'0.6', u'0.8'] 

因此,我们可以简单地改变我们的yticklabels的文本对象最后一个元素,并希望得到一个修正的轴,这是我的最终代码:

fig, ax = plt.subplots() 
fig.set_size_inches(14, 7) 
uniform_data = np.random.rand(10, 12) 
#add an axis to our plot for our cbar, tweak the numbers there to play with the sizing. 
cbar_ax = fig.add_axes([.92, .3, .02, .4]) 
#assign the cbar to be in that axis using the cbar_ax kw 
sns.heatmap(uniform_data, ax=ax, cbar_ax=cbar_ax) 

#hacky solution to change the highest (last) yticklabel 
changed_val = ">= " + cbar_ax.get_yticklabels()[-1].get_text() 

#make a new list of labels with the changed value. 
labels = [x.get_text() for x in cbar_ax.get_yticklabels()[:-1]] + [changed_val] 

#set the yticklabels to the new labels we just created. 
cbar_ax.set_yticklabels(labels) 

主要生产:

enter image description here

关于这个问题的一些额外的资源可以找到here,我从mwaskom的回应中提取了一些信息。

+0

真棒!谢谢!这真的很清楚 – Plug4