Python - 设置任意轮廓 xy 比

Python - setting arbitrary contour xy-ratio

我正在阅读以下讨论:

根据上面的讨论,要获得任意比率,我们可以使用

plt.figure(figsize=(8,2))
# ...
plt.tight_layout()   

但是,此设置适用于 figure,不适用于 contourf

我在代码中使用了以上代码

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import pandas as pd
import math

rm = pd.read_excel("test_3d.xlsx", header = None)

# find min values of noise
rec = np.shape(rm)

# grid
X = np.arange(1,rec[1]+1,1)
Y = np.arange(1,rec[0]+1,1)
x , y = np.meshgrid(X,Y)

# plots
plt.clf() 
con = plt.contourf(x,y,rm, cmap=cm.jet)
plt.figure(figsize=(8,2))
plt.tight_layout()
plt.title('2457MHz')
plt.show()

我得到的结果是

底图比例是我想要的;但是,我使用 plt.figure(figsize=(8,2)),它不适用于 contourf。因此,我没有得到正确的结果。

有什么方法可以为 contourf 绘制任意比率?

不是设置figsize,而是使用Axes.set_aspect来改变等值线图的纵横比Axes:

fig, ax = plt.subplots()
ax.contourf(x, y, rm, cmap='viridis')
ax.set_aspect(0.25)

如果您更喜欢使用 plt 语法,请使用 plt.gca:

访问 Axes
plt.contourf(x, y, rm, cmap='viridis')
plt.gca().set_aspect(0.25)