question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

specifying bins argument of sns.histplot as bin edges of a datetime type

See original GitHub issue

seaborn version : ‘0.11.0’

I can produce a histogram of dates using bins=number of bins with no problem: sns.histplot(data=df['visit_date'],bins=20 I cannot seem to specify the bin edges as a date type: sns.histplot(data=df['visit_date'],bins = np.arange("2000", "2020", dtype="datetime64[D]")

In [57]: sns.histplot(data=df['visit_date'],bins= np.arange("2000", "2020", dtype="datetime64[D]"))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-57-e11b4de76ee6> in <module>
----> 1 sns.histplot(data=df['visit_date'],bins= np.arange("2000", "2020", dtype="datetime64[D]"))

/data2/yelena/miniconda3/lib/python3.7/site-packages/seaborn/distributions.py in histplot(data, x, y, hue, weights, stat, bins, binwidth, binrange, discrete, cumulative, common_bins, common_norm, multiple, element, fill, shrink, kde, kde_kws, line_kws, thresh, pthresh, pmax, cbar, cbar_ax, cbar_kws, palette, hue_order, hue_norm, color, log_scale, legend, ax, **kwargs)
   1433             estimate_kws=estimate_kws,
   1434             line_kws=line_kws,
-> 1435             **kwargs,
   1436         )
   1437 

/data2/yelena/miniconda3/lib/python3.7/site-packages/seaborn/distributions.py in plot_univariate_histogram(self, multiple, element, fill, common_norm, common_bins, shrink, kde, kde_kws, color, legend, line_kws, estimate_kws, **plot_kws)
    434 
    435             # Do the histogram computation
--> 436             heights, edges = estimator(observations, weights=weights)
    437 
    438             # Rescale the smoothed curve to match the histogram

/data2/yelena/miniconda3/lib/python3.7/site-packages/seaborn/_statistics.py in __call__(self, x1, x2, weights)
    369         """Count the occurrances in each bin, maybe normalize."""
    370         if x2 is None:
--> 371             return self._eval_univariate(x1, weights)
    372         else:
    373             return self._eval_bivariate(x1, x2, weights)

/data2/yelena/miniconda3/lib/python3.7/site-packages/seaborn/_statistics.py in _eval_univariate(self, x, weights)
    350         density = self.stat == "density"
    351         hist, _ = np.histogram(
--> 352             x, bin_edges, weights=weights, density=density,
    353         )
    354 

<__array_function__ internals> in histogram(*args, **kwargs)

/data2/yelena/miniconda3/lib/python3.7/site-packages/numpy/lib/histograms.py in histogram(a, bins, range, normed, weights, density)
    876             for i in _range(0, len(a), BLOCK):
    877                 sa = np.sort(a[i:i+BLOCK])
--> 878                 cum_n += _search_sorted_inclusive(sa, bin_edges)
    879         else:
    880             zero = np.zeros(1, dtype=ntype)

/data2/yelena/miniconda3/lib/python3.7/site-packages/numpy/lib/histograms.py in _search_sorted_inclusive(a, v)
    459     """
    460     return np.concatenate((
--> 461         a.searchsorted(v[:-1], 'left'),
    462         a.searchsorted(v[-1:], 'right')
    463     ))

TypeError: invalid type promotion

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
mwaskomcommented, Jan 27, 2021

Thanks!

This happens because at the time the histogram is computed, the datetime data are represented as numeric values, but bins gets passed straight through to numpy, and so you end up with numeric values and datetime bins and it does not make sense.

In principle, this is not difficult to solve, but doing so will be annoying in that bins is a very flexible argument, and most specifications (e.g. a number, a string) should not have any conversion happen.

BTW, I imagine that we’ll run into the same problem with binwidth and binrange.

Fortunately it’s easy to workaround in user-space by doing:

sns.histplot(data=dffake.date, bins=mpl.dates.date2num(bins))
0reactions
mwaskomcommented, Sep 14, 2022

While the workaround here isn’t extremely obvious, I think it’s pretty simple once you know what to do, and it looks like supporting bins-with-original-units would be rather complex. So I think I’m going to close with no action for now.

Read more comments on GitHub >

github_iconTop Results From Across the Web

seaborn.histplot — seaborn 0.12.1 documentation - PyData |
This function allows you to specify bins in several different ways, such as by setting the total number of bins to use, the...
Read more >
How to align histogram bin edges in overlaid plots
histplot API will correctly align the bin edges of the various categories, when using the hue parameter. To use this option, your columns...
Read more >
How to Make a Seaborn Histogram - Sharp Sight
This tutorial explains how to create a Seaborn histogram. It explains the syntax of sns.histplot and shows clear examples.
Read more >
Chapter 4. Visualization with Matplotlib - O'Reilly
plot is that it can be used to create scatter plots where the properties of each individual point (size, face color, edge color,...
Read more >
EDA Basic Plotting Interpretation-Haberman Cancer - Kaggle
Python · Haberman's Survival Data Set ... has no attribute 'histplot' # First verify version with print(sns. ... <class 'pandas.core.frame.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found