Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib histograms (basic questions)

I am trying to plot a simple histogram using matplotlib. I have for example (I will in practice be using different distance functions)

import matplotlib.pyplot as plt
import numpy as np
import itertools


def hamdist(str1, str2):
    """Count the # of differences between equal length strings str1 and str2"""
    if (len(str1) != len(str2)):
        print str1, str2, "Length mismatch bozo!!!!!!"
    diffs = 0
    for ch1, ch2 in itertools.izip(str1, str2):
        if ch1 != ch2:
            diffs += 1
    return diffs

n = 10
bins=np.arange(0,n+2,1)
hamdists = []
for str1 in itertools.product('01', repeat = n):
    for str2 in itertools.product('01', repeat = n):
        hamdists.append(hamdist(str1, str2))
plt.hist(hamdists, bins=bins)
plt.show()

I get a histogram that looks like this.

histogram

How do I do the following?

  1. Change the x-axis so that the last bar counts the number for x = 10. If I simply change to bins=np.arange(0,11,1) this cuts off the value for x = 10.
  2. Label every point in the x-axis
  3. Move the x-axis labels to be under the middle of the bars and not at the start of them as they are now.
like image 661
marshall Avatar asked May 02 '13 08:05

marshall


People also ask

What does a histogram show in MatPlotLib?

It is a graph showing the number of observations within each given interval.

What is the method used in MatPlotLib to generate histogram?

The matplotlib. pyplot. hist() function is used to compute and create histogram of x.

How do you plot a histogram with different variables in Python?

plt. hist() method is used multiple times to create a figure of three overlapping histograms. we adjust opacity, color, and number of bins as needed. Three different columns from the data frame are taken as data for the histograms.


1 Answers

Your first and third points can be solved by setting the align keyword of the histogram function (which defaults to 'mid', the center of the bin). The second by manually setting the xticks.

See:

fig, ax = plt.subplots(1,1)

ax.hist(hamdists, bins=bins, align='left')
ax.set_xticks(bins[:-1])

enter image description here

like image 113
Rutger Kassies Avatar answered Sep 21 '22 11:09

Rutger Kassies