gpt4 book ai didi

python - 在 matplotlib 轴/图上绘图 : get yticklabel individual position and use it for drawlines

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:59 26 4
gpt4 key购买 nike

我想知道掌握更高级 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)

我的需要是在热图上画线,以分离 ytickslabel 上的特征,如下图所示(我手工绘制):

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

有人知道如何以编程方式编写 matplotlib 来做到这一点吗?

最佳答案

我会冒昧地为@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

关于python - 在 matplotlib 轴/图上绘图 : get yticklabel individual position and use it for drawlines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23563246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com