Python Matplotlib 线图与轮廓/imshow 对齐 [英] Python Matplotlib line plot aligned with contour/imshow

查看:56
本文介绍了Python Matplotlib 线图与轮廓/imshow 对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Python和Matplotlib将一个子图的可视宽度设置为等于另一个子图的宽度?第一张图具有固定的长宽比和imshow的正方形像素.然后我想在其下方放置一个线图,但我无法这样做并且无法将所有内容对齐.

How can I set the visual width of one subplot equal to the width of another subplot using Python and Matplotlib? The first plot has a fixed aspect ratio and square pixels from imshow. I'd then like to put a lineplot below that, but am not able to do so and have everything aligned.

我相当确定该解决方案涉及此转换教程页面上的信息.我已经尝试使用fig.transFigure,ax.transAxes,ax.transData等,但是没有成功.我需要在上面板中找到轴的宽度和高度以及偏移量,然后才能在下面板中设置轴的宽度、高度和偏移量.轴标签和刻度等不应该包含在内或更改对齐方式.

I'm fairly sure the solution involves the information on this Transform Tutorial page. I've tried working with fig.transFigure, ax.transAxes, ax.transData, etc. but have not been successful. I need to find the width and height and offsets of the axes in the upper panel, and then be able to set the width, height, and offsets of the axes in the lower panel. Axis labels and ticks and etc. should not be included or change the alignment.

例如,以下代码

fig = plt.figure(1)
fig.clf()

data = np.random.random((3,3))
xaxis = np.arange(0,3)
yaxis = np.arange(0,3)

ax = fig.add_subplot(211)
ax.imshow(data, interpolation='none')
c = ax.contour(xaxis, yaxis, data, colors='k')

ax2 = fig.add_subplot(212)

推荐答案

在撰写本文时,现有的两个答案很有帮助,但没有提供解决方案.解决方案如下.这里使用的关键是直接访问 spine 位置,而不是在其他答案中.在访问坐标之前,需要 plt.draw()来更新坐标.

The two existing answers at the time of this writing are helpful, but do not provide a solution. A solution follows. The key used here, not in the other answers, is to access the spine locations directly. plt.draw() is required to update the coordinates before accessing them.

import numpy as np
from matplotlib import pyplot as plt
im = np.arange(256).reshape(16,16)

fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(211)

ax.imshow(im)
plt.show()

transAxes = ax.transAxes
invFig = fig.transFigure.inverted()

llx,urx = plt.xlim()
lly,ury = plt.ylim()

llx0, lly0 = transAxes.transform((0,0))
llx1, lly1 = transAxes.transform((1,1))

plt.draw()
spleft = ax.spines['left'].get_verts()
spright = ax.spines['right'].get_verts()
llx0 = spleft[0,0]
llx1 = spright[0,0]

axp = invFig.transform(((lly0,llx0),(lly1,llx1)))
ax2 = fig.add_axes([axp[0,1],axp[0,0]-0.5,axp[1,1]-axp[0,1],axp[1,0]-axp[0,0]])
ax2.plot(np.arange(10))
plt.draw()

这篇关于Python Matplotlib 线图与轮廓/imshow 对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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