【问题标题】:python matplotlib 2.x axis autolimitpython matplotlib 2.x 轴自动限制
【发布时间】:2017-11-06 00:38:26
【问题描述】:

在选择轴上的自动限制时,我遇到了 matplotlib 2.x 代码无法重现 1.x 行为的问题。根据 https://matplotlib.org/users/dflt_style_changes.html ,版本 1.x 轴舍入应通过使用以下命令进行复制:

mpl.rcParams['axes.autolimit_mode'] = 'round_numbers'
mpl.rcParams['axes.xmargin'] = 0
mpl.rcParams['axes.ymargin'] = 0

但事实并非如此。请参阅下面的代码。我的 y 值范围从略高于 5 到略低于 50。当我运行代码时:

  • 对于经典(1.x 版)行为 (sys.argv[1]=="1"),y 轴刻度为 5 和 50。
  • 对于版本 2.x 行为 (sys.argv[1]=="2"),y 轴刻度为 0 和 60。

2.x 版的舍入似乎更粗糙。如何重现版本 1.x 舍入?

import sys
import matplotlib.pyplot as plt
import matplotlib as mpl

if sys.argv[1]=="1":
    import matplotlib.style
    matplotlib.style.use('classic')
elif sys.argv[1]=="2":
    mpl.rcParams['axes.autolimit_mode'] = 'round_numbers'
    mpl.rcParams['axes.xmargin'] = 0
    mpl.rcParams['axes.ymargin'] = 0
else:
    raise Exception("param must be 1 or 2")

z = [49.0, 14.5, 6.0, 5.8]
steps = len(z)

plt.clf()
plt.figure(figsize=(8,6)) # Matplotlib 1.x default
plt.subplot(311)
plt.plot(range(steps), z)

plt.xlim(xmin=0, xmax=steps-1)
plt.xticks(range(steps))
ymin, ymax = plt.ylim()
plt.yticks([ymin, ymax])

plt.savefig("mpltest%s.pdf" % sys.argv[1])

【问题讨论】:

  • python 2.7.14,matplotlib 2.1.0
  • 我无法在 Python 2.7.2、matplotlib 2.1.0 上重现此行为

标签: python matplotlib axis-labels


【解决方案1】:

首先,注意坐标轴上的刻度数在经典模式和适配的 rcParams 之间是不同的。

import matplotlib.pyplot as plt

mode = "classic" #"classic" #"modern"
if mode == "classic":
    plt.style.use('classic')
else:
    plt.rcParams['axes.autolimit_mode'] = 'round_numbers'
    plt.rcParams['axes.xmargin'] = 0
    plt.rcParams['axes.ymargin'] = 0

z = [49.0, 14.5, 6.0, 5.8]

plt.figure(figsize=(3,6))
plt.subplot(311)
plt.title("{} mode".format(mode))
plt.plot(range(len(z)), z)

由于刻度数不同,下一个“轮数”也不同。在经典模式下是550,在“现代”模式下是060

changes to the defaults guide 状态在“滴答数”部分:

定位器现在包含一种算法,用于估计为刻度标签留出空间的最大刻度数。 [...] 除了使用mpl.style.use('classic') 之外,没有其他方法可以将以前的行为恢复为默认值。 [...]MaxNLocator 使用的算法已得到改进,这可能会改变刻度位置的选择在某些情况下。这也会影响AutoLocator,它在内部使用MaxNLocator

在这里,您恰好遇到了“在某些情况下”其中之一。

【讨论】:

  • 所以除了自己进行四舍五入之外没有其他方法吗?我想这很好,至少现在我知道了。
  • 这取决于此功能对您的重要性。如果您在很多情况下都需要它,那么值得挖掘旧算法并通过子类化定位器来实现它。如果您只需要几次,手动设置限制绝对是可行的方法。
猜你喜欢
  • 2020-07-08
  • 2012-04-22
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 2015-06-10
相关资源
最近更新 更多