亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用seaborn繪制熱圖時,可以將多行標記為一個標簽嗎?

使用seaborn繪制熱圖時,可以將多行標記為一個標簽嗎?

慕斯709654 2023-08-22 10:28:19
我正在繪制熱圖。我想用它的類別替換原來的 y 軸。例如:數據:                    Location 1    Location 2      Location 3cluster 1:    0       0.3           0.5              0.7cluster 1:    1       1.2           3.1              1.2cluster 1:    2       0.8           0.1              1.3cluster 2:    3       0.2           0.3              1.0cluster 2:    4       3.1           2.1              5cluster 3:    5       0.9           0.7              0.2我不想顯示索引(0,1,2,3,4,5),而是想顯示多行的簇號。我怎樣才能做到這一點?
查看完整描述

1 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

您可以循環瀏覽標簽并將它們放置在平均值處。小 y 刻度線可以用作分隔符。


以下代碼假設第一列具有集群標簽(并且不會用于熱圖本身)。


import pandas as pd

import seaborn as sns

from io import StringIO

import matplotlib.pyplot as plt

from matplotlib.ticker import FixedLocator


data_str = '''    cluster                "Location 1"    "Location 2"      "Location 3"

"cluster 1"         0.3           0.5              0.7

"cluster 1"         1.2           3.1              1.2

"cluster 1"         0.8           0.1              1.3

"cluster 2"         0.2           0.3              1.0

"cluster 2"         3.1           2.1              5

"cluster 3"         0.9           0.7              0.2'''


df = pd.read_csv(StringIO(data_str), delim_whitespace=True)

ax = sns.heatmap(df[df.columns[1:]], cmap='rocket_r', annot=True)


ax.xaxis.tick_top()

ticks = []

labels = []

prev_label = None

for i, label in enumerate(df['cluster']):

    if label != prev_label:

        ticks.append(i)

        labels.append(label)

        prev_label = label

ticks.append(i + 1)

ax.yaxis.set_minor_locator(FixedLocator(ticks))

ax.yaxis.set_major_locator(FixedLocator([(t0 + t1) / 2 for t0, t1 in zip(ticks[:-1], ticks[1:])]))

ax.set_yticklabels(labels, rotation=0)

ax.tick_params(axis='both', which='major', length=0)

ax.tick_params(axis='y', which='minor', length=60)

plt.tight_layout()

plt.show()

https://img1.sycdn.imooc.com//64e41d700001e1db06090386.jpg

查看完整回答
反對 回復 2023-08-22
  • 1 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號