## How plot a histogram of floating points

This is the place for queries that don't fit in any of the other categories.

### How plot a histogram of floating points

Hi,

I am trying to plot a histogram of these values. A have a list with floating points. x=[1,2,3,4,4.5,4.5,5,7]
I use this code:
Code: Select all
x=[1,2,3,4,4.5,4.5,5,7]
n = len(x)
y = range(n+2)

hist, bins = numpy.histogram(x, bins=y)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)

How can i use this code to plot floating points? In this case I want a bar at 4.5, which is two high. But I only get a bar at 4, which is three high. Because the histogram doesn't differ between 4 and 4.5. This pictures shows what i mean.
Last edited by stranac on Fri May 09, 2014 7:06 am, edited 1 time in total.
Reason: First post lock.
Kruemel49

Posts: 1
Joined: Fri May 09, 2014 6:46 am

### Re: How plot a histogram of floating points

A histogram is not the same thing as a frequency bar chart. If all you want is a bar for each number in your data with the height of the bar representing the frequency of the number, then you can do this:

Code: Select all
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt

x=[1,2,3,4,4.5,4.5,5,7]

counts = Counter(x)
heights = [counts[num] for num in x]

plt.bar(x, heights, align='center', width=.3)
plt.xticks(x)

plt.show()

bar_freq.png (2.93 KiB) Viewed 408 times

If you don't specify the xticks, then plt uses some defaults based on the range of the x data.

A histogram whose ranges/bins are extremely tiny would result in each of your x values falling in a separate range/bin, so you could get a similar bar chart that way.
7stud

Posts: 106
Joined: Wed Apr 02, 2014 2:36 am