python - 如何在热图右侧添加自定义刻度

标签 python matplotlib seaborn heatmap

给定以下示例数据

data =\
{'q1': [6, 4, 4, 4, 6, 6, 6, 4, 6, 6, 6, 6],
 'q2': [3, 3, 3, 4, 3, 3, 4, 3, 4, 3, 4, 1],
 'q3': [6, 3, 4, 4, 4, 4, 6, 6, 6, 6, 4, 1],
 'q4': [3, 6, 6, 6, 6, 6, 4, 4, 6, 4, 6, 4],
 'q5': [4, 3, 3, 3, 3, 6, 6, 4, 4, 6, 3, 4],
 'q6': [3, 3, 4, 4, 6, 3, 3, 1, 6, 4, 4, 4],
 'q7': [4, 3, 3, 3, 3, 6, 4, 1, 4, 1, 4, 1],
 'q8': [4, 4, 1, 6, 4, 6, 4, 1, 6, 1, 4, 1],
 'q9': [4, 6, 4, 3, 4, 3, 4, 6, 6, 4, 3, 4],
 'q10': [3, 4, 1, 3, 4, 3, 3, 6, 6, 3, 4, 4]}

这是我的代码:

import seaborn as sns
import pandas as pd

df = pd.DataFrame(data)

cm = sns.heatmap(df.T, annot=False, cbar=True)

cm.get_figure().savefig('heatmap.pdf')

这是输出:

output

我想做的是在右侧添加自定义 y 轴刻度,如下所示:

desired_output

我该怎么做?我按照建议考虑使用 tick_params here ,但这仅使用左侧相同的 y 刻度。

最佳答案

您可以创建双轴并设置其刻度和标签:

cm = sns.heatmap(df.T, annot=False, cbar=True)

# create the twin axis
ax_twin = cm.twinx()

# Set the limits of the y twin axis as the ones of the original y axis
ax_twin.set_ylim(cm.get_ylim())

# Set the position of the ticks in the twin axis 
# copying the positions of the ticks on the original axis
ax_twin.set_yticks(cm.get_yticks())  

# Set the labels of the just created ticks
ax_twin.set_yticklabels('abcdefghij')

# Save the figure, as before
cm.get_figure().savefig('heatmap.pdf')

这就是你得到的:

enter image description here

关于python - 如何在热图右侧添加自定义刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73919130/

相关文章:

python - Django View 测试

python - Pyramid :使用 `view_config` 注册的 View 未与路由相关联

python - 在 wxpython 中嵌入实时更新的 matplotlib 图

python-3.x - 为seaborn 热图创建自定义cmap

python - 为什么 Seaborn 条形图会降低颜色的饱和度?

python - 在seaborn tsplot中将图例移到图外

python - 如何访问 pandas HDStore (pyTables) 中的索引

python - Matplotlib 无法在 Django 上渲染多个等高线图

python - Matplotlib 获取横条边缘的顶部和底部坐标

python - 在 Pandas 中使用特定的图形处理程序