簡體   English   中英

Matplotlib:擴展軸以填充圖形,x 和 y 的比例相同

[英]Matplotlib: Expanding axes to fill figure, same scale on x and y

我知道兩件事,但分開。

figure.tight_layout 

將擴展我當前的軸

axes.aspect('equal')

將在 x 和 y 上保持相同的比例。

但是當我同時使用它們時,我會得到方軸視圖,並且我希望它被擴展。 通過保持相同的比例,我的意思是在 x 和 y 軸上從 0 到 1 的距離相同。 有沒有辦法讓它發生? 保持相同的比例並擴展到全圖(不僅是正方形)答案應該與自動縮放一起使用

可能有不那么笨拙的方法,但至少您可以手動完成。 一個非常簡單的例子:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
ax.set_aspect(1)
ax.set_xlim(0, 1.5)

創造

在此處輸入圖片說明

它尊重縱橫比。

如果你想擁有由tight_layout提供的自動縮放,那么你必須自己做一些數學計算:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
fig.tight_layout()

# capture the axis positioning in pixels
bb = fig.transFigure.transform(ax.get_position())
x0, y0 = bb[0]
x1, y1 = bb[1]
width = x1 - x0
height = y1 - y0

# set the aspect ratio 
ax.set_aspect(1)

# calculate the aspect ratio of the plot
plot_aspect = width / height

# get the axis limits in data coordinates
ax0, ax1 = ax.get_xlim()
ay0, ay1 = ax.get_ylim()
awidth = ax1 - ax0
aheight = ay1 - ay0

# calculate the plot aspect
data_aspect = awidth / aheight

# check which one needs to be corrected
if data_aspect < plot_aspect:
    ax.set_xlim(ax0, ax0 + plot_aspect * aheight)
else:
    ax.set_ylim(ay0, ay0 + awidth / plot_aspect)

當然,您可以按您想要的任何方式設置xlimylim ,例如,您可能想要在比例尺的任一端添加等量的空間。

在此處輸入圖片說明

在我的情況下工作的解決方案是調用

axis.aspect("equal")
axis.set_adjustable("datalim")

從文檔中的此示例中竊取。

示例圖像

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM