Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib Plots Become Non-Square When Adding Colorbar

This is a rather specific request, but I was wondering if anybody had a solution to this particular problem. When a plot includes a colorbar, it seems as though Matplotlib attempts to squeeze both the colorbar and the plot itself into a square bounding box. Is there a way to leave the plot itself exactly the dimensions you want (ideally an aspect ratio of 1) while still having a colorbar? Is there a clever way of doing this so that you don't have to guess and check?

Cramped

Code is below:

plt.figure(figsize=(8,8))
props = dict(boxstyle='round', facecolor='#C0C0C0', alpha=1)
plt.hexbin(p_binned[7],q_binned[7],extent=(0,1,0,1),gridsize=50,cmap='bone')
plt.colorbar()
text_content = "{:1.3f} ".format(bins[7]/r200_MediumMass2)
plt.text(0.05, 0.95, text_content + r"$r/r_{200}$", fontsize=16, verticalalignment='top', bbox=props)
plt.xlabel('p')
plt.ylabel('q',rotation='horizontal')
plt.ylim(0,1)
plt.xlim(0,1)
plt.show()

Thanks!

like image 653
astromax Avatar asked Oct 15 '13 21:10

astromax


1 Answers

You can force the aspect-ratio of the axes to be one via

ax.set_aspect('equal')

and re-size the figure to what ever dimension (in inches) you want

fig.set_size_inches([height, width],forward=True)

You can use

art.get_window_extent()

to get the size of any artist in display units, you can use this to programatically re-size things.

How else should mpl add in the colorbar?

like image 155
tacaswell Avatar answered Nov 02 '22 11:11

tacaswell