Elena Greg
Elena Greg

Reputation: 1165

How to use different scales in a subplot

I have a multiple plot of 6 graphs. I would like to use two different scales in the sixth one. How to do that, please? I tried the commented part, but the result was only one plot.

import matplotlib.pyplot as plt

x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]

x_values3=[150,200,250,300,350]
y_values3=[10,20,30,40,50]

fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, figsize=(10,6))

'''
ax6=fig.add_subplot(111, label="1")
ax7=fig.add_subplot(111, label="2", frame_on=False)
ax6.plot(x_values1, y_values1)
ax7.plot(x_values3, y_values3)
'''
plt.show()

Code after advice

import matplotlib.pyplot as plt

x_values1=[1,2,3,4,5]
y_values1=[12,21,42,54,-1]

x_values2=[0.1,0.2,0.3,0.4,0.5]
y_values2=[5000,3000,4000,1000,2000]

x_values3=[150,200,250,300,350]
y_values3=[30,20,50,40,10]

fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, figsize=(10,6))

ax1.plot(x_values1, y_values1)

parax6 = ax6.twinx().twiny()

ax6.plot(x_values2, y_values2, c="r", label="red")
parax6.plot(x_values3, y_values3, c="b", label="blue")
ax6.legend(loc="lower left")
parax6.legend(loc="upper right")

parax6.set_xticks([]) 
parax6.set_yticks([]) 
for side in ['top','right','left','bottom']:
    parax6.spines[side].set_visible(False)

ax6.set_xticks([]) 
ax6.set_yticks([]) 
for side in ['top','right']:
    ax6.spines[side].set_visible(False)


plt.tight_layout()
plt.show()

How to make top and right axis invisible?

Upvotes: 1

Views: 3854

Answers (1)

Mr. T
Mr. T

Reputation: 12410

Although there is some ambiguity in your question, I assume you want to create parasite axes for both the x- and the y-axis on a subplot.

import matplotlib.pyplot as plt

x_values1=[1,2,3,4,5]
y_values1=[12,21,42,54,-1]

x_values2=[0.1,0.2,0.3,0.4,0.5]
y_values2=[5000,3000,4000,1000,2000]

x_values3=[150,200,250,300,350]
y_values3=[30,20,50,40,10]

fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, figsize=(10,6))

ax1.plot(x_values1, y_values1)

parax6 = ax6.twinx().twiny()

ax6.plot(x_values2, y_values2, c="r", label="red")
parax6.plot(x_values3, y_values3, c="b", label="blue")
ax6.legend(loc="lower left")
parax6.legend(loc="upper right")

plt.tight_layout()
plt.show()

Output: enter image description here

If you want to have better control over the axes properties that are chained in this approach, define the axes separately.

...
ax1.plot(x_values1, y_values1)

parax6x = ax6.twinx()
parax6=parax6x.twiny()

ax6.plot(x_values2, y_values2, c="r", label="red")
parax6.plot(x_values3, y_values3, c="b", label="blue")

parax6.set_axis_off()
parax6x.set_axis_off()
...

Output:

enter image description here

Upvotes: 1

Related Questions