在 matplotlib 中使用 2 个不同的 y 轴时如何制作平方图?

How to make a squared plot when using 2 different y-axis in matplotlib?

我想知道当我有 2 个 y 轴时如何使用 matplotlib 绘制平方图。这是一个例子:

    import matplotlib.pyplot as plt
    import seaborn as sns

    gammas = sns.load_dataset("gammas")
    sns.set(context="paper", palette="colorblind", style="ticks")
    fig, ax1 = plot.subplots()
    sns.tsplot(gammas[(gammas["ROI"] == "IPS")].reset_index(), time="timepoint", unit="subject", value="BOLD signal", ci=95, color="#4477AA", legend=False, ax=ax1)
    ax1.set_xlabel("Timepoint")
    ax1.set_ylabel("BOLD signal (1)")
    ax1.spines["top"].set_visible(False)
    ax1.tick_params(top='off')
    ax2 = ax1.twinx()
    ax2.yaxis.tick_right()
    ax2.yaxis.set_label_position("right")
    sns.tsplot(gammas[(gammas["ROI"] == "AG")].reset_index(), time="timepoint", unit="subject", value="BOLD signal", ci=95, color="#CC6677", legend=False, ax=ax2)
    ax2.set_ylabel("BOLD signal (2)")
    ax2.spines["top"].set_visible(False)
    ax2.tick_params(top='off')
    # Set legend #
    ax2.legend([ax1.get_lines()[0], ax2.get_lines()[0]], ["IPS", "AG"], loc='upper left')
    plt.show()

如您所见,生成的图不是平方的:

到目前为止,我在 plt.show() 命令之前尝试了以下操作:

我使用的数据有 2 个不同的比例:第一个 y 轴范围从 0 到 250,而第二个 y 轴范围从 0 到 100(这就是为什么我考虑将 ax2 中使用的所有值乘以一个因子2.5)。我确定有一些明显的东西我没有看到,所以提前谢谢你。

不完全清楚您是希望坐标轴长度相等,还是希望坐标轴上的缩放比例相等。

为了获得方形纵横比,我创建了一个方形尺寸的图形fig = plt.figure(figsize=(5,5))这足以获得相同长度的轴。

为了在所有轴上获得相同的缩放比例,我添加了 set_scaling() 指令

import matplotlib.pyplot as plt
import seaborn as sns

gammas = sns.load_dataset("gammas")
sns.set(context="paper", palette="colorblind", style="ticks")
fig = plt.figure(figsize=(5,5))
ax1 = fig.add_subplot(111)
sns.tsplot(gammas[(gammas["ROI"] == "IPS")].reset_index(), time="timepoint", unit="subject", value="BOLD signal", ci=95, color="#4477AA", legend=False, ax=ax1)
ax1.set_xlabel("Timepoint")
ax1.set_ylabel("BOLD signal (1)")
ax1.spines["top"].set_visible(False)
ax1.tick_params(top='off')
ax2 = ax1.twinx()
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position("right")
sns.tsplot(gammas[(gammas["ROI"] == "AG")].reset_index(), time="timepoint", unit="subject", value="BOLD signal", ci=95, color="#CC6677", legend=False, ax=ax2)
ax2.set_ylabel("BOLD signal (2)")
ax2.spines["top"].set_visible(False)
ax2.tick_params(top='off')
# Set legend #
ax2.legend([ax1.get_lines()[0], ax2.get_lines()[0]], ["IPS", "AG"], loc='upper left')
# set the aspect ratio so that the scaling is the same on all the axes
ax1.set_aspect('equal')
ax2.set_aspect('equal')