【问题标题】:Arguments for LogLocator in MatPlotLibMatPlotLib 中 LogLocator 的参数
【发布时间】:2018-03-23 13:29:43
【问题描述】:

在 MatPlotLib 中,我想绘制一个带有线性 x 轴和对数 y 轴的图形。对于 x 轴,标签应该是 4 的倍数,小刻度应该是 1 的倍数。我已经能够使用 MultipleLocator 类做到这一点。

但是,我很难为对数 y 轴做类似的事情。我希望在 0.1、0.2、0.3 等处有标签,在 0.11、0.12、0.13 等处有小刻度。我尝试使用 LogLocator 类来执行此操作,但我不确定正确的参数是什么。

这是我到目前为止所尝试的:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
y = [0.32, 0.30, 0.28, 0.26, 0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.10]
fig = plt.figure()
ax1 = fig.add_subplot(111)
x_major = MultipleLocator(4)
x_minor = MultipleLocator(1)
ax1.xaxis.set_major_locator(x_major)
ax1.xaxis.set_minor_locator(x_minor)
ax1.set_yscale("log")
y_major = LogLocator(base=10)
y_minor = LogLocator(base=10)
ax1.yaxis.set_major_locator(y_major)
ax1.yaxis.set_minor_locator(y_minor)
ax1.plot(x, y)
plt.show()

这显示了以下情节:

x 轴是我想要的,但不是 y 轴。 y 轴上 0.1 处有标签,但 0.2 和 0.3 处没有标签。此外,在 0.11、0.12、0.13 等处没有刻度。

我为LogLocator 构造函数尝试了一些不同的值,例如subsnumdecsnumticks,但我无法得到正确的绘图。 https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.LogLocator 的文档并没有很好地解释这些参数。

我应该使用哪些参数值?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    我认为你仍然想要MultipleLocator 而不是LogLocator,因为你想要的刻度位置仍然是“在每个整数上,它是视图间隔中基数的倍数”而不是“ subs[j] * base**i"。例如:

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator
    
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    y = [0.32, 0.30, 0.28, 0.26, 0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.10]
    fig = plt.figure(figsize=(8, 12))
    ax1 = fig.add_subplot(111)
    x_major = MultipleLocator(4)
    x_minor = MultipleLocator(1)
    ax1.xaxis.set_major_locator(x_major)
    ax1.xaxis.set_minor_locator(x_minor)
    ax1.set_yscale("log")
    # You would need to erase default major ticklabels
    ax1.set_yticklabels(['']*len(ax1.get_yticklabels()))
    y_major = MultipleLocator(0.1)
    y_minor = MultipleLocator(0.01)
    ax1.yaxis.set_major_locator(y_major)
    ax1.yaxis.set_minor_locator(y_minor)
    ax1.plot(x, y)
    plt.show()
    

    LogLocator 总是将主要刻度标签放在“每个基数**i”。因此,不可能将它用于您想要的主要刻度标签。您可以将参数subs 用于您的次要刻度标签,如下所示:

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator, LogLocator
    
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    y = [0.32, 0.30, 0.28, 0.26, 0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.10]
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    x_major = MultipleLocator(4)
    x_minor = MultipleLocator(1)
    ax1.xaxis.set_major_locator(x_major)
    ax1.xaxis.set_minor_locator(x_minor)
    ax1.set_yscale("log")
    y_major = LogLocator(base=10)
    y_minor = LogLocator(base=10, subs=[1.1, 1.2, 1.3])
    ax1.yaxis.set_major_locator(y_major)
    ax1.yaxis.set_minor_locator(y_minor)
    ax1.plot(x, y)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 2015-04-29
      • 2014-01-08
      相关资源
      最近更新 更多