原则上,您始终可以通过plt.gca().yaxis.set_xticklabels()
设置自定义标签。
但是,我不确定为什么不能在这里使用matplotlib.ticker.FuncFormatter
。 FuncFormatter
的设计目的正是为了根据刻度标签的位置和值提供自定义刻度标签。实际上,在matplotlib示例集合中有一个不错的示例。
在这种情况下,我们可以像期望的那样使用FuncFormatter,在matplotlib图形的轴上提供单位前缀作为后缀。为此,我们迭代1000的倍数,并检查要格式化的值是否超过它。如果该值是整数,则我们可以将其格式化为带有相应单位符号的整数。另一方面,如果小数点后面有余数,则我们检查需要格式化此数字的小数位数。
以下是完整示例:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
def y_fmt(y, pos):
decades = [1e9, 1e6, 1e3, 1e0, 1e-3, 1e-6, 1e-9 ]
suffix = ["G", "M", "k", "" , "m" , "u", "n" ]
if y == 0:
return str(0)
for i, d in enumerate(decades):
if np.abs(y) >=d:
val = y/float(d)
signf = len(str(val).split(".")[1])
if signf == 0:
return '{val:d} {suffix}'.format(val=int(val), suffix=suffix[i])
else:
if signf == 1:
print val, signf
if str(val).split(".")[1] == "0":
return '{val:d} {suffix}'.format(val=int(round(val)), suffix=suffix[i])
tx = "{"+"val:.{signf}f".format(signf = signf) +"} {suffix}"
return tx.format(val=val, suffix=suffix[i])
return y
fig, ax = plt.subplots(ncols=3, figsize=(10,5))
x = np.linspace(0,349,num=350)
y = np.sinc((x-66.)/10.3)**2*1.5e6+np.sinc((x-164.)/8.7)**2*660000.+np.random.rand(len(x))*76000.
width = 1
ax[0].bar(x, y, width, align='center', linewidth=2, color='red', edgecolor='red')
ax[0].yaxis.set_major_formatter(FuncFormatter(y_fmt))
ax[1].bar(x[::-1], y*(-0.8e-9), width, align='center', linewidth=2, color='orange', edgecolor='orange')
ax[1].yaxis.set_major_formatter(FuncFormatter(y_fmt))
ax[2].fill_between(x, np.sin(x/100.)*1.7+100010, np.cos(x/100.)*1.7+100010, linewidth=2, color='#a80975', edgecolor='#a80975')
ax[2].yaxis.set_major_formatter(FuncFormatter(y_fmt))
for axes in ax:
axes.set_title("TTL Distribution")
axes.set_xlabel('TTL Value')
axes.set_ylabel('Number of Packets')
axes.set_xlim([x[0], x[-1]+1])
plt.show()
提供以下情节:
![这里输入图片描述](https://istack.dev59.com/r1xT4.webp)
y_fmt(100100, 0)
返回100.1 k
,但y_fmt(100010, 0)
返回100 k
。 - BartEngFormatter
,可以直接执行非常相似的操作。http://matplotlib.org/examples/api/engineering_formatter.html - tacaswell