Paul Harris
Paul Harris

Reputation: 169

Setting position of twin axes not possible

I have this code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
a = np.array([1,2,3])
b = a 
ax1.plot(a,b)
ax2 = ax1.twinx()
ax2.set_position(matplotlib.transforms.Bbox([[0.125, 0.125], [0.9, 0.2]]))
c = np.array([4,5,6])
d = c
ax2.plot(c,d)
plt.show()

When I run this with Python 2, it results in:

My plot using Python 2

The problem is when I try to use the same code using Python 3 I get this picture:

My plot using Python 3

How can I have the same result using Python 3?

Upvotes: 2

Views: 300

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339112

This was a bug, which has now been fixed (so it has nothing to do with the python version, but rather the matplotlib version in use). You could use an inset_axes instead of just a usual subplot. The latter could look like this:

import numpy as np
from matplotlib.transforms import Bbox
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111, label="first")
ax2 = fig.add_subplot(111, label="second")

ax2.set_position(Bbox([[0.125, 0.125], [0.9, 0.2]]))
ax1.get_shared_x_axes().join(ax1, ax2)
ax2.yaxis.tick_right()
ax2.tick_params(bottom=False, labelbottom=False)
ax2.set_facecolor("none")

a = np.array([1,2,3])
ax1.plot(a,a)

c = np.array([4,5,6])
ax2.plot(c,c)

plt.show()

Upvotes: 1

Related Questions