简体   繁体   English

使用 Seaborn 和 Matplotlib 对齐热图和线图的共享子图中的 x 轴刻度

[英]Align x-axis ticks in shared subplots of heatmap and line plots using Seaborn and Matplotlib

Plotting a heatmap and a lineplot using Seaborn with shared x-axis, the ticks of the heatmap are placed in the middle of the heatmap bars.使用共享 x 轴的 Seaborn 绘制热图和线图,热图的刻度位于热图条的中间。

Consequently, the bottom lineplot will inherit heatmap ticks position and labels, not reflecting the true data as the lineplot ticks should start from zero.因此,底部线图将继承热图刻度 position 和标签,不反映真实数据,因为线图刻度应从零开始。

In other words, I need to either shift the ticks of both plots to start from the x-axis origin (optimal), or shift the lineplot toward the right by a half of a heatmap cell width, keeping the tick locations and labels (hacky).换句话说,我需要将两个图的刻度移动到从 x 轴原点开始(最佳),或者将线图向右移动热图单元宽度的一半,保持刻度位置和标签(hacky )。

The code below quickly reproduce the issue:下面的代码快速重现了这个问题:

f,[ax_heat,ax_line]=plt.subplots(nrows=2,figsize=(10, 8),sharex=True)

data_heat = np.random.rand(4, 6)
data_line= np.random.randn(6,1)

sb.heatmap(data=data_heat,robust=True, center=0,cbar=False, ax=ax_heat)
sb.lineplot(data=data_line, ax=ax_line)

热图和线图的子图,线图刻度移动

This is a hacky solution, but you can shift the x-axes left by half of the width:这是一个 hacky 解决方案,但您可以将 x 轴向左移动宽度的一半:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb

f,[ax_heat,ax_line]=plt.subplots(nrows=2,figsize=(10, 8),sharex=True)

data_heat = np.random.rand(4, 6)
data_line = np.random.randn(6,1)

# generalizable code regardless of spacing:
ax = sb.heatmap(data=data_heat,robust=True, center=0,cbar=False, ax=ax_heat)
width = ax.get_xticks()[1] - ax.get_xticks()[0]
new_ax = ax.get_xticks() - 0.5*width
ax.set_xticks(new_ax)
sb.lineplot(data=data_line, ax=ax_line)
plt.show()

在此处输入图像描述

To shift the ticks of both plots to start from the x-axis origin, just add this line at the end of your code:要将两个图的刻度从 x 轴原点开始,只需在代码末尾添加以下行:

plt.xticks(plt.xticks()[0] - 0.5)

Explanation:解释:

plt.xticks() returns the x-tick locations and labels, so we can access the locations by indexing with [0] . plt.xticks()返回 x-tick 位置和标签,因此我们可以通过使用[0]索引来访问这些位置。 It turns out this is just a list of consecutive integer values, so we can shift them half a level to the left by subtracting 0.5.原来这只是一个连续的 integer 值的列表,所以我们可以通过减去 0.5 将它们向左移动半个级别。

(partly copied from my answer to another question ) (部分复制自我对另一个问题的回答)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM