【问题标题】:Stacked horizontal plots with multiple Y axis varying in scale多个 Y 轴比例不同的堆叠水平图
【发布时间】:2020-07-26 21:41:17
【问题描述】:

您好,我正在尝试创建:

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

目前进展:

【问题讨论】:

  • 可能会看到 Plots with different scales 在轴对象上使用 .twinx() 方法。
  • 将其与两个水平堆叠的图一起使用意味着无法绘制第二个图,因为定义的两个斧头已被“使用”

标签: python matplotlib subplot


【解决方案1】:

您可以在每个 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()

【讨论】:

  • 这很棒@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))
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 2013-02-06
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 2020-03-19
  • 1970-01-01
相关资源
最近更新 更多