Let’s take a look at how we can generate plots in python. matplotlib is a particularly powerful library that we can use to generate visualisations. Let’s see how this works using a couple of examples.
In a previoustutorial, we saw how we can generate probability plots using R. Let’s see how we can generate such an analysis in Python.
Probability AnalysisThis is just a brief overview on how we can generate cumulative binomial probabilities, which we will then plot using matplotlib.
Let’s import the numpy and pandas libraries.
import numpy as np import pandas as pdWe now define our probabilities l , m , and n :
l=0.02 m=0.04 n=0.06Next, we set 100 values for p (or our number of trials) and define our probability formulas:
p=np.arange(0, 100, 1) h=1 - l j=1 - m k=1 - n q=1-(h**p) r=1-(j**p) s=1-(k**p)Now, let’s plot our results!
Basic Plotting in Python import matplotlib.pyplot as plt plt.plot(q,'r--',r,'b--',s,'g--') plt.title("Probability Curves") plt.show()
You can see that we are plotting q, r, and s on the one plot. Moreover, we are specifying red, blue and green lines with ‘r ‘, ‘b ‘, and ‘g ‘ respectively.
Let’s take a look at another example.
matplotlib: Line and Pie ChartsWe will use matplotlib to generate a series of random numbers, and plot line and pie charts illustrating our results.
import numpy as np import matplotlib.pyplot as plt a=abs(np.random.randn(100)) b=abs(np.random.randn(100)) p=np.arange(0, 100, 1) cuma=np.cumsum(a) cumb=np.cumsum(b)From the above, you can see that we have generated 100 random numbers for the variables a and b , and 100 values for p .
Now, we will plot the cumulative sums for a and b (cuma and cumb) , appending a legend and a title to our plot.
ax=plt.subplot(111) ax.plot(p,cuma,color="red",label='values') ax.plot(p,cumb,color="green",label='values') plt.title("Values") ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), shadow=True, ncol=2) plt.show()
Now, we will obtain the sum of a and b , and generate a pie chart using this information.
#Pie Chart suma=np.sum(a) sumb=np.sum(b) total=suma+sumb c=suma/total d=sumb/total slices_letters=[c,d] categories = ['c', 'd'] colors = ['g', 'r'] plt.pie(slices_letters, labels=categories, colors=colors, startangle=90, autopct='%.1f%%') plt.title('Pie Chart') plt.show()
You can see that the sums of a and b are now plotted in our pie chart in percentage terms, along with the appropriate labels appended to the graph.
ConclusionIn this tutorial, you have learned how to generate plots in Python using matplotlib, as well as how we can use numpy to do some basic data manipulation. Feel free to leave any questions in the comments below.