在 matplotlib 图的轴上显示小数位和科学记数法 [英] Show decimal places and scientific notation on the axis of a matplotlib plot

查看:132
本文介绍了在 matplotlib 图的轴上显示小数位和科学记数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 2.7 在 pyqt 程序中用 matplotlib 绘制一些大数字.我有一个 y 轴,范围从 1e+18 到 3e+18(通常).我希望看到每个刻度线都以科学记数法显示值并保留 2 位小数.例如,2.35e+18 而不是 2e+18,因为 2e+18 和 3e+18 之间的值对于一些刻度线仍然只读取 2e+18.这是该问题的一个示例.

I am plotting some big numbers with matplotlib in a pyqt program using python 2.7. I have a y-axis that ranges from 1e+18 to 3e+18 (usually). I'd like to see each tick mark show values in scientific notation and with 2 decimal places. For example 2.35e+18 instead of just 2e+18 because values between 2e+18 and 3e+18 still read just 2e+18 for a few tickmarks. Here is an example of that problem.

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 300, 20)
y = np.linspace(0,300, 20)
y = y*1e16
ax.plot(x,y)  
ax.get_xaxis().set_major_formatter(plt.LogFormatter(10,  labelOnlyBase=False))
ax.get_yaxis().set_major_formatter(plt.LogFormatter(10,  labelOnlyBase=False))
plt.show()

推荐答案

如果你使用 matplotlib.ticker.FormatStrFormatter 而不是 LogFormatter 这真的很容易做到>.以下代码将使用 '%.2e' 格式标记所有内容:

This is really easy to do if you use the matplotlib.ticker.FormatStrFormatter as opposed to the LogFormatter. The following code will label everything with the format '%.2e':

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

fig = plt.figure()

ax = fig.add_subplot(111)

x = np.linspace(0, 300, 20)

y = np.linspace(0,300, 20)
y = y*1e16

ax.plot(x,y)

ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))

plt.show()

这篇关于在 matplotlib 图的轴上显示小数位和科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆