多个Y轴比例尺变化的水平堆叠图

3

嗨,我正在尝试创建:

  1. 水平堆叠的图表
  2. 两个图表都有辅助轴
  3. 在不同的轴上具有不同的刻度 - 不幸的是,目前每个子图中我的 Y 轴都具有相同的刻度... :(

当前代码:

#  Create axes
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle("XYZ")
fig.set_figheight(5)
fig.set_figwidth(15)
# First graph
ax1.scatter(
    df_PTA_clip_pstar["start_time"],
    df_PTA_clip_pstar["pstar"],
    s=5,
    c="black",
    label="P*",
)
plt.ylabel("P*")
ax1.scatter(df_PTA_clipkh["start_time"], df_PTA_clipkh["kh"], s=2, c="cyan", label="Kh")
ax1.secondary_yaxis("right")
plt.ylabel("Kh")

# Second graph - will add the correct data to this once first graph fixed
ax2.scatter(x, y, s=5, c="Red", label="P*")
ax2.scatter(x, z, s=5, c="Green", label="Kh")

ax2.secondary_yaxis("right")
plt.tight_layout()
plt.legend()
plt.show()

当前进展:

当前进展


1
可以使用 twinx() 方法在一个坐标系对象上显示具有不同刻度的图形,参考Plots with different scales - david
使用这个方法来绘制两个水平堆叠的图表时,由于已经“使用”了定义的两个轴,因此无法绘制第二个图表。 - PJ96
1个回答

1
你可以在每个ax对象上使用.twinx()方法,这样你就可以在同一个共享x轴的ax对象上绘制两个图形:
import matplotlib.pyplot as plt
import numpy as np


#  Create axes
fig, (ax1, ax2) = plt.subplots(1, 2)

## First subplot
x = np.random.random_sample(100)
y = np.random.random_sample(100)

ax1.set_xlim(0, 2)
ax1.scatter(x, y,
            s=5,
            c="black")

ax11 = ax1.twinx()
x = 1 + x
y = 1 + np.random.random_sample(100)
ax11.scatter(x, y,
             s=5,
             c="red")

## Second subplot
x = 2 * np.random.random_sample(100) - 1
y = np.random.random_sample(100)

ax2.set_xlim(-1, 2)
ax2.scatter(x, y,
            s=5,
            c="blue")

ax21 = ax2.twinx()
x = 1 + x
y = 10 + np.random.random_sample(100)
ax21.scatter(x, y,
             s=5,
             c="orange")

plt.show()

enter image description here


1
这很棒,@david。出于格式原因,我进行了一些小的编辑,例如对齐网格:ax1.set_yticks(np.linspace(ax1.get_ybound()[0], ax1.get_ybound()[1], 6)) ax11.set_yticks(np.linspace(ax11.get_ybound()[0], ax11.get_ybound()[1], 6)) ax2.set_yticks(np.linspace(ax1.get_ybound()[0], ax1.get_ybound()[1], 6)) ax21.set_yticks(np.linspace(ax11.get_ybound()[0], ax11.get_ybound()[1], 6)) - PJ96

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接