首页 文章

使用python中的matplotlib绘制对数轴

提问于
浏览
277

我想使用matplotlib绘制一个具有一个对数轴的图形 .

我've been reading the docs, but can' t弄清楚了语法 . 我知道它可能在情节参数中像 'scale=linear' 一样简单,但我似乎无法正确对待

示例程序:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)
pylab.show()

6 回答

  • 242

    你只需要使用semilogy而不是plot:

    from pylab import *
    import matplotlib.pyplot  as pyplot
    a = [ pow(10,i) for i in range(10) ]
    fig = pyplot.figure()
    ax = fig.add_subplot(2,1,1)
    
    line, = ax.semilogy(a, color='blue', lw=2)
    show()
    
  • 291

    如果要更改对数的基数,只需添加:

    plt.yscale('log',basey=2) 
    # where basex or basey are the bases of log
    
  • 8

    首先,混合 pylabpyplot 代码并不是很整洁 . 更重要的是,pyplot style is preferred over using pylab .

    这是一个略微清理的代码,仅使用 pyplot 函数:

    from matplotlib import pyplot
    
    a = [ pow(10,i) for i in range(10) ]
    
    pyplot.subplot(2,1,1)
    pyplot.plot(a, color='blue', lw=2)
    pyplot.yscale('log')
    pyplot.show()
    

    相关功能是pyplot.yscale() . 如果使用面向对象的版本,请使用方法Axes.set_yscale()替换它 . 请记住,您还可以使用pyplot.xscale()(或Axes.set_xscale())更改X轴的比例 .

    查看我的问题What is the difference between ‘log’ and ‘symlog’?,查看matplotlib提供的图表比例的几个示例 .

  • 5

    因此,如果您只是使用不复杂的API,就像我经常使用的那样(我在ipython中经常使用它),那么这只是

    yscale('log')
    plot(...)
    

    希望这有助于寻找简单答案的人! :) .

  • 11

    您可以使用Axes.set_yscale方法 . 这允许您在创建 Axes 对象后更改比例 . 这也可以让你构建一个控件,让用户在需要时选择比例 .

    要添加的相关行是:

    ax.set_yscale('log')
    

    您可以使用 'linear' 切换回线性刻度 . 这是您的代码的样子:

    import pylab
    import matplotlib.pyplot as plt
    a = [pow(10, i) for i in range(10)]
    fig = plt.figure()
    ax = fig.add_subplot(2, 1, 1)
    
    line, = ax.plot(a, color='blue', lw=2)
    
    ax.set_yscale('log')
    
    pylab.show()
    
  • 58

    我知道这有点偏离主题,因为有些评论提到 ax.set_yscale('log') 是"nicest"解决方案,我认为可能是应该的反驳 . 我不建议使用 ax.set_yscale('log') 作为直方图和条形图 . 在我的版本(0.99.1.1)中,我遇到了一些渲染问题 - 不确定这个问题有多普遍 . 但是bar和hist都有可选的参数来将y-scale设置为log,这样可以正常工作 .

    参考:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

    http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist

相关问题