2016-05-05 119 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