Skip to content

Feature request: proper ECDF #16561

Closed

Description

@Wrzlprmft

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);

Activity

  1. anntzer commented on Feb 20, 2020

    @anntzer
    Contributor

    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.

  2. Wrzlprmft commented on Feb 20, 2020

    @Wrzlprmft
    Author

    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.

  3. jklymak commented on Feb 20, 2020

    @jklymak
    Member

    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)

  4. tacaswell commented on Feb 20, 2020

    @tacaswell
    Member

    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.

  5. tacaswell commented on Feb 20, 2020

    @tacaswell
    Member

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

  6. Wrzlprmft commented on Feb 20, 2020

    @Wrzlprmft
    Author

    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.

  7. jklymak commented on Feb 20, 2020

    @jklymak
    Member

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

  8. anntzer commented on Feb 20, 2020

    @anntzer
    Contributor

    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.

  9. anntzer commented on Feb 21, 2020

    @anntzer
    Contributor

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

  10. Wrzlprmft commented on Feb 21, 2020

    @Wrzlprmft
    Author

    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.

  11. jklymak commented on Feb 21, 2020

    @jklymak
    Member

    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?

  12. Phlya commented on Feb 25, 2020

    @Phlya
    Contributor

    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.

  13. tacaswell commented on Feb 25, 2020

    @tacaswell
    Member

    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?

  14. Wrzlprmft commented on Feb 25, 2020

    @Wrzlprmft
    Author

    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.

  15. 20 remaining items

  16. added this to the v3.4.0 milestone on May 7, 2020
  17. tacaswell commented on May 7, 2020

    @tacaswell
    Member

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

  18. mwaskom commented on Jun 15, 2020

    @mwaskom

    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.

  19. modified the milestones: v3.4.0, v3.5.0 on Jan 27, 2021
  20. modified the milestones: v3.5.0, v3.6.0 on Sep 25, 2021
  21. jklymak commented on Nov 13, 2021

    @jklymak
    Member

    @anntzer the consensus seems to be to try and add this? Any thoughts of coming back to it?

  22. anntzer commented on Nov 14, 2021

    @anntzer
    Contributor

    Yes, I just need to find some time for this to bubble back to the top of my stack :-) but thanks for the ping.

  23. modified the milestones: v3.6.0, v3.7.0 on Aug 24, 2022
  24. modified the milestones: v3.7.0, v3.8.0 on Jan 24, 2023
  25. linked a pull request that will close this issueAdd Axes.ecdf() method. #24728on Jan 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions