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

Viewed 1759

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.

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)

subplots of heatmap and liineplot with lineplot ticks shifted

2 Answers

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

enter image description here

To shift the ticks of both plots to start from the x-axis origin, just add this line at the end of your code:

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

(partly copied from my answer to another question)

Related