【问题标题】:Matplotlib log-log plot - only show powers of ten on y axisMatplotlib 对数图 - 仅在 y 轴上显示 10 的幂
【发布时间】:2020-04-03 23:26:40
【问题描述】:

假设我有以下代码:

import matplotlib as mpl
from matplotlib import pyplot as plt
x =[10, 14, 19, 26, 36, 50, 70, 98, 137, 191, 267, 373, 522, 730, 1021, 1429, 2000, 2800, 3919, 5486, 7680] 
y = [ 0.0085,  0.006900000000000001,  0.007600000000000001,  0.007600000000000001,  0.01,  0.008700000000000003,  0.0094,  0.008800000000000002,  0.0092,  0.009,  0.009999999999999998,  0.010099999999999998,  0.010899999999999998,  0.010899999999999998, 0.011,  0.0115,   0.0115,  0.0118,  0.013000000000000001,  0.0129, 0.0131]
fig, ax1 = plt.subplots() 
ax1.plot(x,y,linewidth=1) 
ax1.set_xscale('log') 
ax1.set_yscale('log') 
plt.show()

结果如下:

我想要做的是删除 y 轴上 不是 10 次方的刻度。在这个特定示例中,删除 9x10^-3、8x10^-3 等,并且只保留 10^-2。

我尝试了其他一些建议,例如this one 但他们都没有工作.. 有什么想法吗?

【问题讨论】:

    标签: python python-3.x matplotlib plot


    【解决方案1】:

    您可以在最小和最大 y 值之间找到 10 的所有幂,然后直接使用 ax1.set_yticks( y_ticks) 设置刻度。

    import matplotlib as mpl
    from matplotlib import pyplot as plt
    import math 
    
    x =[10, 14, 19, 26, 36, 50, 70, 98, 137, 191, 267, 373, 522, 730, 1021, 1429, 2000, 2800, 3919, 5486, 7680] 
    y = [ 0.0085,  0.006900000000000001,  0.007600000000000001,  0.007600000000000001,  0.01,  0.008700000000000003,  0.0094,  0.008800000000000002,  0.0092,  0.009,  0.009999999999999998,  0.010099999999999998,  0.010899999999999998,  0.010899999999999998, 0.011,  0.0115,   0.0115,  0.0118,  0.013000000000000001,  0.0129, 0.0131]
    fig, ax1 = plt.subplots() 
    ax1.plot(x,y,linewidth=1) 
    ax1.set_xscale('log') 
    ax1.set_yscale('log')
    
    ymin_pow = math.floor(math.log10(min(y)))
    ymax_pow = math.ceil(math.log10(max(y)))
    
    y_ticks = [10**i for i in range(ymin_pow, ymax_pow + 1)]
    
    # optional: bound the limits 
    if y_ticks[0] < min(y):
        y_ticks = y_ticks[1:]
    if y_ticks[-1] > max(y):
        y_ticks = y_ticks[-1:]
    
    ax1.set_yticks(y_ticks, [str(i) for i in y_ticks])
    
    # un-comment out the following line to have your labels 
    # not in scientific notation
    # ax1.get_yaxis().set_major_formatter(mpl.ticker.ScalarFormatter())
    
    plt.show()
    

    【讨论】:

    • 好的,但是你能告诉我怎么做吗?您可能是指 yticks?
    • 是的,对不起,我的意思是 yticks。答案更新了更多代码。
    • 所以结果恰恰相反。有什么想法吗? i.imgur.com/xQ9vFF1.png
    • 发现bug,应该是math.floor(math.log(min(y),10))(默认为base e)。然而现在的问题是,在这个特定的例子中,它也使 10^-3 出现,这改变了情节。
    • 很好——编辑为使用math.log10。如果出现的 10^(-3) 是一个问题,您可以将轴绑定到最小值和最大值——答案在上面编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多