0

I'm trying to plot this graph in histogram but the graph is drawn not correct. I want the value to be centered on the xticks. I would like this to be done without using numpy nor pandas. How can I succeed?

res = [1,2,3,1,5,4,2,6,3,4,1,2,3,4,1,5,6,1,2,3,4,5] # range 1~6
plt.figure(figsize=[4,4])
plt.hist(x=res)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value',fontsize=15)
plt.ylabel('Frequency',fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.show()

enter image description here

user11398251
  • 31
  • 1
  • 7
  • Does this answer your question? [Matplotlib xticks not lining up with histogram](https://stackoverflow.com/questions/27083051/matplotlib-xticks-not-lining-up-with-histogram) – warped Apr 05 '20 at 09:07

1 Answers1

0

I found that the solution to this question changing default x range in histogram matplotlib

also fixes your problem:


import numpy as np
import matplotlib.pyplot as plt

res = [1,2,3,1,5,4,2,6,3,4,1,2,3,4,1,5,6,1,2,3,4,5]

u, counts = np.unique(res, return_counts=True)

plt.bar(np.arange(len(u)), counts)
plt.xticks(np.arange(len(u)), u)

plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value',fontsize=15)
plt.ylabel('Frequency',fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)

plt.show()

enter image description here

Update: Without numpy:

import matplotlib.pyplot as plt
from collections import Counter
res = [1,2,3,1,5,4,2,6,3,4,1,2,3,4,1,5,6,1,2,3,4,5]

counts = {k: v for k, v in sorted(Counter(res).items(), key=lambda item: item[1])}

u = set(res)

plt.bar(range(len(u)), counts)
plt.xticks(range(len(u)), u)

plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value',fontsize=15)
plt.ylabel('Frequency',fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)

plt.show()
Lydia van Dyke
  • 2,466
  • 3
  • 13
  • 25