matplotlib - 如何使用 MaxNLocator 并指定一个必须位于轴中的数字?
matplotlib - How can I use MaxNLocator and specify a number which has to be in an axis?
我对 python 中的 matplotlib 有疑问。我创建了不同的图形,其中每个图形都应该具有相同的高度,以便将它们打印在彼此相邻的 publication/poster 中。
如果 y 轴的最顶部有标签,这会缩小带有绘图的框的高度。所以我使用 MaxNLocator 来删除上下 y-tick。在某些图中,我希望 1.0 作为 y 轴上的数字,因为我有标准化数据。所以我需要一个解决方案,在这些情况下扩展 y 轴并确保 1.0 是一个 y-Tick,但不会使用 tight_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()
这是一个 link 示例 pdf,其中显示了上框线高度的问题。
我尝试使用 adjust_subplots() 但这对我没有用,因为我改变了图形的大小并且希望始终具有相同的字体大小,这会改变边距.
问题是:
如何使用 MaxNLocator 并指定必须位于 y 轴上的数字?
希望大家给点建议。
您好,
莱南
假设您事先知道一页的一行中将有多少个图,解决此问题的一种方法是将所有这些图放入一个图中 - 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()
我对 python 中的 matplotlib 有疑问。我创建了不同的图形,其中每个图形都应该具有相同的高度,以便将它们打印在彼此相邻的 publication/poster 中。
如果 y 轴的最顶部有标签,这会缩小带有绘图的框的高度。所以我使用 MaxNLocator 来删除上下 y-tick。在某些图中,我希望 1.0 作为 y 轴上的数字,因为我有标准化数据。所以我需要一个解决方案,在这些情况下扩展 y 轴并确保 1.0 是一个 y-Tick,但不会使用 tight_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()
这是一个 link 示例 pdf,其中显示了上框线高度的问题。
我尝试使用 adjust_subplots() 但这对我没有用,因为我改变了图形的大小并且希望始终具有相同的字体大小,这会改变边距.
问题是:
如何使用 MaxNLocator 并指定必须位于 y 轴上的数字?
希望大家给点建议。
您好, 莱南
假设您事先知道一页的一行中将有多少个图,解决此问题的一种方法是将所有这些图放入一个图中 - 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()