我有一个包含记录事件的文件。每个条目都有一个时间和延迟。我对绘制延迟的累积分布函数很感兴趣。我对尾延迟最感兴趣,所以我希望图有一个对数y轴。我对以下百分比的延迟感兴趣:90、99、99.9、99.99和99.99。以下是迄今为止生成常规CDF图的代码:
# retrieve event times and latencies from the file
times, latencies = read_in_data_from_file('myfile.csv')
# compute the CDF
cdfx = numpy.sort(latencies)
cdfy = numpy.linspace(1 / len(latencies), 1.0, len(latencies))
# plot the CDF
plt.plot(cdfx, cdfy)
plt.show()
我知道我想让情节看起来像什么,但我一直在努力想得到它。我希望它看起来像这样(我没有生成这个图):
使x轴成为对数很简单。Y轴就是那个给我带来问题的轴。使用
set_yscale('log')
不起作用,因为它希望使用10的幂。我真的希望Y轴和这个图有相同的滴答标签。我怎样才能把我的数据画成这样的对数图呢?
编辑:
如果我将yscale设置为“log”,将ylim设置为[0.1,1],我得到以下绘图:
问题是,在0到1范围内的数据集上,典型的对数刻度图将集中在接近零的值上。相反,我希望关注接近1的值。
最佳答案
实际上,您需要将以下转换应用于您的Y
值:-log10(1-y)
。这是唯一的限制,所以您应该能够在转换的图上有负值。
以下是一个修改过的y < 1
文档,演示了如何将自定义转换合并到“scales”中:
import numpy as np
from numpy import ma
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
from matplotlib.ticker import FixedFormatter, FixedLocator
class CloseToOne(mscale.ScaleBase):
name = 'close_to_one'
def __init__(self, axis, **kwargs):
mscale.ScaleBase.__init__(self)
self.nines = kwargs.get('nines', 5)
def get_transform(self):
return self.Transform(self.nines)
def set_default_locators_and_formatters(self, axis):
axis.set_major_locator(FixedLocator(
np.array([1-10**(-k) for k in range(1+self.nines)])))
axis.set_major_formatter(FixedFormatter(
[str(1-10**(-k)) for k in range(1+self.nines)]))
def limit_range_for_scale(self, vmin, vmax, minpos):
return vmin, min(1 - 10**(-self.nines), vmax)
class Transform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, nines):
mtransforms.Transform.__init__(self)
self.nines = nines
def transform_non_affine(self, a):
masked = ma.masked_where(a > 1-10**(-1-self.nines), a)
if masked.mask.any():
return -ma.log10(1-a)
else:
return -np.log10(1-a)
def inverted(self):
return CloseToOne.InvertedTransform(self.nines)
class InvertedTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, nines):
mtransforms.Transform.__init__(self)
self.nines = nines
def transform_non_affine(self, a):
return 1. - 10**(-a)
def inverted(self):
return CloseToOne.Transform(self.nines)
mscale.register_scale(CloseToOne)
if __name__ == '__main__':
import pylab
pylab.figure(figsize=(20, 9))
t = np.arange(-0.5, 1, 0.00001)
pylab.subplot(121)
pylab.plot(t)
pylab.subplot(122)
pylab.plot(t)
pylab.yscale('close_to_one')
pylab.grid(True)
pylab.show()
example
请注意,您可以通过关键字参数控制9的数目:
pylab.figure()
pylab.plot(t)
pylab.yscale('close_to_one', nines=3)
pylab.grid(True)