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

2024-05-23 18:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在尝试创建:

  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()

目前的进展:

Current progress


Tags: dfclipfigpltstartlabel比例graph
1条回答
网友
1楼 · 发布于 2024-05-23 18:33:45

可以对每个ax对象使用.twinx()方法,以便在同一ax对象上有两个共享x轴的绘图:

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

相关问题 更多 >