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.
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 : %run ~/hist.py
The figure we plotted is as follows.
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