【问题标题】:Remove axis scale移除轴刻度
【发布时间】:2015-10-30 16:10:20
【问题描述】:

我花了一些时间来寻找我的问题的答案却徒劳无功,所以我认为应该提出一个新问题。考虑这个情节:

坐标轴标签使用科学记数法。在 y 轴上,一切正常。但是,我尝试过摆脱 Python 在右下角添加的缩放因子,但未能成功。我想完全删除这个因素并简单地用轴标题中的单位表示它,或者让它乘以每个刻度标签。一切都会比这个丑陋的1e14更好看。

代码如下:

import numpy as np data_a = np.loadtxt('exercise_2a.txt')

import matplotlib as mpl 
font = {'family' : 'serif',
        'size'   : 12} 
mpl.rc('font', **font)

import matplotlib.pyplot as plt 
fig = plt.figure() 
subplot = fig.add_subplot(1,1,1)

subplot.plot(data_a[:,0], data_a[:,1], label='$T(t)$', linewidth=2)

subplot.set_yscale('log')               
subplot.set_xlabel("$t[10^{14}s]$",fontsize=14) 
subplot.set_ylabel("$T\,[K]$",fontsize=14) 
plt.xlim(right=max(data_a [:,0])) 
plt.legend(loc='upper right')

plt.savefig('T(t).pdf', bbox_inches='tight')

更新:将 Will 对 scientificNotation 的实现合并到我的脚本中,情节现在看起来像

如果你问我,那就更好了。以下是任何想要采用其中一部分的人的完整代码:

import numpy as np
data = np.loadtxt('file.txt')

import matplotlib as mpl
font = {'family' : 'serif',
        'size'   : 16}
mpl.rc('font', **font)

import matplotlib.pyplot as plt
fig = plt.figure()
subplot = fig.add_subplot(1,1,1)

subplot.plot(data[:,0], data[:,1], label='$T(t)$', linewidth=2)

subplot.set_yscale('log')
subplot.set_xlabel("$t[s]$",fontsize=20)
subplot.set_ylabel("$T\,[K]$",fontsize=20)
plt.xlim(right=max(data [:,0]))
plt.legend(loc='upper right')

def scientificNotation(value):
    if value == 0:
        return '0'
    else:
        e = np.log10(np.abs(value))
        m = np.sign(value) * 10 ** (e - int(e))
        return r'${:.0f} \cdot 10^{{{:d}}}$'.format(m, int(e))

formatter = mpl.ticker.FuncFormatter(lambda x, p: scientificNotation(x))
plt.gca().xaxis.set_major_formatter(formatter)


plt.savefig('T(t).pdf', bbox_inches='tight', transparent=True)

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    只需将 x 值除以 1e14

    subplot.plot(data_a[:,0] / 1e14, data_a[:,1], label='$T(t)$', linewidth=2)
    

    如果您想为每个单独的刻度添加标签,您必须提供custom formatter,就像在汤姆的回答中一样。

    如果你想让它看起来像你的 y 轴上的刻度一样漂亮,你可以提供一个函数来用 LaTeX 格式化它:

    def scientificNotation(value):
        if value == 0:
            return '0'
        else:
            e = np.log10(np.abs(value))
            m = np.sign(value) * 10 ** (e - int(e))
            return r'${:.0f} \times 10^{{{:d}}}$'.format(m, int(e))
    
    # x is the tick value; p is the position on the axes.
    formatter = mpl.ticker.FuncFormatter(lambda x, p: scientificNotation(x))
    plt.gca().xaxis.set_major_formatter(formatter)
    

    当然,这会使您的 x 轴变得非常混乱,因此您可能最终需要以一定角度显示它们。

    【讨论】:

    • 感谢您的提示。我之前简单地尝试过,认为它不起作用,因为情节消失了,比例因子仍然存在。我昨天才开始使用 Python,所以我认为这是从那时起犯的许多语法错误之一。但是现在你也提出来了,我再次检查并意识到它只是第一次出错,因为我忘记了将重新缩放添加到put.xlim,如plt.xlim(right=max(data_a [:,0])/1e14)
    • 您是否还知道让因子出现在每个刻度标签中的方法?如果轴标签的数量级发生变化,这将意味着更少的摆弄。
    • @Casimir:是的,你需要设置formatter。看我的回答
    • @Will 非常感谢您的编辑。这看起来和我的想法一模一样。我在我的问题中添加了一个用你实现scientificNotation 制作的情节。就个人而言,我不认为 x 轴看起来很杂乱。
    • 科学点比 Python 点更多——我喜欢这个答案,但我建议将轴上的数字保留为 0、1、2、3、4、5 并更改轴标题到 t / 1e14s。在这种情况下,数字 1 的字面意思是 t = 1x10e14 s / 10e14 s。同样,y 轴上的数字 10^4 是 T = 1e4 K / K。方括号中的单位没有意义 - 您正在除以单位。
    【解决方案2】:

    您还可以使用 ticker 模块更改刻度格式器。

    一个例子是使用FormatStrFormatter:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    
    fig,ax = plt.subplots()
    ax.semilogy(np.linspace(0,5e14,50),np.logspace(3,7,50),'b-')
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.0e'))
    

    另请参阅here 的答案,其中包含许多解决此问题的好主意。

    【讨论】:

    • 这很酷,但有没有办法像y 标签一样打印x 标签,即使用4 x 10^14 而不是4e+14
    • 是的,我想你已经看到@WillVousden 的回答已经做到了
    【解决方案3】:

    除了 Will Vousden 的好答案之外,您还可以使用以下方法设置您在记号中写入的内容:

    plt.xticks(range(6), range(6))
    

    第一个range(6)是位置,第二个是标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      相关资源
      最近更新 更多