Python : Matplotlib

Matplotlib is a Python library used to create charts and graphs.

Installation
$ sudo python3.6 -m pip install pandas
Simple Line plot
import codecademylib  
from matplotlib import pyplot as plt

days = [0, 1, 2, 3, 4,5,6]  
money_spent = [10, 12, 12, 10, 14,22,24]  
plt.plot(days, money_spent)  
plt.show()  

multiple line plots displayed on the same set of axes.

import codecademylib  
from matplotlib import pyplot as plt

time = [0, 1, 2, 3, 4]  
revenue = [200, 400, 650, 800, 850]  
costs = [150, 500, 550, 550, 560]

plt.plot(time, revenue)  
plt.plot(time, costs)  
plt.show()  

Plot options

import codecademylib  
from matplotlib import pyplot as plt

time = [0, 1, 2, 3, 4]  
revenue = [200, 400, 650, 800, 850]  
costs = [150, 500, 550, 550, 560]

plt.plot(time,revenue,color='purple',linestyle='--')  
# marker='o' is circle; s is squar , * is star
plt.plot(time,costs,color='#82edc9',marker='s')  
plt.show()  
special

zoom in and zoom out

# first wto are x coordinates and last two and y coordinates
plt.axis([0, 12, 2900, 3100])  
#Labelling the axis
plt.xlabel('Time of day')  
plt.ylabel('Happiness Rating (out of 10)')  
plt.title('My Self-Reported Happiness While Awake')  
Creating subplots

he command plt.subplot(2, 3, 4) would create “Subplot 4” from the figure above.

Any plt.plot that comes after plt.subplot will create a line plot in the specified subplot

import codecademylib  
from matplotlib import pyplot as plt

x = range(7)  
straight_line = [0, 1, 2, 3, 4, 5, 6]  
parabola = [0, 1, 4, 9, 16, 25, 36]  
cubic = [0, 1, 8, 27, 64, 125, 216]

# Subplot 1
plt.subplot(2, 1, 1)  
plt.plot(x, straight_line)

# Subplot 2
plt.subplot(2, 2, 3)  
plt.plot(x, parabola)

# Subplot 3
plt.subplot(2, 2, 4)  
plt.plot(x, cubic)

plt.subplots_adjust(wspace=0.35, bottom=0.2)

plt.show()  

Adding legends

plt.legend(['Hyrule', 'Kakariko','Gerudo Valley'],loc=8)  
specific ticks
ax.set_xticks([1, 2, 4])  
ax.set_yticks([0.1, 0.6, 0.8])  
ax.set_yticklabels(['10%', '60%', '80%'])  

Working example

from matplotlib import pyplot as plt

month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"]

months = range(12)  
conversion = [0.05, 0.08, 0.18, 0.28, 0.4, 0.66, 0.74, 0.78, 0.8, 0.81, 0.85, 0.85]

plt.xlabel("Months")  
plt.ylabel("Conversion")

plt.plot(months, conversion)

# Your work here
ax = plt.subplot()  
ax.set_xticks(months)  
ax.set_xticklabels(month_names)

ax.set_yticks([0.10, 0.25, 0.5, 0.75])  
ax.set_yticklabels(['10%', '25%', '50%','75%'])

plt.show()  
Axis lables
plt.xlabel('Time of day')  
plt.ylabel('Happiness Rating (out of 10)')  
plt.title('My Self-Reported Happiness While Awake')  
plt.show()  
Showing legends
plt.legend(['parabola', 'cubic'], loc=6)  
plt.show()  
saving fig
plt.figure(figsize=(7, 3))  
plt.plot(years, power_generated)  
plt.savefig('power_generated.png')  
Different type of graphs
bargraph
from matplotlib import pyplot as plt

drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]  
sales =  [91, 76, 56, 66, 52, 27]

plt.bar(range(len(drinks)), sales)

#create your ax object here
ax = plt.subplot()  
ax.set_xticks([0, 1, 2, 3, 4, 5])  
ax.set_xticklabels(["cappuccino", "latte", "chai", "americano", "mocha", "espresso"],  
rotation=90)  
plt.show()  

adjecent bargraph

from matplotlib import pyplot as plt

drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]  
sales1 = [91, 76, 56, 66, 52, 27]  
sales2 = [65, 82, 36, 68, 38, 40]

#Paste the x_values code here
n = 1  # This is our first dataset (out of 2)  
t = 2 # Number of dataset  
d = 6 # Number of sets of bars  
w = 0.8 # Width of each bar  
store1_x = [t*element + w*n for element  
             in range(d)]

plt.bar(store1_x, sales1)  
#Paste the x_values code here
n = 2  # This is our second dataset (out of 2)  
t = 2 # Number of dataset  
d = 6 # Number of sets of bars  
w = 0.8 # Width of each bar  
store2_x = [t*element + w*n for element  
             in range(d)]

plt.bar(store2_x, sales2)

plt.show()  
Creating range
from matplotlib import pyplot as plt

months = range(12)  
month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]  
revenue = [16000, 14000, 17500, 19500, 21500, 21500, 22000, 23000, 20000, 19500, 18000, 16500]

#your work here
ax = plt.subplot()  
ax.set_xticks(months)  
ax.set_xticklabels(month_names)

y_upper = [1.1*i for i in revenue]  
y_lower = [0.9*i for i in revenue]  
plt.fill_between(range(len(months)), y_lower, y_upper, alpha=0.2) 

plt.plot(range(len(months)),revenue)  
plt.show()  
Pie charts
from matplotlib import pyplot as plt

payment_method_names = ["Card Swipe", "Cash", "Apple Pay", "Other"]  
payment_method_freqs = [270, 77, 32, 11]

plt.pie(payment_method_freqs, autopct="%0.1f%%")  
plt.axis('equal')  
plt.legend(payment_method_names)

plt.show()  
Histogram
a = normal(loc=64, scale=2, size=10000)  
b = normal(loc=70, scale=2, size=100000)

plt.hist(a, range=(55, 75), bins=20, alpha=0.5, normed=True)  
plt.hist(b, range=(55, 75), bins=20, alpha=0.5, normed=True)  
plt.show()  

 

Please refer to matplotlib tutorial for further information.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.