Skip to content

probability plots with multiple data series #1297

Open

Description

@josef-pkt

mainly an idea while thinking of k-sample goodness of fit tests and plots:

can we plot several data series on the same qq or pp plot?

one application would be if we have several series, by category for example
another application would be a k sample comparison where the reference distribution is the edf of the pooled sample.

Activity

  1. josef-pkt commented on Jan 6, 2014

    @josef-pkt
    MemberAuthor

    @phobson Any idea how difficult this would be to implement?

  2. phobson commented on Jan 6, 2014

    @phobson
    Contributor

    In the current master, you can do something like this:

    import numpy as np
    import matplotlib.pyplot as plt
    import statsmodels.api as sm
    
    x = sm.ProbPlot(np.random.normal(loc=3.0, scale=0.5, size=37))
    y = sm.ProbPlot(np.random.normal(loc=3.5, scale=1.5, size=37))
    z = sm.ProbPlot(np.random.normal(loc=2.5, scale=2.5, size=37))
    
    fig, ax = plt.subplots()
    x.probplot(ax=ax, plotkwargs=dict(marker='s', markerfacecolor='b'))
    y.probplot(ax=ax, plotkwargs=dict(marker='o', markerfacecolor='r'))
    z.probplot(ax=ax, plotkwargs=dict(marker='d', markerfacecolor='g'))
    
    fig.savefig('probplot_test01.png')

    Does that cover your use cases or do I misunderstand?

  3. josef-pkt commented on Jan 6, 2014

    @josef-pkt
    MemberAuthor

    Thanks, yes that does it - except it doesn't work (using master)
    Did you run it?
    Did we forget to merge something?

    The ppplot below is exactly what I had in mind:

    import numpy as np
    import matplotlib.pyplot as plt
    import statsmodels.api as sm
    
    x = sm.ProbPlot(np.random.normal(loc=3.0, scale=0.5, size=37))
    y = sm.ProbPlot(np.random.normal(loc=3.5, scale=1.5, size=37))
    z = sm.ProbPlot(np.random.normal(loc=2.5, scale=2.5, size=37))
    
    fig, ax = plt.subplots()
    ##x.probplot(ax=ax, plotkwargs=dict(marker='s', markerfacecolor='b'))
    ##y.probplot(ax=ax, plotkwargs=dict(marker='o', markerfacecolor='r'))
    ##z.probplot(ax=ax, plotkwargs=dict(marker='d', markerfacecolor='g'))
    probplot = False
    if probplot:
        x.probplot(ax=ax, **dict(fmt='s'))#, markerfacecolor='b'))
        y.probplot(ax=ax, **dict(fmt='o'))#, markerfacecolor='r'))
        z.probplot(ax=ax, **dict(fmt='d'))#, markerfacecolor='g'))
        fig.savefig('probplot_test01.png')
    else:
        # Bug: code has typo quantiles
        x.ppplot(ax=ax, line='45', **dict(fmt='s'))#, markerfacecolor='b'))
        y.ppplot(ax=ax, line='45', **dict(fmt='o'))#, markerfacecolor='r'))
        z.ppplot(ax=ax, line='45', **dict(fmt='d'))#, markerfacecolor='g'))    
    
        fig.savefig('ppplot_test01.png')
    
  4. phobson commented on Jan 6, 2014

    @phobson
    Contributor

    I didn't get a chance to run it. I'm not at a machine where I can run master at the moment.

    The following should work:

    x.ppplot(ax=ax, line='45', plotkwargs=dict(fmt='s'))
    y.ppplot(ax=ax, line='45', plotkwargs=dict(fmt='o'))
    z.ppplot(ax=ax, line='45', plotkwargs=dict(fmt='d'))

    If it doesn't I screwed up that PR. At the very least, you've exposed a major documentation deficiency where the plotkwargs aren't actually the standards kwargs a typical matplotlib user might expect to be passed to ax.plot(...).

    So I owe you a PR to fix that.

  5. josef-pkt commented on Jan 6, 2014

    @josef-pkt
    MemberAuthor

    Ok, **plotkwargs are ** unpacked. I would prefer them packed as in your example

    typo on line 190 self.dist.cdf(quantiles) is misspelled in master

    related: I'm using now `fmt='s-' which adds a line, but maybe a step function would be interesting.
    maybe it gets too close to ECDF plots.

    I was again looking for references to add confidence intervals to the plots, but it's still not yet clear to me what needs to be done.

    The articles I'm looking at use step plots, similar to kaplan-meier plots.

  6. josef-pkt commented on Jan 6, 2014

    @josef-pkt
    MemberAuthor
  7. josef-pkt commented on Jan 6, 2014

    @josef-pkt
    MemberAuthor

    a quick try just adding step as additional keyword to _do_plot
    https://picasaweb.google.com/106983885143680349926/Joepy#5965921015956964514

    edit 2015-01-13
    updated link https://picasaweb.google.com/106983885143680349926/Joepy?noredirect=1#5965921015956964514

        if not step:
            ax.plot(x, y, fmt)
        else:
            ax.step(x, y, fmt)
    

    I haven't looked at the correct step options yet, to get the symbols on the upper edge of the step

  8. josef-pkt commented on Jan 6, 2014

    @josef-pkt
    MemberAuthor

    There is something wrong with getting ppplot with fit=False
    In the above plot, the data is individually loc scale corrected, so we don't see samples that are location or scale shifted.

    forcing fit_params = (0, 1) gives me this plot, which shows clear differences and that they are not from the parameterized distribution N(0, 1)
    https://picasaweb.google.com/106983885143680349926/Joepy#5965930448408216082

    edit 2015-01-13
    updated link https://picasaweb.google.com/106983885143680349926/Joepy?noredirect=1#5965930448408216082

  9. josef-pkt commented on Jan 7, 2014

    @josef-pkt
    MemberAuthor

    line 136 fit is called even if fit=False

            self.fit_params = dist.fit(data)
            if fit:
    

    line 189: quantiles use fit_params, which are not the default (0, 1) because of above

  10. phobson commented on Jan 7, 2014

    @phobson
    Contributor

    any chance you can post nbviewer links for the code that you're using to
    make these plots?

    On Tue, Jan 7, 2014 at 6:06 AM, Josef Perktold [email protected]:

    two more variations, with pointwise confidence intervals

    https://picasaweb.google.com/106983885143680349926/Joepy#5966152154485158946

    https://picasaweb.google.com/106983885143680349926/Joepy#5966152154437212114

    —
    Reply to this email directly or view it on GitHubhttps://github.com//issues/1297#issuecomment-31739474
    .

  11. josef-pkt commented on Jan 7, 2014

    @josef-pkt
    MemberAuthor

    oops, I'm using IDLE right now :)
    I still need to look more into the confidence interval question.

    here is my dirty script, based on your code:

    import numpy as np
    import matplotlib.pyplot as plt
    import statsmodels.api as sm
    
    import statsmodels.stats.proportion as smprop
    
    def add_ci(prob_expected, prob_sample, ax, kwds=None):
        print kwds
        nobs = prob_sample.shape
        ci = smprop.proportion_confint(prob_sample * nobs, nobs)
        ax.fill_between(prob_expected, ci[0], ci[1], alpha=0.25, **kwds)
        return ax
    
    x = sm.ProbPlot(np.random.normal(loc=0.0, scale=0.5, size=37))
    y = sm.ProbPlot(np.random.normal(loc=1.5, scale=1.5, size=37))
    z = sm.ProbPlot(np.random.normal(loc=2.5, scale=2.5, size=37))
    x.fit_params = (0, 1)
    y.fit_params = (0, 1)
    z.fit_params = (0, 1)
    
    fig, ax = plt.subplots()
    ##x.probplot(ax=ax, plotkwargs=dict(marker='s', markerfacecolor='b'))
    ##y.probplot(ax=ax, plotkwargs=dict(marker='o', markerfacecolor='r'))
    ##z.probplot(ax=ax, plotkwargs=dict(marker='d', markerfacecolor='g'))
    probplot = False
    if probplot:
        x.probplot(ax=ax, **dict(fmt='s'))#, markerfacecolor='b'))
        y.probplot(ax=ax, **dict(fmt='o'))#, markerfacecolor='r'))
        z.probplot(ax=ax, **dict(fmt='d'))#, markerfacecolor='g'))
        fig.savefig('probplot_test01.png')
    else:
        # Bug: code has typo quantiles
        x.ppplot(ax=ax, line='45', **dict(fmt='-', step=True))#, markerfacecolor='b'))
        y.ppplot(ax=ax, line='45', **dict(fmt='-', step=True))#, markerfacecolor='r'))
        z.ppplot(ax=ax, line='45', **dict(fmt='-', step=True))#, markerfacecolor='g'))
    ##    nobs = x.data.shape
    ##    import statsmodels.stats.proportion as smprop
    ##    p = x.sample_percentiles
    ##    p = x.theoretical_percentiles
    ##    ci = smprop.proportion_confint(p*nobs, nobs)
    ##    ax.fill_between(x.theoretical_percentiles, *ci, alpha=0.25, **{'color':'b'})
        ci_th = False #True
        if ci_th:
            add_ci(x.theoretical_percentiles, x.theoretical_percentiles, ax, kwds={'color':'b'})
        else:                                                                        
            add_ci(x.theoretical_percentiles, x.sample_percentiles, ax, kwds={'color':'b'})
            add_ci(y.theoretical_percentiles, y.sample_percentiles, ax, kwds={'color':'g'})
            add_ci(z.theoretical_percentiles, z.sample_percentiles, ax, kwds={'color':'r'})
    
        fig.savefig('ppplot_test03_ci2.png')
    

    I only made two changes to the source, fixing quantiles typo and adding step option

    @@ -185,11 +185,11 @@ class ProbPlot(object):
    
         @cache_readonly
         def sample_percentiles(self):
             quantiles = \
                 (self.sorted_data - self.fit_params[-2])/self.fit_params[-1]
    -        return self.dist.cdf(qntls)
    +        return self.dist.cdf(quantiles)
    
         def ppplot(self, xlabel=None, ylabel=None, line=None, other=None,
                    ax=None, **plotkwargs):
             """
             P-P plot of the percentiles (probabilities) of x versus the
    @@ -702,11 +702,11 @@ def _fmt_probplot_axis(ax, dist, nobs):
                            rotation_mode='anchor',
                            horizontalalignment='right',
                            verticalalignment='center')
         ax.set_xlim([axis_qntls.min(), axis_qntls.max()])
    
    -def _do_plot(x, y, dist=None, line=False, ax=None, fmt='bo'):
    +def _do_plot(x, y, dist=None, line=False, ax=None, fmt='bo', step=False):
         """
         Boiler plate plotting function for the `ppplot`, `qqplot`, and
         `probplot` methods of the `ProbPlot` class
    
         Parameteters
    @@ -729,11 +729,14 @@ def _do_plot(x, y, dist=None, line=False, ax=None, fmt='bo'):
         ax : Matplotlib AxesSubplot instance (see Parameters)
    
         """
         fig, ax = utils.create_mpl_ax(ax)
         ax.set_xmargin(0.02)
    -    ax.plot(x, y, fmt)
    +    if not step:
    +        ax.plot(x, y, fmt)
    +    else:
    +        ax.step(x, y, fmt, where='post')
         if line:
             if line not in ['r','q','45','s']:
                 msg = "%s option for line not understood" % line
                 raise ValueError(msg)
    
  12. josef-pkt commented on Jan 9, 2014

    @josef-pkt
    MemberAuthor

    #1307 includes another addition to probplots

  13. added this to the 0.10 milestone on Oct 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions