简体   繁体   English

使用 xarray (pcolormesh) 绘制二维数据,同时保持纵横比

[英]Plot 2D data with xarray (pcolormesh) while keeping aspect ratio

I am trying to plot a 2D data set using xarray (which uses matplotlib.pcolormesh ) while keeping the natural aspect ratio of the data.我正在尝试使用 xarray (使用matplotlib.pcolormesh )绘制二维数据集,同时保持数据的自然纵横比。

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添加plt.gca().set_aspect('equal')确实以我想要的方式缩放绘图,但是, plt.gca().set_aspect('equal')的高度不变,产生

Using the parameters size , aspect , or figsize does not help either.使用参数sizeaspectfigsize也无济于事。 For the above example:对于上面的例子:

data.plot(size=6, aspect=150 / 30. * 6)

(or with the same result data.plot(figsize=(150 / 30. * 6,6)) ) (或具有相同的结果data.plot(figsize=(150 / 30. * 6,6))

which is better but still off (maybe due to the colorbar?).哪个更好但仍然关闭(可能是由于颜色条?)。

Both the size / aspect as well as the figsize arguments affect the size of the figure, not of the axes. size / aspect以及figsize参数都会影响图形的大小,而不是轴的大小。 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).您可以通过提供与您的数据纵横比(在您的情况下为 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.对我来说,如果您选择的图形纵横比比数据纵横比大一点,以给颜色条一些空间,那看起来最好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM