Repository navigation
Closed
Milestone
Description
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);Reacted by Jarosław Rzeszótko
Reacted by Jarosław Rzeszótko
Activity
anntzer commentedon 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:
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 commentedon Feb 20, 2020
Matplotlib already has things like
histandacorr, 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 commentedon 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 commentedon 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 commentedon Feb 20, 2020
And despite the responses mostly being negative, I appreciate that you opened this issue!
Wrzlprmft commentedon Feb 20, 2020
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 toplotas 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-prevs.steps-post), which is nothing most users of this function want to think about.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.
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 commentedon Feb 20, 2020
In Matlab ecdf is part of the stats toolbox. Same with r.
anntzer commentedon 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 commentedon Feb 21, 2020
Looks like it might exist in the
statsmodelspackage already? https://www.statsmodels.org/dev/_modules/statsmodels/distributions/empirical_distribution.htmlhttps://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 commentedon Feb 21, 2020
As discussed above, the tricky part is more the plotting than the computation (IMO).
Wrzlprmft commentedon Feb 21, 2020
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 commentedon Feb 21, 2020
statsmodelhas 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.
statswould get violin, box plot, and maybe this one;signalwould 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 commentedon 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 commentedon Feb 25, 2020
Is the compromise path here to add a
plot_ecdffunction to Matplotlib that takes in the pre-computed ECDF and bakes in th assumptions needed to plot in right?Wrzlprmft commentedon Feb 25, 2020
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.20 remaining items
tacaswell commentedon May 7, 2020
Pushed to 3.4 as this is to going to get sorted and implemented in the next few days.
mwaskom commentedon 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.
jklymak commentedon Nov 13, 2021
@anntzer the consensus seems to be to try and add this? Any thoughts of coming back to it?
anntzer commentedon Nov 14, 2021
Yes, I just need to find some time for this to bubble back to the top of my stack :-) but thanks for the ping.