Python Forum
histogram with matplotlib
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
histogram with matplotlib
#1
Hi everyone,

I have tried the following code from the matplotlib tutorial.

https://matplotlib.org/gallery/statistic...tures.html

in my computer, but I don't get the same Gaussian fit by running the python code on my computer. I only get a straight line :-(

Can anyone tell me why?

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

np.random.seed(19680801)

# example data
mu = 100  # mean of distribution
sigma = 15  # standard deviation of distribution
x = mu + sigma * np.random.randn(437)

num_bins = 50

fig, ax = plt.subplots()

# the histogram of the data
n, bins, patches = ax.hist(x, num_bins, density=1)

# add a 'best fit' line
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()

#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions and methods is shown in this example:

matplotlib.axes.Axes.hist
matplotlib.axes.Axes.set_title
matplotlib.axes.Axes.set_xlabel
matplotlib.axes.Axes.set_ylabel
Reply
#2
I just tried your code and everything works fine. I get the same figure as from the link above.
Reply
#3
This is what I get :-/

https://ufile.io/ee7wf

the code compiles perfectly. I wonder if something in my python installation is wrong, and how to check.
Reply
#4
I have tried your code (copied from your post, not the one from matplotlib) and the result is the expected one: a nice histogram and a normal curve.

If you see a line that means that you have at least a correct matplotlib backend so the error must be something not so obvious. You can enter with the debugger or add some prints to the variables to understand what's happening.

Have you tried to do an easy plot:
import matplotlib.pyplot as plt

from matplotlib.patches import Rectangle

f = plt.figure()
ax = f.add_subplot(1, 1, 1)
ax.plot([1, -2, 4, -8])

r = Rectangle((0, 2), 2, 1, color='orange')
ax.add_patch(r)

plt.show()
If it does not work either I suspect it is a problem with your installation.

Ok, with the image I see it, you are using python2, so the division is truncating to integer.
This:
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
Only produces the expected result in python 3, for python 2 you need to force working with float numbers:
y = ((1.0 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1.0 / sigma * (bins - mu))**2))
But nevertheless I recommend you to use python 3 if you are learning.
Reply
#5
Thank you so much killerrex !!!

How do I force in terminal to use python 3 instead of python 2?
Reply
#6
In linux depends of your distribution. In some of them like arch the default is already python3, for others you can check it with:
Output:
$> ls -l /usr/bin/python
But do not change the default python yourself or you can easily finish with a broken system. Just use "python3" to run your scripts and the shebang "#!/usr/bin/env python3".

For windows I think is not so easy. Possibly the easiest thing is to only install python3 (either from the official page or from anaconda) as in windows python is not needed by the OS.
But it is easy that someone in the forum knows better how to choose the default python version in windows.
Reply
#7
I have a mac (OSX) so I usually write the scripts in this program called TextWrangler, then I just select "run in terminal" and it runs it for me.

When I type

$> ln -s /usr/bin/python

it gives

ln: ./python: File exists

when I type

$ python --version

it gives

Python 2.7.15

:-(
Reply
#8
I used these instructions to upgrade to python3 and python35 in my mac !
https://machinelearningmastery.com/insta...-learning/

it worked very well :-)
Reply
#9
Help again !

I am using this python script to plot some nice error bars

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.errorbar(x, y_sin, 0.2)
plt.errorbar(x, y_cos, 0.2)
plt.show()
and I don't get the nice error bars as they do: like this "I", I only get vertical lines
What could the problem be now? I am using python35 :/
Reply
#10
Try:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
#---| Style
plt.style.use('seaborn')
mpl.rcParams['figure.figsize'] = (7,4)
 
x = np.linspace(0, 2 * np.pi)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.errorbar(x, y_sin, yerr=0.2, uplims=True)
plt.errorbar(x, y_cos, yerr=0.2, uplims=True)
plt.show()
[Image: Uy50Uf.jpg]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to fit a 2D histogram like in ROOT? Zandar 2 4,110 Aug-06-2019, 03:01 PM
Last Post: Zandar
  histogram error alyssaantarctica 1 3,752 Jul-09-2018, 10:46 PM
Last Post: Larz60+
  Plot Probability Density of an Histogram Python_TLS 1 2,877 Jun-28-2018, 06:19 AM
Last Post: scidam
  Help creating a histogram using an array rubadub 0 2,179 Apr-17-2018, 08:57 PM
Last Post: rubadub
  Histogram help dandatadan 1 2,540 Nov-25-2017, 06:07 AM
Last Post: heiner55
  mcerp: error while plotting a histogram rakhmadiev 2 4,529 Apr-02-2017, 09:08 PM
Last Post: rakhmadiev
  plotting histogram vvv 1 3,286 Mar-10-2017, 11:47 PM
Last Post: zivoni

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020