使用Seaborn和Matplotlib在热图和折线图的共享子图中对齐x轴刻度 [英] Align x-axis ticks in shared subplots of heatmap and line plots using Seaborn and Matplotlib

查看:133
本文介绍了使用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()

这篇关于使用Seaborn和Matplotlib在热图和折线图的共享子图中对齐x轴刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆