Matplotlib / Seaborn自定义比例除以0

时间:2017-01-23 16:41:28

标签: python matplotlib

我正在尝试为显示http://matplotlib.org/examples/api/custom_scale_example.htmlCreating Probability/Frequency Axis Grid (Irregularly Spaced) with Matplotlib创建自定义比例尺,但我的比例在0和1都变为无穷大。我正在利用屏蔽数组,如示例所示块值介于.01和.99之间。我有4个案例如下。我的愿望是让seaborn在没有警告的情况下使用y轴。我找到了1个案例(case 2),其中没有seaborn我没有错误,但我不知道为什么它与case 1

相符合作用
from __future__ import unicode_literals

import numpy as np
from numpy import ma
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
from matplotlib.ticker import AutoLocator
from matplotlib import rcParams


# BUG: this example fails with any other setting of axisbelow
rcParams['axes.axisbelow'] = False


class WeibullProbScale(mscale.ScaleBase):

    name = 'weibull'

    def __init__(self, axis, **kwargs):

        mscale.ScaleBase.__init__(self)
        lowerLim = kwargs.pop("lowerLim",.01)
        upperLim = kwargs.pop("upperLim", .99)

        self.lowerLim = lowerLim
        self.upperLim = upperLim

    def get_transform(self):
        return self.WeibullProbTransform(self.lowerLim,self.upperLim)

    def set_default_locators_and_formatters(self, axis):

        axis.set_major_locator(AutoLocator())

    class WeibullProbTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, lowerLim, upperLim):
            mtransforms.Transform.__init__(self)
            self.lowerLim = lowerLim
            self.upperLim = upperLim

        def transform_non_affine(self, a):
            masked = ma.masked_where((a < self.lowerLim) | (a > self.upperLim), a)
            if masked.mask.any():
                return ma.log(ma.log(1.0/(1.0 - masked)))
            else:
                return np.log(np.log(1.0/(1.0 - a)))

        def inverted(self):
            return WeibullProbScale.InvertedWeibullProbTransform(
                self.lowerLim, self.upperLim)

    class InvertedWeibullProbTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, lowerLim, upperLim):
            mtransforms.Transform.__init__(self)
            self.lowerLim = lowerLim
            self.upperLim = upperLim

        def transform_non_affine(self, a):
            return 1.0 - np.exp(-np.exp(a))

        def inverted(self):
            return WeibullProbScale.WeibullProbTransform(self.thresh)

# Now that the Scale class has been defined, it must be registered so
# that ``matplotlib`` can find it.
mscale.register_scale(WeibullProbScale)


if __name__ == '__main__':

    #Setup arrays to plot
    import matplotlib.pyplot as plt
    from scipy.stats import exponweib

    t = np.logspace(1,6,num=100,base=10)
    dist = exponweib(a=1,c=1.3,loc=0,scale=10000)

    # Case 1 - Standard...what I want
    if True:
        plt.plot(t, dist.cdf(t), '-', lw=2)
        plt.gca().set_xscale('log')
        plt.gca().set_yscale('weibull',lowerLim=.01,upperLim=.99)
        plt.ylim([.01,.99])
        plt.xlabel('time')
        plt.ylabel('probability')
        plt.title('Probability Plot')
        plt.grid(True)
        plt.show()

    # Case 2 - For some reason 1.E-10 makes the error go away...
    if True:
        plt.plot(t, dist.cdf(t), '-', lw=2)
        plt.gca().set_xscale('log')
        plt.gca().set_yscale('weibull',lowerLim=1.E-10,upperLim=.99)
        plt.ylim([.01,.99])
        plt.xlabel('time')
        plt.ylabel('probability')
        plt.title('Probability Plot')
        plt.grid(True)
        plt.show()

    # Case 3 - Seaborn works without y label
    if True:
        import seaborn as sns
        plt.plot(t, dist.cdf(t), '-', lw=2)
        plt.gca().set_xscale('log')
        plt.gca().set_yscale('weibull',lowerLim=1.E-10,upperLim=.99)
        plt.ylim([.01,.99])
        plt.xlabel('time')
        plt.title('Probability Plot')
        plt.grid(True)
        plt.show()

    # Case 4 - Seaborn fails with ylabel
    if True:
        plt.plot(t, dist.cdf(t), '-', lw=2)
        plt.gca().set_xscale('log')
        plt.gca().set_yscale('weibull',lowerLim=1.E-10,upperLim=.99)
        plt.ylim([.01,.99])
        plt.xlabel('time')
        plt.ylabel('probability')
        plt.title('Probability Plot')
        plt.grid(True)
        plt.show()

case 1

的输出
UserWarning: Warning: converting a masked element to nan.
  warnings.warn("Warning: converting a masked element to nan.")

Figure for basic .01 lower limit

Case 2lowerLim默认值更改为1.e-10,x轴正常工作且不输出任何警告,但数字的减少并不会产生敏感为什么它删除了警告。 Working x axis with very small lowerlim

Case 3使用seaborn尝试让情节更漂亮,一切正常,但我无法在情节上添加ylabel。下图是没有y标签的工作图。

Seaborn without ylabel so the output actually works

Case 4尝试使用带有seaborn的ylabel。您可以在下面看到错误消息。

Traceback (most recent call last):
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\backe
nds\backend_qt5agg.py", line 180, in __draw_idle_agg
    FigureCanvasAgg.draw(self)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\backe
nds\backend_agg.py", line 474, in draw
    self.figure.draw(self.renderer)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\artis
t.py", line 62, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\figur
e.py", line 1159, in draw
    func(*args)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\artis
t.py", line 62, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\axes\
_base.py", line 2319, in draw
    a.draw(renderer)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\artis
t.py", line 62, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\axis.
py", line 1122, in draw
    self.label.draw(renderer)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\artis
t.py", line 62, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "\AppData\Local\Continuum\Miniconda2\lib\site-packages\matplotlib\text.
py", line 757, in draw
    raise ValueError("posx and posy should be finite values")
ValueError: posx and posy should be finite values

似乎matplotlibseaborn依赖于将1和0传递给我的变换函数,后者无法提供所需的输出。有关如何使这项工作的任何想法?

0 个答案:

没有答案