【问题标题】:Shared y axis per row每行共享 y 轴
【发布时间】:2018-07-12 16:20:07
【问题描述】:

我有一个关于使用 matplotlib 的子图的每行共享 y 轴的问题。 我以以下脚本为例。当我在 subplots 函数中使用sharey=True 作为参数然后ax[x, x].set_ylim(n, n) 然后它使用我使用的最后一个参数。

import matplotlib.pyplot as plt

fig, ax = plt.subplots(3, 2, figsize=(8, 10), sharey=True, gridspec_kw={'height_ratios': [1, 2, 2]})
ax[0, 0].set_ylim(-1.5, 1.5)
ax[1, 0].set_ylim(-40, 40)
ax[1, 1].set_ylim(-40, 40)
ax[2, 0].set_ylim(-40, 40)
ax[2, 1].set_ylim(-40, 40)

有没有一种方法可以共享每行的 y 轴?

【问题讨论】:

  • 您可以找到一个如何做到这一点的示例here。简短回答:f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row').

标签: python python-3.x matplotlib subplot


【解决方案1】:

您可以通过指定sharey='row' 来做您想做的事情,如matplotlib demo 所示。这里有一点代码来显示这样做的热度:

from matplotlib import pyplot as plt
import numpy as np

x1 = np.linspace(0,2*np.pi,100)
x2 = np.linspace(-1,1,100)


f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey='row')
ax1.plot(x1, np.sin(x1))
ax1.set_title('sin(x)')

ax2.plot(x1, 2*np.cos(x1)+1)
ax2.set_title('2*cos(x)+1')

ax3.plot(x2, np.sqrt(np.abs(x2)))
ax3.set_title('sqrt(abs(x))')

ax4.plot(x2, x2**3)
ax4.set_title('x**3')

f.tight_layout()

plt.show()

这给出了以下结果:

【讨论】:

  • 感谢错过这个例子
猜你喜欢
  • 2016-05-21
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 2021-11-22
相关资源
最近更新 更多