matplotlib - 如何使用 MaxNLocator 并指定必须位于轴中的数字?

问题描述 投票:0回答:1

我确实对 python 中的 matplotlib 有疑问。我创建了不同的图形,其中每个图形都应具有相同的高度,以便将它们并排打印在出版物/海报中。

如果 y 轴的最顶部有标签,则会缩小绘图框的高度。所以我使用 MaxNLocator 删除上下 y 刻度。在某些图中,我希望将 1.0 作为 y 轴上的数字,因为我已经标准化了数据。所以我需要一个解决方案,在这些情况下扩展 y 轴并确保 1.0 是 y-Tick,但不会使用ight_layout() 破坏图形的大小。

这是一个最小的例子:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

x = np.linspace(0,1,num=11)
y = np.linspace(1,.42,num=11)

fig,axs = plt.subplots(1,1)
axs.plot(x,y)

locator=MaxNLocator(prune='both',nbins=5)
axs.yaxis.set_major_locator(locator)

plt.tight_layout()

fig.show()

这里是示例 pdf 的链接,它显示了上框线高度的问题。

我尝试使用 adjustment_subplots() 但这对我来说没有用,因为我改变图形的大小并希望始终保持相同的字体大小,这会改变边距。

问题是:

如何使用 MaxNLocator 并指定 y 轴上的数字?

希望大家能给点建议。

您好, 莱南

python matplotlib label axis
1个回答
6
投票

假设您事先知道一页上的 1 行中有多少个绘图,解决此问题的一种方法是将所有这些绘图放入一个图中 -

matplotlib
将确保它们在轴上对齐:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

x = np.linspace(0, 1, num=11)
y = np.linspace(1, .42, num=11)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,3), gridspec_kw={'wspace':.2})
ax1.plot(x,y)
ax2.plot(x,y)

locator=MaxNLocator(prune='both', nbins=5)
ax1.yaxis.set_major_locator(locator)

# You don't need to use tight_layout and using it might give an error
# plt.tight_layout()  

fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.