1

I am making a histogram but somehow my ticks are not correct. I need that ticks will be in the center of the histogram bars. I was trying to use align="mid" but it didn't help.

Here is my code:

import random
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib.ticker import PercentFormatter

data_trough_min = pd.DataFrame(columns = ['month'])

month = []
for i in range(0,7942):
    n = random.randint(1,12)
    month.append(n)
print(month)
    
data_trough_min['month'] = month

def bins_labels(bins, **kwargs):
    bin_w = (max(bins) - min(bins)) / (len(bins) - 1)
    plt.xticks(np.arange(min(bins)+bin_w/2, max(bins), bin_w), bins, **kwargs)
    plt.xlim(bins[0], bins[-1])


plt.hist(data_trough_min.month, weights=np.zeros_like(data_trough_min.month) + 1. / data_trough_min.month.size, bins=12, histtype='bar', ec='black', density = True,
          rwidth=0.7)
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
bins = range(1,13)
bins_labels(bins, fontsize=20)
plt.xticks(bins,)
plt.grid(axis='y', alpha=0.75)

enter image description here

How can I set up the histogram such that all of the xticks are aligned in the center? I will appreciate any help.

Kateryna Lubyk
  • 165
  • 1
  • 10
  • 1
    Hope this solves your issue https://stackoverflow.com/questions/23246125/how-to-center-labels-in-histogram-plot – abhi Jun 17 '21 at 14:38
  • Yes I was actually using that example, but I think when I use 'weights' it is not working well – Kateryna Lubyk Jun 17 '21 at 14:59
  • 1
    You're using continuous bins for a discrete histogram. Seaborn usually is easier to use in these situations. – JohanC Jun 17 '21 at 18:11

0 Answers0