5

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!

astromax
  • 6,001
  • 10
  • 36
  • 47

1 Answers1

7

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?

tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • Is there a way to achieve the same result without creating instances of fig and ax? (i.e. - the way my code is shown above) – astromax Oct 16 '13 at 13:36
  • Ah - I figured it out: axes().set_aspect('equal') – astromax Oct 16 '13 at 14:20
  • 1
    @astromax See this answer: http://stackoverflow.com/questions/14254379/how-can-i-attach-a-pyplot-function-to-a-figure-instance/14261698#14261698 You already have created the `fig` and `ax` objects, `plt` is just hiding them from you. – tacaswell Oct 16 '13 at 16:38