我在 matplotlib 中有以下子圖和子圖”
Sub figure 1 > ax1
Sub figure 2 > Sub plot 1 > ax2
> Sub plot 2 > ax3
下面給出了 MWE。當前 MWE 的問題在于,對于 y 軸上不同大小的數字;ax1、ax2和ax3之間的對齊被破壞,如圖綠色框所示。

設定contstrained_layout為FalseI 可以使對齊正確,但會弄亂間距。所以我需要constrained_layout設定為True,但需要正確對齊 ax1、ax2、ax3。是否有我缺少的任何方法來修復此對齊方式?
移動電源
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()
uj5u.com熱心網友回復:
子圖的要點是使子圖獨立。如果您希望軸脊對齊,則需要將軸保持在同一圖中:
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()
請注意,您可以設定height_ratios和width_ratios使用gridspec_kw說法。

更多解釋可以看:https : //matplotlib.org/stable/tutorials/intermediate/arranging_axes.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383667.html
標籤:Python matplotlib
