gpt4 book ai didi

python - 如何将 twinx 与使用 make_axes_locatable 创建的斧头一起使用

转载 作者:行者123 更新时间:2023-11-28 22:30:45 25 4
gpt4 key购买 nike

我想在下面绘制一个图像和颜色条及其相关的直方图。图像和直方图的两个轴必须具有相同的宽度。此外,颜色条应与图像高度相同。复杂(并且不应该)的部分是将累积直方图的图与每个 bin 相对于数据大小的百分比叠加。

目前,我得到了这样的东西:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable


data = np.random.normal(0,2,size=(100,100))

fig = plt.figure()
ax = fig.add_subplot(2,1,1)
im = ax.imshow(data,cmap="bone")
divider = make_axes_locatable(ax)
ax1 = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im,cax=ax1)
ax2 = divider.append_axes("bottom",size="100%",pad = 0.3)
n,bins,patches = ax2.hist(data.flatten(),bins=20)
ax3 = ax2.twinx()
ax3.plot(bins[:-1],np.cumsum(n*100/np.size(data)),lw=2)

plt.show()

一切都很顺利,直到我尝试在 ax2 上使用 twinx(以便用不同的 y 尺度在 ax3 上绘制我的累积分布)。生成的轴不是使用 ax2,而是环绕图形的所有轴。

我不明白哪里出了问题,也不知道该如何解决。

最佳答案

这是一个艰难的过程。问题是 axes_grid1 工具包设计用于在绘图时定位轴。显然它首先绘制双轴,然后才根据分隔线重新定位轴。
更糟糕的是,您希望将纵横比相等的轴绑定(bind)到纵横比不相等的轴,这使得无法使用 AxisGrid

虽然相等+不相等或相等+孪生或不相等+孪生的任何双重组合都可以以一种或另一种方式起作用,但这三种方式都太多了。

所以解决方案可能是从头开始,只需将轴放在 Canvas 上,然后只在最后重新定位/调整它们的大小。这可以使用连接到函数的事件监听器来完成,该函数获取具有相等纵横比的轴的位置并相应地调整其他两个轴的大小。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

data = np.random.normal(0,2,size=(100,100))

fig = plt.figure()
ax = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

im = ax.imshow(data,cmap="bone")
n,bins,patches = ax2.hist(data.flatten(),bins=20)

divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)

ax3 = ax2.twinx()
ax3.plot(bins[:-1],np.cumsum(n*100/np.size(data)),lw=2, c=plt.cm.bone(0.4))

def resize(event):
axpos = ax.get_position()
axpos2 = ax2.get_position()
newpos = [axpos.x0, axpos2.y0, axpos.width, axpos2.height]
ax2.set_position(newpos)
ax3.set_position(newpos)

cid = fig.canvas.mpl_connect('draw_event', resize)
cid2 = fig.canvas.mpl_connect('resize_event', resize)

#if you want to save the figure, trigger the event manually
save=False
if save:
fig.canvas.draw()
resize()
plt.savefig(__file__+".png")
plt.show()

enter image description here

关于python - 如何将 twinx 与使用 make_axes_locatable 创建的斧头一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com