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

邮差的信 提交于 2021-01-27 17:42:09

问题


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)


回答1:


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




回答2:


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)



来源:https://stackoverflow.com/questions/61050855/align-x-axis-ticks-in-shared-subplots-of-heatmap-and-line-plots-using-seaborn-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!