Matplotlib sharex not working as expected

对着背影说爱祢 提交于 2020-08-10 22:52:13

问题


I'm sure I am missing something obvious, but why is sharex=True, sharey=True not working? I expected the xlims and xticks to be the same for both subplots, and the ylims/yticks to be the same for both subplots. Using Python 3.8.3, matplotlib 3.2.1.

x1, y1 = [(2,7,1), (6,2,2)]
x2, y2 = [(8,3,0), (1,4,9)]

fig, ax = plt.subplots(2,1, sharex=True, sharey=True, figsize=(15, 8));
ax1 = plt.subplot(2,1,1);
ax1.scatter(x1, y1,  c='red', label='Set1');
ax2 = plt.subplot(2,1,2);
ax2.scatter(x2, y2, c='black', label='Set2');


回答1:


ax1 = plt.subplot(2,1,1); creates a different (new) subplot than those already in ax. You want:

fig, ax = plt.subplots(2,1, sharex=True, sharey=True, figsize=(15, 8));
ax1, ax2 = ax

ax1.scatter(x1, y1,  c='red', label='Set1');
ax2.scatter(x2, y2, c='black', label='Set2');

Or simply:

fig, ax = plt.subplots(2,1, sharex=True, sharey=True, figsize=(15, 8));


ax[0].scatter(x1, y1,  c='red', label='Set1');
ax[1].scatter(x2, y2, c='black', label='Set2');

Output:



来源:https://stackoverflow.com/questions/63252213/matplotlib-sharex-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!