【问题标题】:Drawing over matplotlib axis/figs: get yticklabel individual position and use it for drawlines绘制 matplotlib 轴/无花果:获取 yticklabel 单个位置并将其用于绘制线
【发布时间】:2014-05-09 11:16:57
【问题描述】:

我想知道支配更高级 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 上分离特征,如下图所示(我在其中手动绘制):

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

【问题讨论】:

  • 我不清楚您是如何得出水平线的 y 值的;那些和 yticks 有关系吗?
  • 我认为 axhline 可以满足您的需求。
  • hline + clip_on=False (抱歉,没有时间写一个更完整的答案)
  • @tillsten axhline 非常聪明,并以轴分数单位设置限制,因此它不能做边缘部分。

标签: python matplotlib heatmap


【解决方案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))

【讨论】:

  • 是的,但是谁来检测特定 yticklabel 完成的位置?这是主要问题。
  • 某事 yticklabel_pos = like ax.yaxis.get_label_position()
  • 这其实很简单,把[5,10,15,20]换成[i for i, v in enumerate(y_labels) if v in [a list of THE_TICK_LABELS_YOU_WANT TO DRAW LINES AT]]就行了
猜你喜欢
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2015-06-17
  • 2016-02-16
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
相关资源
最近更新 更多