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

问题描述:

使用带有共享x轴的Seaborn绘制热图和线图,热图的刻度位于热图栏的中间.

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.

因此,底部的线图将继承热图刻度的位置和标签,因为线图的刻度应从零开始,所以不会反映真实的数据.

Consequently, the bottom lineplot will inherit heatmap ticks position and labels, not reflecting the true data as the lineplot ticks should start from zero.

换句话说,我需要移动两个图的刻度以从x轴原点开始(最佳),或者将线图向右偏移一个热图单元宽度的一半,同时保持刻度位置和标签(hacky).

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).

下面的代码可以快速重现该问题:

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)

这是一个很棘手的解决方案,但是您可以将x轴向左移动一半的宽度:

This is a hacky solution, but you can shift the x-axes left by half of the width:

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()