【问题标题】:ticks format of an axis in matplotlibmatplotlib中轴的刻度格式
【发布时间】:2017-08-13 06:18:33
【问题描述】:

我正在尝试使用 matplotlib 绘制干净的图形。 这是我的代码:

fig = plt.figure(figsize = (6,6))
plt.grid(True)
plt.xlabel('time (s)',fontweight='bold')
plt.ylabel('density',fontweight='bold')
plt.plot(data1, data2, color = 'y', linewidth = 2)
plt.show()

data2 中的浮点数介于 0.0001 和 0.001 之间,所以当我这样做时,y 轴会出现 '0.0001' '0.0002' 等刻度。 如何强制刻度为科学记数法('1e-3'、'1e-4' 等)? 谢谢 :)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这样设置就像1e-04:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as mtick
    
    data1 = [1,2,3,4,5]
    data2 = [1e4,3e4,4e4,2e4,5e4]
    fig = plt.figure(figsize = (6,6))
    plt.grid(True)
    plt.xlabel('time (s)',fontweight='bold')
    plt.ylabel('density',fontweight='bold')
    plt.plot(data1, data2, color = 'y', linewidth = 2)
    plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e')) 
    plt.show()
    

    【讨论】:

    • 经历了这个问题的大约 8 个无用版本,直到你的答案中至关重要的 plt.gca() 部分发生。这是一个比我见过的其他解决方案更优雅的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    相关资源
    最近更新 更多