Python 如何将twinx与使用make_axes_locatable创建的ax一起使用
我想在下面绘制一幅图像和一个带有相关直方图的色条。图像和直方图的两个轴必须具有相同的宽度。 此外,颜色条的高度应与图像的高度相同。 复杂的部分(也不应该)是将累积直方图的图与每个箱子相对于数据大小的百分比叠加在一起 目前,我得到了如下结果:Python 如何将twinx与使用make_axes_locatable创建的ax一起使用,python,matplotlib,Python,Matplotlib,我想在下面绘制一幅图像和一个带有相关直方图的色条。图像和直方图的两个轴必须具有相同的宽度。 此外,颜色条的高度应与图像的高度相同。 复杂的部分(也不应该)是将累积直方图的图与每个箱子相对于数据大小的百分比叠加在一起 目前,我得到了如下结果: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable data = np.random.nor
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\u grid1
toolkit设计用于在绘制时定位轴。显然,它首先绘制双轴,然后根据分隔器重新定位轴。更糟糕的是,您希望将具有相等纵横比的轴绑定到具有不等纵横比的轴,这使得无法使用
AxisGrid
虽然任何相等+不相等或相等+孪生或不相等+孪生的双重组合都会以这样或那样的方式起作用,但这三种组合都太多了
因此,解决方案可能是从头开始,只需将轴放到画布上,并仅在最末端重新定位/调整它们的大小。这可以通过使用一个连接到函数的事件侦听器来完成,该函数获取具有相同纵横比的轴的位置,并相应地调整其他两个轴的大小
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()