Plot histograms in python with matplotlib

Suppose we have a file theta.dat which has 1000 lines and each line has a angle value. Its first 10 lines are as follows.

100.35766
105.05182
112.56954
119.66241
125.35966
127.44947
125.47673
121.08910
118.00765
117.77907

How to plot a histogram figure in python with matplotlib with the file theta.dat?

We put this file in the home directory, thus the position is ~/theta.dat.
Then , we plot in Enthought Canopy Graphical Environment! One can download and install it in Software Manager. If we open it, the window looks like this.

f0


We then click the Editor icon to open the Editor. Our plotting program is written in the ~/hist.py, which is also put in the home directory. Here is the code.

#=====
#hist.py
#=====
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
theta=[]
with open("~/theta.dat") as f:
for line in f:
    theta.append(float(line))
num_bins = 30
#Plotting the histogram of the data.
# You can set parameters such as range,histtype,facecolor,etc
n,bins, patches = plt.hist(theta, num_bins, range=[0,180], normed = True, histtype='bar',facecolor='none')
#Controling the labels
plt.xlabel(r'$theta$ ($degree$)',fontsize=25)
plt.ylabel(r'$P(theta)$',fontsize=25)
#Show the figure
plt.show()

In the Canopy Eidtor, type in the command to run this program:

In [14]: %run ~/hist.py

run_1

The figure we plotted is as follows.

f1

Here are some additional questions about controlling the parameters.
Q1: How to control the tick spacing in the figure? We can add the module ticker.

import matplotlib.ticker as ticker
ax=plt.axes()
ax.xaxis.set_major_locator(ticker.MultipleLocator(20))
ax.yaxis.set_major_locator(ticker.MultipleLocator(0.002))
#ax.xaxis.set_minor_locator(ticker.MultipleLocator(10) # for minor ticks 

Q2:How to control the tick lable size?

plt.rcParams['xtick.labelsize']= 20
plt.rcParams['ytick.labelsize']= 20

Notes: Set the aspect ratio if we want to specific ratio for the height and width of the figure. The value can be “auto”, “equal”, or any value we want. For example

plt.axes().set_aspect('auto','datalim')

or

plt.axes().set_aspect('15000','datalim')
打赏作者
喜欢这篇文章,打赏犒劳下作者,以此激励作者创作更多!

您的支持将鼓励我们继续创作!

[微信] 扫描二维码打赏

[支付宝] 扫描二维码打赏

发表评论

电子邮件地址不会被公开。