简体   繁体   中英

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:

我的情节使用 Python 2

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

我的情节使用 Python 3

How can I have the same result using Python 3?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM