PJ96
PJ96

Reputation: 33

Stacked horizontal plots with multiple Y axis varying in scale

Hi I am trying to create:

  1. horizontally stacked plots
  2. Have secondary axis on both plots
  3. Have different scales on axis - unfortunately, both my Y axis currently have the same scale per subplot... :(

Current code:

#  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:

Current progress

Upvotes: 3

Views: 481

Answers (1)

david
david

Reputation: 1501

You can use .twinx() method on each ax object so you can have two plots on the same ax object sharing x-axis:

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

Upvotes: 1

Related Questions