简体   繁体   中英

Matplotlib: axis ticks number format - engineering notation

Background

Axis ticks can be converted to scientific format as suggested here .

Numbers can be converted into engineering format, one at a time as shown here

Question

How to format axis ticks in engineering notations ie order of magnitude is a multiple of 3.

You may want to explain exactly what you mean by "engineering notation", but there is an EngFormatter , which automatically uses the SI unit prefixes (ie micro, milli, kilo, mega, etc.)

fig, ax = plt.subplots()
ax.set_ylim(0,1e6)
ticker = matplotlib.ticker.EngFormatter(unit='')
ax.yaxis.set_major_formatter(ticker)

在 y 轴上带有工程符号的结果图

Playing around with the decimal module, I came around with the following solution:

from decimal import Decimal
import matplotlib.pyplot as plt
import numpy as np

data1 = np.linspace(-9, 9, 19)
data2 = 2.3 * 10**data1

yticks = 10**(np.linspace(-9, 9, 19))
yticklabels = [Decimal(y).quantize(Decimal('0.0000000001')).normalize().to_eng_string() for y in yticks]

plt.figure(1)
plt.subplot(121)
plt.grid(True)
plt.xlabel('k')
plt.ylabel('10^k')
plt.plot(data1, data2, 'k.')
plt.yscale('log')
plt.xticks(data1)
plt.yticks(yticks)
plt.subplot(122)
plt.grid(True)
plt.xlabel('k')
plt.ylabel('10^k')
plt.plot(data1, data2, 'k.')
plt.yscale('log')
plt.xticks(data1)
plt.yticks(yticks, yticklabels)
plt.show()

输出

Please refer to the accepted answer on your second linked Q&A : Exponents between 0 and -6 are not converted to the desired format by definition/standard. Also, I needed to use the quantize method from decimal , too, because otherwise the outputted numbers would have had to many positions. (Remove the quantize part, and you'll see, what I mean.)

Hope that helps!

If one looks at the source , they realize that the solution proposed by Diziet Asahi can be easily modified to fulfill OP desires, as in the following

import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter

fig, ax = plt.subplots()
ax.set_ylim(0,1e6)
ticker = EngFormatter(unit='')
############################################################################
ticker.ENG_PREFIXES =  {i:"10**%d"%i if i else "" for i in range(-24, 25,3)}
############################################################################
ax.yaxis.set_major_formatter(ticker)
plt.show()

在此处输入图像描述

Maybe ScalarFormatter (instead of EngFormatter) will do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM