![](/img/trans.png)
[英]Matplotlob set_position() is not working with subplots with constrained_layout
[英]How to get aligments of subplots and subfigures right with constrained_layout in matplotlib?
我在 matplotlib 中有以下子圖和子圖”
Sub figure 1 > ax1
Sub figure 2 > Sub plot 1 > ax2
> Sub plot 2 > ax3
MWE 如下所示。 當前 MWE 的問題在於,對於 y 軸上不同幅度的數字; 如圖綠框所示,ax1、ax2、ax3之間的alignment斷線。
將contstrained_layout
設置為False
我可以正確對齊,但會弄亂間距。 所以我需要將constrained_layout
設置為True
,但需要正確對齊 ax1、ax2、ax3。 我是否缺少任何方法來修復此 alignment?
MWE
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 100, 100)
y = x ** 2
y2 = x ** 10
figure = plt.figure(figsize=(10, 8), constrained_layout=True)
figure.clf()
subfigs = figure.subfigures(2, 1, height_ratios=[1, 1], hspace=0.05, wspace=0.05)
plots = subfigs[0].subplots()
ax1 = plt.gca()
ax1.plot(x, y2)
sub_plot = subfigs[1].subplots(2,1)
ax2 = sub_plot[0]
ax2.plot(x, y)
ax3 = sub_plot[1]
ax3.plot(x, y)
plt.show()
子圖的重點是使子圖獨立。 如果您希望軸脊對齊,則需要將軸保持在同一圖中:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 100, 100)
y = x ** 2
y2 = x ** 10
figure = plt.figure(figsize=(5, 4), constrained_layout=True)
ax1, ax2, ax3 = figure.subplots(3, 1, gridspec_kw={'height_ratios': [2, 1, 1]})
ax1.plot(x, y2)
ax2.plot(x, y)
ax3.plot(x, y)
plt.show()
請注意,您可以使用gridspec_kw參數設置height_ratios和width_ratios 。
更多解釋可以看: https://matplotlib.org/stable/tutorials/intermediate/arranging_axes.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.