我一直在尝试构建一个类似于 an example from the matplotlib gallery 的布局,进行一些修改:
- 中心轴应具有“相等”的纵横比,但具有
xlim != ylim
- 顶部轴将包含一个颜色条,用于显示中心轴中的数据
- 右轴将容纳
twiny()
设置
引用的示例似乎在轴的位置进行了硬编码,当我希望动态完成此操作时,因为中心轴中的 x 和 y 限制可能会发生变化。
我尝试了不同的方法,但我将首先介绍使用 add_sublot()
的方法。
中心轴可以用类似的东西制作(预计使用AxisDivider
来添加顶部轴,即121):
from matplotlib.pyplot import *
fig = gcf()
ax_c = fig.add_subplot(121,aspect='equal',xlim=[0,2],ylim=[0,0.5])
draw()
达到了预期的结果。 (这是我第一次使用 StackExchange,所以我还没有 10 的声誉来发布图像或超过两个链接。)好的。但是当我添加第二个子图时,例如:
ax_r = fig.add_subplot(122,sharey=ax_c,xlim=[0,4])
draw()
纵横比被破坏,最初设置的 x 限制也被破坏。
使用 GridSpec
的结果似乎是相同的,并且有 another implementation of the given example使用 AxesDivider
,但我确定无法在 append_axes()
的帮助下使用 AxesDivider
,因为我还想生成一个右侧的 twiny()
轴,并且考虑到 twiny()
和 AxesGrid
的实现方式,twiny()
轴最终跨越整个图形。
fig.clf()
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
ax_c = fig.add_subplot(111,aspect='equal',xlim=[0,2],ylim=[0,0.5])
divider = make_axes_locatable(ax_c)
ax_r = divider.append_axes("right", size=1.3, pad=0.1, sharey=ax_c)
ax_rty = ax_r.twiny()
draw()
我认为颜色条(跨越中心轴宽度的所需顶轴)可以使用 make_axes_locatable() 方法来实现。我还尝试了 AxesGrid
,它可以很好地处理颜色条,但这种结构不适合不同的轴比例,并且似乎不适用于中心轴和右轴组合。
最佳答案
这是回答我自己的问题的一种有点丑陋的方式,我从 the first example I referenced 破解了以下代码。这绝对是我想与更高级别的助手一起处理的事情,因此欢迎其他更短/更清晰的答案。
import numpy as np
import matplotlib.pyplot as plt
xlim = (-60.,60.)
ylim = (-110.,110.)
axes_pad = 0.02
cbar_height = 0.025
h_pad = 0.1
v_pad = 0.1
fig_w = 7.
fig_h = 6.
height = 1-axes_pad-cbar_height-2*v_pad
width = np.abs((xlim[1]-xlim[0])/(ylim[1]-ylim[0]))*height*fig_h/fig_w # ensure equal aspect
bottom_h = v_pad+height+axes_pad
left_h = h_pad+width+axes_pad
rect_c = [h_pad, v_pad, width, height]
rect_cbar = [h_pad, bottom_h, width, cbar_height]
rect_r = [left_h, v_pad, 1-axes_pad-width-2*h_pad, height]
fig = plt.figure(1, figsize=(fig_w,fig_h))
ax_c = plt.axes(rect_c)
ax_cbar = plt.axes(rect_cbar)
ax_r = plt.axes(rect_r)
ax_c.set_xlim(xlim)
ax_c.set_ylim(ylim)
ax_r.set_ylim(ylim)
ax_rty = ax_r.twiny()
ax_rty.set_xlim((-100,0)) # determined dynamically later
ax_r.set_xlim((0,0.5)) # determined dynamically later
plt.savefig('skeleton.pdf',bbox_inches='tight')
关于python - 网格中的三个子图,一个具有共享 x 轴和 y 轴的等宽子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22076635/