Reputation: 397
I am trying to plot a 2D data set using xarray (which uses matplotlib.pcolormesh) while keeping the natural aspect ratio of the data.
Example:
import xarray as xr
import matplotlib.pyplot as plt
plt.close('all')
data = xr.DataArray(np.random.randn(2, 3), dims=('x', 'y'),coords={'x': [10, 20],'y' : [0,50,100]})
data.plot() # Will produce a square plot
The result is
Adding a plt.gca().set_aspect('equal')
does scale the plot in the way I want, however, the height of the colorbar is unchanged yielding
Using the parameters size
, aspect
, or figsize
does not help either.
For the above example:
data.plot(size=6, aspect=150 / 30. * 6)
(or with the same result data.plot(figsize=(150 / 30. * 6,6))
)
which is better but still off (maybe due to the colorbar?).
Upvotes: 6
Views: 2997
Reputation: 890
Both the size
/aspect
as well as the figsize
arguments affect the size of the figure, not of the axes.
The aspect ratio of the axes is somewhat influenced by those arguments but difficult to control exactly. For instance, as you noted, the colorbar will also take up some space so that the width left for the axes is less.
I would recommend the following:
ax = data.plot(figsize=(18, 2))
# Alternatively
# ax = data.plot(size=2, aspect=9)
ax.axes.set_aspect('equal')
The second line ensures that the axes have the correct aspect ratio (just as in your first attempt). If you do not additionally specify a figure size, the it will be determined from default parameters. The problem is that the default figure size does not fit very well with your actual data aspect ratio. Therefore the axes will have to be very small in order to fit into the default width.
You can solve this by providing a figure size that roughly matches your data aspect ratio (which is in your case 7.5). To me, it looks best if you choose the figure aspect ratio a bit larger than the data aspect ratio to give the colorbar some space.
Upvotes: 6