0

In this post i'm not talking about how bins are calculated.

I want that the first bin gets located at the beginning of the X-axis.

In other words :

I want that the first bin gets located where is the Y-axis

Here is my source code :

import random
import pandas as pd
from matplotlib import pyplot as plt

# Preparing the variable
data = {}
data["values"] = [random.randint(0,50) for x in range(200)]
df = pd.DataFrame(data)

# Creation of the figure
plt.figure(figsize = (10, 10))
plt.subplot(1, 1, 1)

# Creation of my bins
mybins = [-0.5+x for x in range(0,52)]

# Creation of the chart
plt.hist(df["values"], bins=mybins,
         rwidth=0.7, align="mid")

plt.xticks(list(range(0, 51, 5)))

plt.show()

As an output i get this histogram :

histogram_first_bin_shifted

As you can see, there is blank space between the Y-axis and the first bin.

floupinette
  • 150
  • 11
  • 1
    You have 51 values but only 50 bins. – Mr. T Feb 22 '22 at 17:33
  • 1
    Better use `bins=np.arange(df["values"].min()-.5, df["values"].max()+1)` to have nice bins around the discrete values. – JohanC Feb 22 '22 at 17:43
  • 1
    You can also try seaborn's `sns.histplot(...., discrete=True)` to get nice histogram bins. Or `sns.countplot()` as a discrete histogram is basically counting each x-value once. – JohanC Feb 22 '22 at 17:52
  • I don't talk about how bins are calculated. There is a "free space" between the Y Axis and the start of the first bin. This is what i want to avoid. Please review your judgement and reopen my question. – floupinette Feb 23 '22 at 10:48
  • 1
    Try [`plt.margins(x=0.01)`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.margins.html). – Mr. T Feb 23 '22 at 10:54
  • @Mr.T: You provided the right answer. It would really worth reopening this question. – floupinette Feb 23 '22 at 10:59
  • 1
    In this case, the question is a duplicate of this: https://stackoverflow.com/q/42045767/8881141 – Mr. T Feb 23 '22 at 11:11

0 Answers0