Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a shared axis plot to an AxesGrid plot in matplotlib

I would like to create a 2x3 plot of 2d histograms in matplotlib with a shared colorbar and a 1d histogram at the top of each subplot. AxesGrid got me everything except for the last part . I tried to add a 2d histogram to the top of each subplot by following the "scatter_hist.py" example on the above page using make_axes_locatable. The code looks something like this:

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}$)')

This gives an error at the divider.append_axes() function call:

AttributeError: 'LocatablePolyCollection' object has no attribute '_adjustable'

Does anyone know if it's possible to easily add the histograms to the top with the axesgrid approach, or do I need to use a different approach? Thanks!

like image 673
Rory Avatar asked Nov 14 '22 20:11

Rory


1 Answers

You should give an instance of AxesSubplot (which has an _adjustable attribute) to the sharex keyword in your call of divider.append_axes. Instead of this you are giving the return value of hexbin to this keyword argument, which is an instance of a LocatablePolyCollection.

So your code should work if you replace sharex=plots[i] with sharex=grid[i] in your call of divider.append_axes.

like image 97
bmu Avatar answered Dec 18 '22 09:12

bmu