Visitar URL original
Feature request: proper ECDF · Issue #16561 · matplotlib/matplotlib · GitHub
The Wayback Machine - https://web.archive.org/web/20210209021746/https://github.com/matplotlib/matplotlib/issues/16561
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: proper ECDF #16561

Open
Wrzlprmft opened this issue Feb 20, 2020 · 34 comments
Open

Feature request: proper ECDF #16561

Wrzlprmft opened this issue Feb 20, 2020 · 34 comments
Assignees
Milestone

Comments

@Wrzlprmft
Copy link

@Wrzlprmft Wrzlprmft commented Feb 20, 2020

While the hist method allows to plot empirical cumulative distribution functions (ECDFs) with the cumulative and density keywords, this is far from perfect:

  • It uses a binning, which is unnecessary for ECDFs and either leads to inaccuracies (low binning) or a waste of time and spurious plot points for small datasets (high binning).
  • The default plot style is bars which are not the typical way to visualise ECDFs.
  • It is not easy to find. I bet that this very issue will soon be the first thing people wanting to plot the ECDF with Matplotlib will find.

Please implement a “proper” ECDF.

Half a pull request

The following should contain all the major components necessary to implement this. If I had the the time and patience to work through Matplotlib’s code structure, testing, replicating everything for the legacy interface and so on, I would make a pull request.

from warnings import warn
import numpy as np
from matplotlib import pyplot as plt

def ecdf_points(data,remove_redundant,absolute=False):
    assert data.ndim==1
    assert np.all(np.isfinite(data))
    
    abscissae = np.append(data,np.inf)
    abscissae.sort()
    
    if absolute:
        ordinates = np.arange(len(abscissae),dtype=int)
    else:
        ordinates = np.linspace(0,1,len(abscissae)) 
    
    if remove_redundant:
        needed = np.ediff1d(abscissae,to_begin=True).astype(bool)
        abscissae = abscissae[needed]
        ordinates = ordinates[needed]
    
    return abscissae, ordinates

test_data = np.array([4,2,3,2,4,3,1,2,1,4])
np.testing.assert_allclose(
    ecdf_points(test_data,remove_redundant=True),
    [ [1,2,3,4,np.inf], [0,0.2,0.5,0.7,1.0] ],
)
np.testing.assert_equal(
    ecdf_points(test_data,remove_redundant=True,absolute=True),
    [ [1,2,3,4,np.inf], [0,2,5,7,10] ],
)


def ecdf(axes,x,*args,remove_redundant=False,absolute=False,**kwargs):
    """
        Plot the empirical cumulative distribution function, i.e., the fraction of data points less than or equal than some value. Returns the supporting points of the underlying step plot.

        Parameters
        ----------
        x : one-dimensional array
            Input values
        
        remove_redundant : bool, optional
            Whether spurious points arising from identical data points shall be removed. This is mainly useful for large datasets containing many identical data points, where you get an unnecessarily large or inefficient figure otherwise. If your data does not contain any duplicate points, this has no effect and just uses some time and memory.
        
        absolute : bool, optional
            Whether to plot the absolute number (instead of the fraction) of data points less than or equal than some value.
            
        Returns
        -------
        abscissae : array
            The positions of steps in the ECDF.

        ordinates : array
            The lower values of the steps.
        
        lines : Lines object
            The lines object produced by the underlying plot call.
    """
    if "drawstyle" in kwargs and kwargs["drawstyle"]!="steps-pre":
        warn("Overwriting 'drawstyle' argument with 'steps-pre' to achieve a correct ECDF.")
    kwargs["drawstyle"] = "steps-pre"
    
    points = ecdf_points(x,remove_redundant,absolute)
    lines = axes.plot(*points,*args,**kwargs)
    return (*points,lines)

fig,axes = plt.subplots()
ecdf(axes,test_data,remove_redundant=True,absolute=True)
axes.hist(test_data,bins=1000,cumulative=True);

fig,axes = plt.subplots()
ecdf(axes,test_data,remove_redundant=True)
axes.hist(test_data,bins=1000,cumulative=True,density=True);
@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 20, 2020

FWIW I have been using my own helper for a while, which supports both ecdf and eccdf, weighted points, and plotting along the x or the y axis:

def _ecdf_helper(ax, data, weights, swapaxes, label):
    data = np.asarray(data)
    mask = ~np.isnan(data)
    data = data[mask]
    sort = np.argsort(data)
    data = data[sort]
    if weights is None:
        # Ensure that we end at exactly 1, avoiding floating point errors.
        cweights = (1 + np.arange(len(data))) / len(data)
    else:
        weights = weights[mask]
        weights = weights / np.sum(weights)
        weights = weights[sort]
        cweights = np.cumsum(weights)
    if not swapaxes:
        if not ax.get_ylabel():
            ax.set_ylabel(label)
    else:
        if not ax.get_xlabel():
            ax.set_xlabel(label)
    return data, cweights


def plot_ecdf(ax, data, *, weights=None, swapaxes=False, **kwargs):
    """Plot an empirical cumulative distribution function."""
    data, cweights = _ecdf_helper(ax, data, weights, swapaxes, "CDF")
    if not swapaxes:
        return ax.plot([data[0], *data], [0, *cweights],
                       drawstyle="steps-post", **kwargs)[0]
    else:
        return ax.plot([0, *cweights], [data[0], *data],
                       drawstyle="steps-pre", **kwargs)[0]


def plot_eccdf(ax, data, *, weights=None, swapaxes=False, **kwargs):
    """Plot an empirical, complementary cumulative distribution function."""
    data, cweights = _ecdf_helper(ax, data, weights, swapaxes, "CCDF")
    if not swapaxes:
        return ax.plot(
            [*data, data[-1]], [1, *1 - cweights],
            drawstyle="steps-pre", **kwargs)[0]
    else:
        return ax.plot(
            [1, *1 - cweights], [*data, data[-1]],
            drawstyle="steps-post", **kwargs)[0]

I agree hist() is not a proper substitute for that. I am not sure this should go in mpl proper though, as it's perfectly fine as a standalone package.

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 20, 2020 •

I am not sure this should go in mpl proper though, as it's perfectly fine as a standalone package.

Matplotlib already has things like hist and acorr, which go beyond pure plotting. So, unless there is some policy not to include anything new of that kind, the ECDF doesn’t seem to be misplaced. It is a pretty basic tool after all. Also, let’s not forget that a bad ECDF (hist(…,cumulative=True,density=True)) is already in Matplotlib.

In some standalone package it will stay obscure and won’t reach most of those who want to use it.

@jklymak
Copy link
Contributor

@jklymak jklymak commented Feb 20, 2020

I think this is something numpy or scipy should be in charge of. There was some discussion in numpy, but looks like they think it should be in scipy.stats... numpy/numpy#9057. Then we can just plot whatever they tell us to. I.e. x,y = scipy.stats.ecdf(data), ax.plot(x,y)

@tacaswell
Copy link
Member

@tacaswell tacaswell commented Feb 20, 2020

I agree this is better as a stand-alone package, it not being discover-able is a solvable documentation problem. We have a third-party packages page in our docs and a blog that we can use to promote a new project. If it gets any take up, we are also open to putting the canonical repo in the Matplotlib organization.

Matplotlib is used across a wide range of domains so things that seem "basic" is some domains are at best obscure in others (for example, when I saw the title of this issue I thought this was going to be a request for output to a file format used internally by some Microsoft products). If we were to become a union of all of the specialized plots from every domain Matplotlib would grow even larger/less discover-able than it already is. Once we add a function to the top level API it is very hard to change so we need to make sure that anything we add is something that is broadly useful and paramaterized the way users expect. Given that @Wrzlprmft and @anntzer wrote the same function, but with different inputs suggests to me that we don't yet know what the "right" api is. This problem is compounded when two fields call two very different things the same name.

A significant advantage of doing it as a stand-alone package is that you can be much more nimble. If we were to take this into Matplotlib, it would be best-case several months before we got it out to users who have to upgrade to the newest release. If you do this as a stand alone package you could have it up on pypi and available to install in the next few hours (see https://github.com/NSLS-II/scientific-python-cookiecutter for a cookie cutter) and you can probably make this work with almost any version of Matplotlib that has been released.

A recent example of this is https://cmasher.readthedocs.io/ which started as a single color map being proposed to be added to Matplotlib that is now a stand-alone package of a whole set of color maps.

@tacaswell
Copy link
Member

@tacaswell tacaswell commented Feb 20, 2020

And despite the responses mostly being negative, I appreciate that you opened this issue!

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 20, 2020

I think this is something numpy or scipy should be in charge of. There was some discussion in numpy, but looks like they think it should be in scipy.stats... numpy/numpy#9057. Then we can just plot whatever they tell us to. I.e. x,y = scipy.stats.ecdf(data), ax.plot(x,y)

It won’t work like this, as the computation of points and plotting are somewhat intertwined. Any data SciPy could output would also have to work for further computation, so it’s either a function or a set of data points. However, a proper plot of the ECDF is a step plot (hence the drawstyle = "steps-pre"). To be passed to plot as you suggest, SciPy would have to output extra data, which won’t make sense in contexts other than plotting. On the other hand, if you plot with steps, you have to ensure that the points you compute match the choice of steps (steps-pre vs. steps-post), which is nothing most users of this function want to think about.

Given that @Wrzlprmft and @anntzer wrote the same function, but with different inputs suggests to me that we don't yet know what the "right" api is. This problem is compounded when two fields call two very different things the same name.

I don’t think that this is the case here. Our suggestions implement different optional features, but the basic behaviour is the same. I also don’t see a name collision.

so things that seem "basic" is some domains are at best obscure in others

For whatever it’s worth, the ECDF is part of basic R and Matlab (but then, those haven’t invented namespaces). Also, please consider that Matplotlib already has the ECDF (hist(…,cumulative=True,density=True)); it’s just a suboptimal implementation for many use cases (see my initial request). I don’t presume you will just retire that functionality for an external solution. Most people will just use that “bad” implementation instead of installing a package.

@jklymak
Copy link
Contributor

@jklymak jklymak commented Feb 20, 2020

In Matlab ecdf is part of the stats toolbox. Same with r.

@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 20, 2020

FWIW when I said "I'm not sure this should go in mpl proper" this was already a much more positive response than my usual one for most feature requests, which is "this should definitely go in another package" :-) Obviously I may be biased because I plot a lot of e(c)cdfs, but I actually think they are an quite fundamental stats tool which is also slightly tricky to plot properly (not everyone knows about "steps-pre" -- or is it "steps-post"? well one needs to check), for this reason they may be worth considering for inclusion into mpl.
OTOH, having this elsewhere as a first step doesn't preclude later inclusion into mpl, and may be useful to iron out the API.

@mbolt01
Copy link

@mbolt01 mbolt01 commented Feb 21, 2020 •

Looks like it might exist in the statsmodels package already? https://www.statsmodels.org/dev/_modules/statsmodels/distributions/empirical_distribution.html
https://www.statsmodels.org/dev/generated/statsmodels.distributions.empirical_distribution.ECDF.html

I found this via the wikipedia page https://en.wikipedia.org/wiki/Empirical_distribution_function, but am not too familiar with its use myself, but on quick glance it seems to be what is being discussed.

@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 21, 2020

As discussed above, the tricky part is more the plotting than the computation (IMO).

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 21, 2020

Looks like it might exist in the statsmodels package already? https://www.statsmodels.org/dev/_modules/statsmodels/distributions/empirical_distribution.html

It is the same thing (and I am aware of it), but it has the same problem as a potential SciPy suggested earlier: It only returns the data points and it is not straightforward to properly plot those.

@jklymak
Copy link
Contributor

@jklymak jklymak commented Feb 21, 2020

statsmodel has plotting, so certainly contributing the plotting interface to them might make sense.

Long-term there is discussion of matplotlib moving to a sub-library based model, so that different types of plots can live in their own sub library (i.e. stats would get violin, box plot, and maybe this one; signal would get the various spectral plotting methods; etc), but those plans are a ways off.

However, if this is truly standard and requires a bit of fiddling to get right, then maybe its worth including now if someone wants to write it up. Conversely, an example on our page may be enough guidance?

@Phlya
Copy link
Contributor

@Phlya Phlya commented Feb 25, 2020

I agree, I had the same thoughts that the hist-based ECDF plotting is kinda weird and had to write my own function - which was strange for such a basic statistical plot type. I think matplotlib would benefit from having ECDF plotting built-in.

@tacaswell
Copy link
Member

@tacaswell tacaswell commented Feb 25, 2020

It only returns the data points and it is not straightforward to properly plot those.

Is the compromise path here to add a plot_ecdf function to Matplotlib that takes in the pre-computed ECDF and bakes in th assumptions needed to plot in right?

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 25, 2020

It only returns the data points and it is not straightforward to properly plot those.

Is the compromise path here to add a plot_ecdf function to Matplotlib that takes in the pre-computed ECDF and bakes in th assumptions needed to plot in right?

I don’t see how. The pre-computations of how you compute the ECDF and plot it have to match. There is one way to do it for "steps-pre" and one for "steps-post". Moreover, this is overcomplicated to the point that it has almost zero advantage over the status quo.

@tacaswell
Copy link
Member

@tacaswell tacaswell commented Feb 26, 2020

so may take away from this conversation is:

  • this is a basic plot that people who use it use it all the time
  • this is not dependent on any particular data structures
  • the computation is not complicated or subtle
  • but there are choices in how it is done that needs to be carefully coupled to how it is plotted
  • I do not have domain expertise on this

I am going to delegate responsibility for this feature (👍 /👎 on if the feature should go in or not, API choices, docs, etc) to @anntzer (but if it goes in, the final PR is still the standard 2 reviewer).

@tacaswell tacaswell added this to the v3.3.0 milestone Feb 26, 2020
@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 26, 2020

@Wrzlprmft @Phlya given that you use this kind of plots, can you comment on the implementation I propose?

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 26, 2020

@Wrzlprmft @Phlya given that you use this kind of plots, can you comment on the implementation I propose?

  • There should at least be an option to remove redundant points (see my implementation). For example np.random.randint(0,60,10000000) (think of the age distribution of 10 million people), takes considerably longer to plot. However, there seems to be an automatic removal of redundant points in the exporting backends, avoiding bigger files. One could even argue to make this the default since it does not need relevantly more computation and memory than the other operations (sorting and masking).

  • Rename swapaxes to horizontal in analogy to hist.

  • [data[0], *data] could be a bottleneck/memory issue for big data sets, since it forces them into a list.

  • The separation of the helper and the main function seems overcomplicated and error-prone. The helper should only take data and weights as arguments and be the only one to directly use those.

  • The setting of labels (and the name of the argument that does this) seems to be in conflict with other Matplotlib functions.

  • Using drawstyle as a keyword argument (to plot_ecdf) results in an unhelpful error message: “plot() got multiple values for keyword argument 'drawstyle'”. (See my implementation for an alternative.)

  • I don’t know if Matplotlib has a general policy to what extent nans or missing data should be handled. Right now, hist does not seem to properly support them and your implementation does not support masked arrays. This is all nice to support, but of course comes at maintenance costs and risks of errors.

  • Multidimensional arrays work, but probably not as expected by everybody. This should at least throw a warning.

  • I am not sure whether (1+np.arange(n))/n really is free from floating-point errors, but np.linspace(1/n,1,n) should be.

@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 26, 2020 •

There should at least be an option to remove redundant points (see my implementation). For example np.random.randint(0,60,10000000) (think of the age distribution of 10 million people), takes considerably longer to plot. However, there seems to be an automatic removal of redundant points in the exporting backends, avoiding bigger files. One could even argue to make this the default since it does not need relevantly more computation and memory than the other operations (sorting and masking).

I agree it takes longer but I'm quite curious why; Line2D and the backends have code to get rid of the duplicates (really, to merge straight lines), so I think this should be handled there...

Rename swapaxes to horizontal in analogy to hist.

Agreed, this was just a copypaste of what I have in my utils.py.

[data[0], *data] could be a bottleneck/memory issue for big data sets, since it forces them into a list.

Probably should be replaced with np.insert(data, 0, data[0]) (things are going to be cast into a numpy array at some point anyways).

The separation of the helper and the main function seems overcomplicated and error-prone. The helper should only take data and weights as arguments and be the only one to directly use those.

Likely this would be easier after removal of label (and thus swapaxes as well). I think factoring out the common parts between horizontal/vertical and ecdf/eccdf is still valuable.

The setting of labels (and the name of the argument that does this) seems to be in conflict with other Matplotlib functions.

Yes, this was just for my personal use, they would be removed.

Using drawstyle as a keyword argument (to plot_ecdf) results in an unhelpful error message: “plot() got multiple values for keyword argument 'drawstyle'”. (See my implementation for an alternative.)

Yup, needs a check.

I don’t know if Matplotlib has a general policy to what extent nans or missing data should be handled. Right now, hist does not seem to properly support them and your implementation does not support masked arrays. This is all nice to support, but of course comes at maintenance costs and risks of errors.

I think we should support neither (and thus remove the nan-handling) for consistency with hist().

Multidimensional arrays work, but probably not as expected by everybody. This should at least throw a warning.

Agreed this should just throw.

I am not sure whether (1+np.arange(n))/n really is free from floating-point errors, but np.linspace(1/n,1,n) should be.

I think both are fine. 1 + np.arange(n) is an integer array so there's no FP errors involved, AFAICT.

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 26, 2020

I agree it takes longer but I'm quite curious why; Line2D and the backends have code to get rid of the duplicates (really, to merge straight lines), so I think this should be handled there...

Maybe it is handled there, but it takes longer because these routines are general, while for ECDFs we can optimise for step functions with sorted abscissae.

I think factoring out the common parts between horizontal/vertical and ecdf/eccdf is still valuable.

Indeed.

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 26, 2020

@anntzer: Some further thoughts:

  • It probably makes sense to set the range of the value axis to [0,1] (unless set before), just like hist sets the minimum of the value axis to 0. Apart from anything else making little sense for any application I can think of, this also reduces the ugliness caused by the ECDF not starting at (−∞,0) and ending at (∞,1).

  • Does anybody use “absolute CDFs”, i.e., like hist(data,cumulative=True,density=False) and if yes, how are they named and should they be supported?

@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 26, 2020

It probably makes sense to set the range of the value axis to [0,1] (unless set before), just like hist sets the minimum of the value axis to 0. Apart from anything else making little sense for any application I can think of, this also reduces the ugliness caused by the ECDF not starting at (−∞,0) and ending at (∞,1).

For me the main reason to keep them is to make the underlying data info possibly more valuable, e.g. so that https://mplcursors.readthedocs.io/en/stable/ (my package) may be able to provide "smarter" cursor labels. But I agree this should only be done if the performance cost is not too high.

Does anybody use “absolute CDFs”, i.e., like hist(data,cumulative=True,density=False) and if yes, how are they named and should they be supported?

At least I don't use them.

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 27, 2020

It probably makes sense to set the range of the value axis to [0,1] (unless set before), just like hist sets the minimum of the value axis to 0. Apart from anything else making little sense for any application I can think of, this also reduces the ugliness caused by the ECDF not starting at (−∞,0) and ending at (∞,1).

For me the main reason to keep them is to make the underlying data info possibly more valuable, e.g. so that https://mplcursors.readthedocs.io/en/stable/ (my package) may be able to provide "smarter" cursor labels. But I agree this should only be done if the performance cost is not too high.

I fail to understand this. My point was about having an implied set_ylim(0,1) (or similar) in the ECDF method. What do you want to keep? What is the performance cost? Are you by any chance referring to the redundant points?

@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 27, 2020 •

Sorry, I misread you, yes, I was referring to redundant points. Forget what I wrote :)

For the limits I think it would make sense to add sticky values to 0/1, which should have the same effect as putting the ylims to 0/1, except that things would also "just work" in log or logit scale.


Do you have a use case for non-normalized cdfs? I just realized they could be easily supported in the API by not normalizing weights (so you'd just pass weights=np.ones_like(data) for that case).

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 27, 2020 •

For the limits I think it would make sense to add sticky values to 0/1, which should have the same effect as putting the ylims to 0/1, except that things would also "just work" in log or logit scale.

Sounds good to me, if this is what you are referring to.

Do you have a use case for non-normalized cdfs? I just realized they could be easily supported in the API by not normalizing weights (so you'd just pass weights=np.ones_like(data) for that case).

Sure, but then explicit is better than implicit. It’s certainly not a big problem to implement (also see my implementation), though handling limits, last points, etc. may be a bit tedious. On the other hand, if nobody ever uses those, what’s the point? Anyway, let’s find out whether the latter is the case.


On another note, I stumbled upon this tutorial, which should arguably be retired should this be realised.

@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 27, 2020 •

Sounds good to me, if this is what you are referring to.

Yes.

We can forget about the nonnormalized case for now. But what do we do if weights don't sum to 1, then?

I agree the tutorial will need a rewrite.

Or do we want to further shoehorn this into the hist() API? ;-) (ugh)

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 27, 2020

But what do we do if weights don't sum to 1, then?

I vote to normalise them under the hood and document this (unless the ECDF is not normalised):

  • Otherwise we can only raise an exception, which in turn would cause unnecessary issues with rounding errors and similar.
  • This way, the new method would behave like hist with cumulative=True, density=True, which seems to me like a reasonable thing to aspire.
@anntzer
Copy link
Contributor

@anntzer anntzer commented Feb 27, 2020

Well, I was thinking we could put this as hist(data, bins="ecdf", cumulative=True, density=True) then :)

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 27, 2020

Well, I was thinking we could put this as hist(data, bins="ecdf", cumulative=True, density=True) then :)

If hist(data, bins="ecdf") provides a bin-free histogram, I am all in.

@jklymak
Copy link
Contributor

@jklymak jklymak commented Feb 27, 2020

I think this is different enough from hist that it should be its own method.

@Wrzlprmft
Copy link
Author

@Wrzlprmft Wrzlprmft commented Feb 27, 2020

I think this is different enough from hist that it should be its own method.

Just to avoid Poe’s Law: Note the smilies and other subtle signs of irony.

@story645
Copy link
Member

@story645 story645 commented Feb 28, 2020

NIST has a handbook of statistical methods that might work as the authoritative reference for implementing ECDF and other functions like it.
https://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/ecdfplot.htm

@tacaswell
Copy link
Member

@tacaswell tacaswell commented May 7, 2020

Pushed to 3.4 as this is to going to get sorted and implemented in the next few days.

@mwaskom
Copy link

@mwaskom mwaskom commented Jun 15, 2020

Of note, ECDF is going into seaborn: mwaskom/seaborn#2141

I think they are simple and useful enough to live in matplotlib too, so I don't mean to dampen enthusiasm here. But interested parties should feel free to weigh in on the seaborn PR.

@QuLogic QuLogic modified the milestones: v3.4.0, v3.5.0 Jan 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
9 participants