Feature request: proper ECDF #16561
Feature request: proper ECDF #16561
Comments
|
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. |
Matplotlib already has things like In some standalone package it will stay obscure and won’t reach most of those who want to use it. |
|
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 |
|
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. |
|
And despite the responses mostly being negative, I appreciate that you opened this issue! |
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
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 ( |
|
In Matlab ecdf is part of the stats toolbox. Same with r. |
|
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. |
|
Looks like it might exist in the 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. |
|
As discussed above, the tricky part is more the plotting than the computation (IMO). |
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. |
|
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. 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? |
|
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. |
Is the compromise path here to add a |
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 |
|
so may take away from this conversation is:
I am going to delegate responsibility for this feature ( |
|
@Wrzlprmft @Phlya given that you use this kind of plots, can you comment on the implementation I propose? |
|
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...
Agreed, this was just a copypaste of what I have in my utils.py.
Probably should be replaced with
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.
Yes, this was just for my personal use, they would be removed.
Yup, needs a check.
I think we should support neither (and thus remove the nan-handling) for consistency with hist().
Agreed this should just throw.
I think both are fine. |
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.
Indeed. |
|
@anntzer: Some further thoughts:
|
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.
At least I don't use them. |
I fail to understand this. My point was about having an implied |
|
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 |
Sounds good to me, if this is what you are referring to.
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. |
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) |
I vote to normalise them under the hood and document this (unless the ECDF is not normalised):
|
|
Well, I was thinking we could put this as |
If |
|
I think this is different enough from |
Just to avoid Poe’s Law: Note the smilies and other subtle signs of irony. |
|
NIST has a handbook of statistical methods that might work as the authoritative reference for implementing ECDF and other functions like it. |
|
Pushed to 3.4 as this is to going to get sorted and implemented in the next few days. |
|
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. |


While the
histmethod allows to plot empirical cumulative distribution functions (ECDFs) with thecumulativeanddensitykeywords, this is far from perfect: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.
The text was updated successfully, but these errors were encountered: