python - 删除轴刻度

标签 python matplotlib plot

我花了一些时间寻找问题的答案,但毫无结果,所以我认为需要提出一个新问题。考虑这个情节:

![enter image description here

坐标轴标签使用科学记数法。在 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 实现合并到我的脚本中,情节现在看起来像

enter image description here

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

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)

最佳答案

只需将 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 - 删除轴刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33416541/

相关文章:

python - 类变量和实例变量有什么区别?

python - M1 Mac 上的 Pip 安装 matplotlib 失败

python - Matplotlib:子图中不同的x轴标签

r - 使用 plotly 中的标记将抖动添加到箱线图

python - 显示渐近线的 pylab 图

python - selenium.common.exceptions.ElementClickInterceptedException : Message: element click intercepted: 的问题

python - Django TypeError <Page 1 of 8> 不是 JSON 可序列化的

python - Pyqtgraph 强制轴标签具有小数点

python - 在 PySpark 中存储大型 SparseMatrix 的最佳有效格式是什么

python - 从文件中读取 matplotlib 图形