【问题标题】:How do I make this LogLog plot?如何制作这个 LogLog 图?
【发布时间】:2020-11-18 09:22:52
【问题描述】:

我是 python 新手,我正在尝试创建一个 LogLogPlot,类似于下图中的那个:

如上图所示,此图基于等式 y=x^2/(e^x +1)。

我找到了 https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.loglog.html ,但这对我来说没有多大意义。

我还尝试了链接中显示的代码:pyplot: loglog() with base e 并将我的表达式更改为“y”,但轴以指数形式编写,我的目标是让轴以实数形式编写,如图所示。代码如下:

# Generate some data.
x = np.linspace(0, 10, 10)
y = x**2/(np.exp(x)+1)

plt.loglog(x,y, basex=np.e, basey=np.e)
plt.show()

但这并没有给我与上面相同的情节。

【问题讨论】:

    标签: python matplotlib plot loglog


    【解决方案1】:

    您当前的 x 轴只有 10 个值,在 0 到 10 之间的线性空间中等距分布。您需要更多值,并且在对数空间中等距分布。例如,np.logspace(-3, 1, 100) 在 10-3 和 101 之间创建 100 个 x 值。

    如果您更改plt.loglog(x, y, basex=np.e, basey=np.e) 中的基数,轴将显示为带有e 幂的刻度。如果您不更改底数,则默认使用熟悉的 10 次幂。请注意,更改底数不会更改转换,只会更改刻度的位置。

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.logspace(-3, 1, 100)
    y = x ** 2 / (np.exp(x) + 1)
    
    plt.loglog(x, y)
    plt.autoscale(enable=True, axis='x', tight=True) # optionally set a tight x-axis
    plt.show()
    

    PS:为了避免科学记数法,this post 建议:

    import matplotlib.ticker as ticker
    plt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, _: f'{y:g}'))
    plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda y, _: f'{y:g}'))
    

    或者,对于更多小数也强制使用十进制表示法:

    plt.gca().yaxis.set_major_formatter(
        ticker.FuncFormatter(lambda y, _: ('{{:.{:1d}f}}'.format(int(np.maximum(-np.log10(y),0)))).format(y)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 2017-11-11
      相关资源
      最近更新 更多