簡體   English   中英

以每月日期增量注釋 matplotlib 熱圖 y 軸刻度

[英]Annotating matplotlib heatmap y-axis ticks in monthly date increments

我目前正在嘗試創建一個熱圖來表示當前存儲在數值矩陣中的一組數據。 然而,矩陣的每一行也與一個特定的日期值相關聯,我想在 y 軸刻度標簽上表示。 我目前有一些代碼可以做到這一點,看起來有點像這樣:

matrix = [[5, 9, 0, 4],
          [0, 8, 3, 6],
          [9, 1, 0, 4],
          [0, 0, 3, 1]]

dates = [datetime.today() - timedelta(weeks=x * random.getrandbits(2)) for x in range(4)]
x_labels = ['Y29K', 'D950N', 'D142G', 'T95I']

title = 'Example Heatmap'
cbtitle = 'Mutation Count'

fig, ax = plt.subplots()
im = ax.imshow(matrix)

# Implement colorbar
max_val = round(int(np.max(matrix))/10)*10
color_bar_rnge = np.linspace(0,max_val,10, endpoint=False)
cb = fig.colorbar(im, ticks=color_bar_rnge)
cb.ax.set_title(cbtitle)

# Show all x axis ticks and label them with the respective list entries
ax.set_xticks(np.arange(len(x_labels)), labels=x_labels)

m_dates = mdates.date2num(dates)
ax.set_yticks(np.arange(len(m_dates)), labels=m_dates)
ax.yaxis_date()

# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=90, ha="right",
         rotation_mode="anchor")

dx, dy = -6, 0
offset = ScaledTranslation(dx / fig.dpi, dy / fig.dpi, fig.dpi_scale_trans)

for label in ax.xaxis.get_majorticklabels():
    label.set_transform(label.get_transform() + offset)

ax.yaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.set_title(title)
fig.tight_layout()
fig.show()

輸出熱圖

但是由於某種原因,結果輸出似乎將 y 軸上的日期標記為 1970 年代。 此問題僅在我實施時出現:

ax.yaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

但是,我想以這種方式格式化我的日期,因為我的真實數據集包含數百個日期(每月有多個日期),因此用單獨的日期值標記每個刻度會在 y 軸上創建一組極度擁擠的標簽。 無論如何,是否只格式化日期 y_tick 標簽以每月增量進行注釋,或者是否有人知道繪制此類數據的可能更好的解決方案?

非常感謝

擺脫 1970 年的一種方法是將隨機生成的日期轉換為字符串列表,並使用 set_yticklabels() 將其用作標簽。 創建日期后,您可以使用dateLabels = [date.strftime('%Y-%m') for date in dates]將日期列表轉換為字符串。 但是,請注意所有月份都可能接近或相同。 您也可以添加-%d來查看日期。 在末尾添加ax.set_yticklabels(dateLabels)以用此列表替換標簽。

請注意,我必須進行一些其他更改,例如 set_xticks()、set_yticks() 並將它們拆分為包括 set_xticklables()、set_yticklabels(),因為您的代碼沒有在我的版本上運行。 請檢查是否需要所有代碼,因為有些代碼可能不再需要。

完整代碼如下。

import matplotlib.transforms as transforms
matrix = [[5, 9, 0, 4],
          [0, 8, 3, 6],
          [9, 1, 0, 4],
          [0, 0, 3, 1]]

dates = [datetime.today() - timedelta(weeks=x * random.getrandbits(2)) for x in range(4)]
dateLabels = [date.strftime('%Y-%m') for date in dates]
print(dateLabels)

x_labels = ['Y29K', 'D950N', 'D142G', 'T95I']

title = 'Example Heatmap'
cbtitle = 'Mutation Count'

fig, ax = plt.subplots()
im = ax.imshow(matrix)

# Implement colorbar
max_val = round(int(np.max(matrix))/10)*10
color_bar_rnge = np.linspace(0,max_val,10, endpoint=False)
cb = fig.colorbar(im, ticks=color_bar_rnge)
cb.ax.set_title(cbtitle)

# Show all x axis ticks and label them with the respective list entries
ax.set_xticks(np.arange(len(x_labels)))
ax.set_xticklabels(x_labels)

m_dates = mdates.date2num(dates)
ax.set_yticks(np.arange(len(m_dates)))
ax.yaxis_date()

# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=90, ha="right",
         rotation_mode="anchor")

dx, dy = -6, 0
offset = transforms.ScaledTranslation(dx / fig.dpi, dy / fig.dpi, fig.dpi_scale_trans)

for label in ax.xaxis.get_majorticklabels():
    label.set_transform(label.get_transform() + offset)

#ax.yaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.set_yticklabels(dateLabels)

ax.set_title(title)
fig.tight_layout()
fig.show()

輸出

['2022-07', '2022-07', '2022-06', '2022-06']

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM