Plotting graphs in Python

Plotting graphs in python is quite straightforward. You need to make sure that scipy, numpy and matplotlib libraries are installed. Once installed we can then create a graph quite simply by using the following commands.

1
2
3
4
import matplotlib.pyplot as plt 
plt.plot([1,4,5,7],[3,4,4,5])
plt.ylabel('some numbers')
plt.savefig('graph.png')

Will produce the following plot:

A simple python graph plot

You can do other things with the graph modules, below is a small python script I wrote to calculate the chances of rolling the numbers 2 thru 12 with two dice. We can add axis labels, titles, change the graph style and much more.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import pylab
import random

sampleSize = 1000000

twoDice = []
for i in range(sampleSize):
newValue = random.randint(1,6) + random.randint(1,6)
twoDice.append(newValue)

print("Results for throwing a single die", sampleSize, "times.")
print("Mean of the sample =", pylab.mean(twoDice))
print("Median of the sample =", pylab.median(twoDice))
print("Standard deviation of the sample =", pylab.std(twoDice))

pylab.hist(twoDice, bins = pylab.arange(1.5,12.6,1.0))
pylab.xlabel('Value')
pylab.ylabel('Count')
pylab.savefig('twoDice.png')

Average dice rolls python plot

^