绘制matplotlib轴/ figs:获取yticklabel个别位置并将其用于绘制线条

时间:2014-05-09 11:16:58

标签: python matplotlib heatmap

我想知道是否有人主宰更高级的matplotlib可以帮助我解决这个问题。我有一个热图,可以使用以下代码进行模拟:

import numpy as np
import string
from matplotlib import pylab as plt

def random_letter(chars=string.ascii_uppercase, size=2):
    char_arr = np.array(list(chars))
    if size > 27:
        size = 27
    np.random.shuffle(char_arr)
    return char_arr[:size]

data = np.random.poisson(1, (174, 40))

y_labels = [', '.join(x for x in random_letter()) for _ in range(174)]
y_labels = sorted(y_labels)

fig, ax = plt.subplots()
fig.set_size_inches(11.7, 16.5)

heatmap = ax.pcolor(data, 
                    cmap=plt.cm.Blues, 
                    vmin=data.min(), 
                    vmax=data.max(), 
                    edgecolors='white')
ax.set_xticks(np.arange(data.shape[1])+.5, minor=False);
ax.set_yticks(np.arange(data.shape[0])+.5, minor=False);
ax.set_xticklabels(np.arange(40), rotation=90);
ax.set_yticklabels(y_labels, fontsize=5);
cb = fig.colorbar(heatmap, shrink=0.33, aspect=10)

我需要在热图上绘制线条,在ytickslabels上分隔功能,如下图所示(我手工绘制):

heatmap with red lines draw over the y tick label when the first letter changes

任何人都知道如何以编程方式编写matplotlib代码来做到这一点?

1 个答案:

答案 0 :(得分:1)

我冒昧地为@tcaswell编写完整的解决方案,实际上它只需要7行:

xl, xh=ax.get_xlim()
left=xl-(xh-xl)*0.1 #10% extension on each side
right=xh+(xh-xl)*0.1
Lines=ax.hlines([5,10,15,20], left, right, color='r', linewidth=1.2)
Lines.set_clip_on(False)
ax.set_xlim((xl, xh))

enter image description here