在 matplotlib 中共享轴时显示刻度标签
Show tick labels when sharing an axis in matplotlib
我是运行以下函数:
def plot_variance_analysis(indices, stat_frames, legend_labels, shape):
x = np.linspace(1, 5, 500)
fig, axes = plt.subplots(shape[0], shape[1], sharex=True sharey=True)
questions_and_axes = zip(indices, axes.ravel())
frames_and_labels = zip(stat_frames, legend_labels)
for qa in questions_and_axes:
q = qa[0]
ax = qa[1]
for fl in frames_and_labels:
frame = fl[0]
label = fl[1]
ax.plot(x, stats.norm.pdf(x, frame['mean'][q], frame['std'][q]), label=label)
ax.set_xlabel(q)
ax.legend(loc='best')
plt.xticks([1,2,3,4,5])
return fig, axes
这是我用自己的一些示例数据得到的:
我试图保持轴之间的共享状态,但同时在 所有 子图(包括前两个)上显示 x 轴的刻度标签。我在文档中找不到任何方法来关闭它。有什么建议么?还是我应该逐轴设置 x 刻度标签?
我是 运行 matplotlib 1.4.0,如果这很重要的话。
缺失的报价已将其 visible
属性 设置为 False
。 plt.subplot
的文档中指出了这一点。解决这个问题的最简单方法可能是:
for ax in axes.flatten():
for tk in ax.get_yticklabels():
tk.set_visible(True)
for tk in ax.get_xticklabels():
tk.set_visible(True)
这里我遍历了所有轴,你不一定需要这样做,但这样代码更简单。如果你愿意,你也可以在丑陋的一行中使用列表理解来做到这一点:
[([tk.set_visible(True) for tk in ax.get_yticklabels()], [tk.set_visible(True) for tk in ax.get_yticklabels()]) for ax in axes.flatten()]
在 Matplotlib 2.2 及更高版本中,可以使用以下方法重新打开刻度标签:
ax.xaxis.set_tick_params(labelbottom=True)
您可以在此处找到有关 matplotlib 标签的额外信息:
https://matplotlib.org/3.1.3/api/_as_gen/matplotlib.axes.Axes.tick_params.html
在我的例子中,我需要打开所有的 x 和 y 标签,这个解决方案有效:
for ax in axes.flatten():
ax.xaxis.set_tick_params(labelbottom=True)
ax.yaxis.set_tick_params(labelleft=True)
我是运行以下函数:
def plot_variance_analysis(indices, stat_frames, legend_labels, shape):
x = np.linspace(1, 5, 500)
fig, axes = plt.subplots(shape[0], shape[1], sharex=True sharey=True)
questions_and_axes = zip(indices, axes.ravel())
frames_and_labels = zip(stat_frames, legend_labels)
for qa in questions_and_axes:
q = qa[0]
ax = qa[1]
for fl in frames_and_labels:
frame = fl[0]
label = fl[1]
ax.plot(x, stats.norm.pdf(x, frame['mean'][q], frame['std'][q]), label=label)
ax.set_xlabel(q)
ax.legend(loc='best')
plt.xticks([1,2,3,4,5])
return fig, axes
这是我用自己的一些示例数据得到的:
我试图保持轴之间的共享状态,但同时在 所有 子图(包括前两个)上显示 x 轴的刻度标签。我在文档中找不到任何方法来关闭它。有什么建议么?还是我应该逐轴设置 x 刻度标签?
我是 运行 matplotlib 1.4.0,如果这很重要的话。
缺失的报价已将其 visible
属性 设置为 False
。 plt.subplot
的文档中指出了这一点。解决这个问题的最简单方法可能是:
for ax in axes.flatten():
for tk in ax.get_yticklabels():
tk.set_visible(True)
for tk in ax.get_xticklabels():
tk.set_visible(True)
这里我遍历了所有轴,你不一定需要这样做,但这样代码更简单。如果你愿意,你也可以在丑陋的一行中使用列表理解来做到这一点:
[([tk.set_visible(True) for tk in ax.get_yticklabels()], [tk.set_visible(True) for tk in ax.get_yticklabels()]) for ax in axes.flatten()]
在 Matplotlib 2.2 及更高版本中,可以使用以下方法重新打开刻度标签:
ax.xaxis.set_tick_params(labelbottom=True)
您可以在此处找到有关 matplotlib 标签的额外信息: https://matplotlib.org/3.1.3/api/_as_gen/matplotlib.axes.Axes.tick_params.html
在我的例子中,我需要打开所有的 x 和 y 标签,这个解决方案有效:
for ax in axes.flatten():
ax.xaxis.set_tick_params(labelbottom=True)
ax.yaxis.set_tick_params(labelleft=True)