原则上re始终可以通过plt.gca().yaxis.set_xticklabels()
设置自定义标签。
但是,我不确定为什么不应该有可能在这里使用matplotlib.ticker.FuncFormatter
。 FuncFormatter
专门用于根据ticklabel的位置和价值提供自定义标签。 matplotlib示例集合中实际上有一个nice example。
在这种情况下,我们可以根据需要使用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
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()
它提供了以下情节:
不错的例子,比我的完整得多。但是你写*“如果有一个小数点后面的余数,我们检查需要多少小数位”*,但是截断点仍然有点随机?例如。 'y_fmt(100100,0)'返回'100.1 k',但'y_fmt(100010,0)'返回'100 k'。 – Bart
@Bart正确!我确实想到了这个问题,但之后就忘记了。我更新了这个例子,以包括这样的情况,其中数字很大但彼此接近。 – ImportanceOfBeingErnest
还有内置的'EngFormatter',它可以做一些非常类似于开箱即用的工具http://matplotlib.org/examples/api/engineering_formatter.html – tacaswell