使用热图将线图与双轴图上的xticks对齐 [英] Align line graph to xticks on dual axis plot with heatmap

查看:55
本文介绍了使用热图将线图与双轴图上的xticks对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在双轴图上绘制折线图和热图.这就是我得到的:

I'm trying to plot a line graph and a heatmap on a dual axis plot. This is what I'm getting:

如您所见,由于存在将xticks居中的热图,因此折线图未与xticks对齐.如何将线图向右移动0.5,以使线图上的数据点正确对应于xticks?

As you can see, the line graph isn't aligned to the xticks due to the presence of the heatmap, which centers the xticks. How can I shift the line graph to the right by 0.5 so that the data points on the line graph correctly correspond to the xticks?

下面是我的代码:

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

data1 = np.random.random((10, 10))
data2 = np.random.random((10))

f, ax = plt.subplots(figsize=(11, 9))
plt.tick_params(bottom='on')
ax = sns.heatmap(data1, cmap=sns.color_palette("Greens", 5))
ax2 = plt.twinx()
sns.lineplot(data=data2, linewidth=5, ax=ax2)
ax.axis('tight')

plt.show()

推荐答案

以下是一种方法.

说明:双轴实例 ax2 仅使用 sns.lineplot 绘制了一条线.您首先提取该 line 对象.然后,您可以根据需要将该行的x数据更新(移位)到右边 0.5 .line.get_xdata() 返回一个 x 值数组,您只需以矢量化方式添加 0.5,然后使用 line.set_xdata.在 sns.lineplot() 命令之后添加以下几行.

Explanation: The twin axis instance ax2 has only one line plotted using sns.lineplot. You extract that line object first. Then you just update (shift) the x-data of that line to the right by 0.5 as you wanted. The line.get_xdata() returns you an array of x-values and you simply add 0.5 in a vectorized manner followed by applying the changes using line.set_xdata. Add the following lines after your sns.lineplot() command.

line = ax2.lines[0] # get the line
line.set_xdata(line.get_xdata() + 0.5)

这篇关于使用热图将线图与双轴图上的xticks对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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