Wednesday, October 15, 2014

MatPlotLib for plottiing data in technical documents

Around two months ago, I came across an awesome tool which we can use to visualize data graphically using various plots. That is a python library called MatPlotLib. Until then, I was relying on GnuPlot for drawing graphs in technical documents which has it's own syntax. However I found MatPlotLib more useful because of the language it comes with. As a Python fan, this is what I was waiting for. Moreover, I think different graphs we draw using MatPlotLib are much more beautiful and attractive than the graphs in GnuPlot.

We can easily install MatPlotLib on Ubuntu using the following command.

sudo apt-get install python-matplotlib

After the installation, we can start plotting data straightaway. Following two
sample python scripts are for drawing a graph and a pie chart. Open your favorite text editor and put the following contents in two files. Save those two files with two names as graph.py and pie_chart.py since they are python scripts. Now, just run those python scripts and it will come up with graphs in a new window. We can save those graphs into different file formats using the save button in this new window.

graph.py file


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
plt.plot(x, x, linestyle="dashed", marker="o")
plt.plot(x, 2 * x, linestyle="dashed", marker="o")
plt.plot(x, 3 * x, linestyle="dashed", marker="o")
plt.plot(x, 4 * x, linestyle="dashed", marker="o")

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

#labels
plt.xlabel("this is X")
plt.ylabel("this is Y")

#title
plt.title("Simple plot")

plt.show()


pie_chart.py file


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import matplotlib.pyplot as plt

# The slices will be ordered and plotted counter-clockwise.
labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True)

# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')

plt.show()



Here is an excellent gallery with so many examples. Happy plotting! :)

No comments:

Post a Comment