在matplotlib中向AxesGrid图添加共享轴图
我想在matplotlib中创建一个2x3的二维直方图图表,里面有一个共享的颜色条,并且在每个子图的顶部都有一个一维直方图。使用AxesGrid我几乎实现了所有功能,但最后一部分有点麻烦。我尝试按照上面页面中"scatter_hist.py"示例的方式,使用make_axes_locatable
在每个子图的顶部添加一个二维直方图。代码大概是这样的:
plots = []
hists = []
for i, s in enumerate(sim):
x = np.log10(s.g['temp']) #just accessing my data
y = s.g['vr']
histy = s.g['mdot']
rmin, rmax = min(s.g['r']), max(s.g['r'])
plots.append(grid[i].hexbin(x, y, C = s.g['mass'],
reduce_C_function=np.sum, gridsize=(50, 50),
extent=(xmin, xmax, ymin, ymax),
bins='log', vmin=cbmin, vmax=cbmax))
grid[i].text(0.95 * xmax, 0.95 * ymax,
'%2d-%2d kpc' % (round(rmin), round(rmax)),
verticalalignment='top',
horizontalalignment='right')
divider = make_axes_locatable(grid[i])
hists.append(divider.append_axes("top", 1.2, pad=0.1, sharex=plots[i]))
plt.setp(hists[i].get_xticklabels(), visible=False)
hists[i].set_xlim(xmin, xmax)
hists[i].hist(x, bins=50, weights=histy, log=True)
#add color bar
cb = grid.cbar_axes[0].colorbar(plots[i])
cb.set_label_text(r'Mass ($M_{\odot}$)')
但是在调用divider.append_axes()这个函数时出现了错误:
AttributeError: 'LocatablePolyCollection' object has no attribute '_adjustable'
有没有人知道用axesgrid的方法是否可以轻松地在顶部添加直方图,还是说我需要换个方法?谢谢!
1 个回答
1
你需要在调用 divider.append_axes
时,把一个 AxesSubplot
的实例(这个实例有一个 _adjustable
属性)传给 sharex
这个参数。现在你传给这个参数的是 hexbin
的返回值,而这个返回值是一个 LocatablePolyCollection
的实例。
所以,如果你在调用 divider.append_axes
时,把 sharex=plots[i]
替换成 sharex=grid[i]
,你的代码就应该能正常工作了。