1
$\begingroup$

I'm walking through a course on Seaborn and I'm having trouble understanding how exactly the x_bins parameter in Seaborn's seaborn.regplot() function works.

The documentation has the below:

Bin the x variable into discrete bins and then estimate the central tendency and a confidence interval. This binning only influences how the scatterplot is drawn; the regression is still fit to the original data. This parameter is interpreted either as the number of evenly-sized (not necessary spaced) bins or the positions of the bin centers.

So I understand that when I mention, say, x_bins = 5, seaborn will bin the X-axis such that there is an equal (as much as possible) number of observations in each bin. And if I mention something like sns.regplot(data=mpg, x="weight", y="mpg", x_bins=np.arange(2000, 5500, 250), order=2) (as given in the docs), the numbers are taken to be the bin centres.

My question: what exactly are the bin edges then? For example:

  1. In this figure from the docs, what are the first and second bins? Is it 1500 to some number between 1500 to 2,250?
  2. In this figure (from a DataCamp course), produced through the code below (by specifying the number of bins), is the first bin 0.0 to ~0.25, and the second bin ~0.25 to somewhere under ~0.4?

I'm having trouble understanding the creation of bins and where exactly the point representing the mean is made.

$\endgroup$
1
  • $\begingroup$ Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. $\endgroup$
    – Community Bot
    Commented Jan 16 at 5:32

1 Answer 1

3
$\begingroup$

The code for calculating the bins can be found in the bin_predictor method of the _RegressionPlotter class:

def bin_predictor(self, bins):
    """Discretize a predictor by assigning value to closest bin."""
    x = np.asarray(self.x)
    if np.isscalar(bins):
        percentiles = np.linspace(0, 100, bins + 2)[1:-1]
        bins = np.percentile(x, percentiles)
    else:
        bins = np.ravel(bins)

    dist = np.abs(np.subtract.outer(x, bins))
    x_binned = bins[np.argmin(dist, axis=1)].ravel()

    return x_binned, bins

It determines the center of the bins using np.linspace and np.percentile, after which the distance for each point to the bin centers are calculated. The points are then assigned to the bins with the closest distance.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.