In this article, you learn step-by-step Python data visualization library Matplotlib. This is a complete beginer to advance guide, so you don’t need any previous knowledge. After reading this article you understand everything in this library.
Keep reading
Now import this library into your notebook.
import matplotlib.pyplot as plt
Create your first plot
plt.plot();
Congrats, you create your first plot. Now it’s time to learn a few details in the plot, so you understand what this blank plot is 🙆🏻♀️.
See this image below 🔻
This is an anatomy of the matplotlib plot.
Two things to remember —
- Figure — The Figure is all the overall window or page that everything you draw. See the below example so you can understand better.
import matplotlib.pyplot as plt
plt.plot()
2. Axes — In this figure, you add axes. Axes are the area you decide which data point you plot. See the image below.
import matplotlib.pyplot as plt
number_one = [1, 2, 3, 4, 5, 6, 7, 8, 9]
number_two = [10, 20, 30, 40, 50, 60, 70, 80, 90]
plt.plot(number_one, number_two);
Remember — Each plot has two axes [ X and Y ]. In this above example 🔺
X axis is — number_one
Y axis is — number_two
# This is a matplotlib workflow # This is the step every matplotlib workflow -- So keep in mind # 1. Import matplotlib libray in your notebook import matplotlib.pyplot as plt # 2. Create some data Or you have already some data first_number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] secound_number = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] # 3. Setup plot fig, ax = plt.subplots(figsize=(6,6)) # 4. Plot data ax.plot(first_number, secound_number) # 5. Customize plot ax.set(title="This is my numbers plot", xlabel="x-axis", ylabel="y-axis") # 6. Save your plot & show fig.savefig("/content/sample_data")
Now you create your plot [ This is my numbers plot ] and this time learns the code, you used to build this plot.
Let’s learn one by one code meaning.
import matplotlib.pyplot as plt
When you use the matplotlib library, your first job is to import this library in your notebook.
The command is 🔻
import matplotlib
Let’s understand this code
.pyplot as plt
Pyplot is a function Matplotlib library. And Matplotlib is a 2D data visualization library in Python. This library was created by john D. Hunter. Matplotlib is designed to be able to use a Matlab-like interface. One of the main advantages of this library is free and open source. Meaning anyone can use and implement this library.
as plt # plt is shortfrom is pyplot - evrty time we call plt
# this is not necessary you use plt -- you defined short name you remember
Let’s understand this code 🔻
first_number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
secound_number = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
This is our data, we create itself. So we can build a plot.
first_number — X axis
secound_number — Y axis
# 3. Setup plot
fig, ax = plt.subplots(figsize=(6,6))
Subplot( ) is a function in matplotlib, you can draw multiple plots in one figure, figsize ( ) is a method in matplotlib, you can pass an argument, and set your figure size.
See this below code example. So you can understand better.
import matplotlib.pyplot as plt
import numpy as np
# First plot
one_to_ten = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
ten_to_twenty = np.array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
plt.subplot(1, 2, 1)
plt.plot(one_to_ten, ten_to_twenty)
# Secound plot
twenty_to_thirty = np.array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30])
thirty_to_fourty = np.array([31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41])
plt.subplot(1, 2, 2)
plt.plot(twenty_to_thirty, thirty_to_fourty)
plt.show()
Matplotlib is built on NumPy arrays. So in this section, we learn the most common type of plot in using NumPy arrays.
In this section, I cover this topic.
Line
Scatter
Bar
Histogram
Pie
Subplots ( )
Keep reading
Now first import import NumPy library
import numpy as np
But before learning line charts. First, learn Matplotlib Marker, so you can understand better every plot in Matplotlib library.
Matplotlib Marker
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 12])
plt.plot(point_y, marker = 'o')
plt.show()
Marker meaning you — You mark something in your plot,
In this example, I am marking [ 2, 4, 8, 12 ] — see the image above, so you can understand better.
You can use keyword marker mark points.
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 12])
plt.plot(point_y, marker = '*');
Here is a list of some of the marker reference, you can try. Now it’s time to customize our plot.
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, 'o:r')
plt.show()
Understand this code 👇🏻
plt.plot(point_y, 'o:r') # o is a mareker and r is a red argumet we pass
Let’s now another, but this time Green
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, 'o:g')
plt.show()
Here are some of the color references in Marker —
‘r’ — Red🔴
‘g’ — Green🟢
‘b’ — Blue🔵
‘y’ — Yellow🟡
‘k’ — Black⚫
Change Marker Size In Matplotlib
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([3, 8, 1, 10])
plt.plot(point_y, marker = 'o', ms = 21)
plt.show()
Now it’s time to understand code🔻
plt.plot(point_y, marker = 'o', ms = 21) # ms is short for — Markersize
Change marker size in green plot above example. 👆🏻🟢
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, 'o:g', ms = 21)
plt.show()
Draw Marker Edge Color Matplotlib
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 6, 1, 10])
plt.plot(point_y, marker = 'o', ms = 20, mec = 'r')
plt.show()
Understand above code.👆🏻
plt.plot(point_y, marker = 'o', ms = 20, mec = 'r')
marker — Where we mark our plot
ms — Marker size, in this example, I use size 20.
mec — The marker edge color is short from mec. In this case, above example, we use red as our marker edge color.
Change Marker Face Color Matplotlib
In this section, you learn how to change marker edge color meaning ( change inside color )
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([3, 8, 1, 10])
plt.plot(point_y, marker = 'o', ms = 20, mfc = 'r')
# mfc — Is short form marker face color.
plt.show()
let’s see one more example 🔻
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 1, 10])
plt.plot(point_y, marker = 'o', ms = 21, mfc = 'y')
plt.show()
Now it’s time to apply both marker edge ( mec ) and marker face color ( mfc ).
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([3, 8, 4, 9,6])
plt.plot(point_y, marker = 'o', ms = 16, mec = 'r', mfc = 'r')
plt.show()
Now you know, marker. And this time do some exercise, so you can understand how much you learn.
This is your exercise 🔻
Create a 3 marker you desire number 🔢
Change marker size to 30 and marker face color yellow 🟡
How To Create A Line Chart Using Matplotlib
In this section, you learn a step-by-step guide to creating a line chart with Matplotlib.
Keep reading,
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, linestyle = 'dotted')
plt.show()
Let’s understand code
plt.plot(point_y, linestyle = 'dotted')
linestyle is a keyword in a matplotlib library. This keyword use when you create a line chart.
linestyle short form is ls, meaning you use the keyword linestyle or ls, both are the same.
dotted — This is a style of our line chart.
See the below example.
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, ls = 'dotted') # this time i use ls
plt.show()
Let’s see some of the Styles in line chart.
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, ls = 'dashed') # i use dashed style
plt.show()
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, ls = 'dashdot') # i use dashdot style
plt.show()
If you learn more linestyle read this article.
How To Change Line Color Matplotlib
let’s see below code example. How you can change line color matplotlib.
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, color = 'g')
plt.show()
Understand above code
plt.plot(point_y, color = 'g')
color is a keyword in matplotlib, this keyword you use when draw line color.
color is short form c. You can use color or c both are the same.
See the below example,
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, c = 'g') # this time i use c keyword
plt.show()
Or you can Hexadecimal color values, as you like.
See the below example,
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, c = '#FFD700')
plt.show()
Change Line Width Matplotlib
let’s see the code
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, linewidth = '16.3')
plt.show()
Understand above code
plt.plot(point_y, linewidth = '16.3')
linewidth is a keyword in matplotlib. You can use change your line width.
linewidth shorter form is lw.
let’s see another linewidth example.
import matplotlib.pyplot as plt
import numpy as np
point_y = np.array([2, 8, 4, 10])
plt.plot(point_y, c = '#00ff83', lw = '9') # this time i use lw
plt.show()
Let’s add two lines in the same plot, using plt.plot( ) function.
import matplotlib.pyplot as plt
import numpy as np
first_line = np.array([2, 8, 4, 10])
secound_line = np.array([6, 2, 12, 14])
plt.plot(first_line, c = 'r')
plt.plot(secound_line, c = "g")
plt.show()
Now at this moment, you know how to create a plot in matplotlib. And next step is to learn how to customize the plot.
Plot is like drawing, why not create good drawings, in your data?
So when you share someone your plot they like your work.
Keep reading,
How To Add Labels And Titles To A Plot In Matplotlib
import numpy as np
import matplotlib.pyplot as plt
x = np.array ([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array ([9, 10, 11, 12, 13, 14, 15, 16])
plt.plot(x, y)
plt.title("This is my - Numbers plot");
plt.xlabel ("This is my X axis - first number ");
plt.ylabel ("This is my Y axis - and secound number");
Understand the above code.
In this section, we are using the Pyplot method to plot our data. In Pyplot you can use xlabel() and ylabel( ) functions to set the label in your plot. And you can use the title function to set your plot title.
x axis – xlabel ( )
y axis — ylabel( )
Change Font Style And Size Matplolib Plot
import numpy as np
import matplotlib.pyplot as plt
x = np.array ([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array ([9, 10, 11, 12, 13, 14, 15, 16])
font1 = {'family':'serif','color':'red','size':18}
font2 = {'family':'serif','color':'green','size':14}
font3 = {'family':'serif','color':'blue','size':14}
# In this line of code, I create font name, color, and font size
plt.title("This is my - Numbers plot", fontdict = font1);
plt.xlabel ("This is my X axis - first number ", fontdict = font2);
plt.ylabel ("This is my Y axis - and secound number", fontdict = font3);
fontdict ( ) — Is a function pyplot.
Now it’s time to change the position of the title.
import numpy as np
import matplotlib.pyplot as plt
x = np.array ([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array ([9, 10, 11, 12, 13, 14, 15, 16])
font1 = {'family':'serif','color':'red','size':16}
font2 = {'family':'serif','color':'green','size':14}
font3 = {'family':'serif','color':'blue','size':14}
plt.title("This is my - Numbers plot", fontdict = font1, loc = 'left');
plt.xlabel ("This is my X axis - first number ", fontdict = font2);
plt.ylabel ("This is my Y axis - and secound number", fontdict = font3);
Understand the above code.
You can use the loc parameter to change the position of the title.
Here is value — left, right, and center. The default value is center. See another example, so you understand better.
import matplotlib.pyplot as plt
#define x and y
x = [1, 2, 3, 4, 5, 6]
y = [7, 8, 9, 10, 11, 12]
#create plot of x and y
plt.plot(x, y)
#add title
plt.title('1-12 Numbers Plot', loc='left');
plt.title('I Understand', loc ='right');
Without a grid, there is no line chart. No, I am just joking. 😜
Add Grid Line Matplotlib Figure
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [7, 8, 9, 10, 11, 12]
plt.title ('This is my numbers line chart ');
plt.xlabel ('X axis ');
plt.ylabel ('Y axis ');
plt.plot(x, y);
plt.grid()
plt.show()
In Pyplot, you can use the grid( ) function to add a grid to your line chart.
You notice X and Y two grid lines show the default. But you can change this setting.
See the below code example.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [7, 8, 9, 10, 11, 12]
plt.title ('This is my numbers line chart ');
plt.xlabel ('X axis ');
plt.ylabel ('Y axis ');
plt.plot(x, y);
plt.grid(axis = 'x') # This line show only X grid
plt.show()
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [7, 8, 9, 10, 11, 12]
plt.title ('This is my numbers line chart ');
plt.xlabel ('X axis ');
plt.ylabel ('Y axis ');
plt.plot(x, y);
plt.grid(axis = 'y') # This line show only Y grid
plt.show()
Now it’s time to change grid style. See the below example of how you can do.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [7, 8, 9, 10, 11, 12]
plt.title ('This is my numbers line chart ');
plt.xlabel ('X axis ');
plt.ylabel ('Y axis ');
plt.plot(x, y);
plt.grid(color = 'red', linestyle = '--', linewidth = 0.5)
# Note — grid(color = 'color', linestyle = 'linestyle', linewidth = number).
plt.show()
Subplot In Matplotlib
In this section, you learn how to create a subplot in Matplotlib, but before start writing any code first understand what is subplot.
What Is A Subplot In Matplotlib
A subplot is a function in matplotlib, you can draw multiple plots in one figure.
See below code example, so you can understand better.
import matplotlib.pyplot as plt
import numpy as np
# 1st plot
first_number = np.array ([1, 2, 3, 4, 5, 6])
secound_number = np.array ([7, 8, 9, 10, 11, 12])
plt.subplot(1, 2, 1)
plt.plot(first_number, secound_number)
# 2nd Plot
first_number = np.array ([2, 3, 4, 5, 6])
secound_number = np.array ([8, 12, 6, 7,1])
plt.subplot(1, 2, 2)
plt.plot(first_number, secound_number)
plt.show()
let’s understand the code
The subplot ( ) function takes three arguments that show the layout of the figure. This layout is organized in rows and columns.
The third argument is which plot you show, that number you pass.
let’s see the same code 🔺
import matplotlib.pyplot as plt
import numpy as np
# 1st plot
first_number = np.array ([1, 2, 3, 4, 5, 6])
secound_number = np.array ([7, 8, 9, 10, 11, 12])
plt.subplot(1, 2, 1)
# 1 is row , 2 is coloumn , 1 is a first plot
plt.plot(first_number, secound_number)
# 2nd Plot
first_number = np.array ([2, 3, 4, 5, 6])
secound_number = np.array ([8, 12, 6, 7,1])
plt.subplot(1, 2, 2)
# 1 is row , 2 is coloumn , 2 is a secound plot
plt.plot(first_number, secound_number)
plt.show()
Now it’s time to add title ( ) in my plot.
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3, 4, 5 ])
y = np.array([4, 8, 6, 10, 2, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("Sales Increse & Descress Report ")
#plot 2:
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([10, 20, 30, 40, 60, 50])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("Income Reports This Year ")
plt.show()
If you share this plot with your friends or other people. They don’t know what is plot. Meaning they see sales increase and decrease and they see income report. But they asked one question you?
Hi, which person, company, or other reports is it?
So your answer is, let’s see this plot.
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3, 4, 5 ])
y = np.array([4, 8, 6, 10, 2, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("Sales Increse & Descress Report ")
#plot 2:
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([10, 20, 30, 40, 60, 50])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("Income Reports This Year ")
plt.suptitle("This is a HIWHY Company Report")
plt.show()
suptitle ( ) is a function, you can use to add the title entire figure.
Scatter Plot Matplotlib
Now it’s time to learn how to draw scatter plots in matplotlib. But before you jump to how to draw a scatter plot, first understand what a scatter plot is.
What Is A Scatter Plot Matplotlib?
Scatter plots represent data in graphical format. Every scatters plot use dots. This plot needs two arrays of the same length one for the value ( X axis ) and one for values on the ( Y axis ).
If you understand, that is good, but if you don’t understand that’s fine.
See below example code.
import matplotlib.pyplot as plt
import numpy as np
numbers = np.array([2, 3, 4, 5])
multiply_2 = np.array([4, 6, 8, 10])
plt.scatter(numbers, multiply_2);
Understand above code 🔻
An x-axis is a number [ 2, 3, 4, 5 ], and a y-axis is a multiply number [ 4, 6, 8, 10 ]. In matplotlib, you can use the scatter ( ) function to draw a scatter plot.
let’s underastnd more details.
Here is an example of how old a car is, and their speed test 🚗
# this is a example old car and their speed test
import matplotlib.pyplot as plt
import numpy as np
cars_age = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
speed_test = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.title ("This is cars age and their speed test report")
plt.xlabel ("Cars age")
plt.ylabel ("Speed of this car")
plt.scatter(cars_age, speed_test)
plt.show()
let’s create another plot to compare [ Computer Science Or Math ] yearly exam passing report!
#Computer Science Or Math yearly exam passing report
import matplotlib.pyplot as plt
import numpy as np
# This is a computer science exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_computer_science = np.array([80, 77, 67, 56, 46])
plt.scatter(years, pass_exam_computer_science)
# This is a math exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_math = np.array([70, 60, 63, 40, 36])
plt.scatter(years, pass_exam_math)
plt.grid()
plt.title("This is a Computer science & Math exam yearly report")
plt.xlabel("Years")
plt.ylabel("Percantage of the Passing ")
plt.show()
Note — The default color is Blue 🔵, Orange 🟠. But we change this color to your favorite color.
See the below code, how you change color.
import matplotlib.pyplot as plt
import numpy as np
# This is a computer science exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_computer_science = np.array([80, 77, 67, 56, 46])
plt.scatter(years, pass_exam_computer_science, color = "r")
# This is a math exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_math = np.array([70, 60, 63, 40, 36])
plt.scatter(years, pass_exam_math, color = "g")
plt.grid()
plt.title("This is a Computer science & Math exam yearly report")
plt.xlabel("Years")
plt.ylabel("Percantage of the Passing ")
plt.show()
Just one line code and you change the color of this plot. Just type color or c and then pass color name,
Choose Different Color For Each Dots In Scatter Plot
You can change every dot color in the scatter plot, see below code example.
import matplotlib.pyplot as plt
import numpy as np
# This is a computer science exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_computer_science = np.array([80, 77, 67, 56, 46])
colors = np.array (["red" , "green", "black", "yellow", "gray"])
plt.scatter (years, pass_exam_computer_science, c = colors)
plt.title ("This is yearly report computer science exam ")
plt.xlabel("Years")
plt.ylabel("Passing percantage")
plt.grid()
plt.show()
Now it’s time to learn matplotlib awesome module colormap.This module has lots of lists of colors. And every color value range starts from 0 to 100.
Let’s see an example, so you can understand better. 🔻
This image you see above is called ‘viridis’. Range 0 which is purple and up to 100 which is yellow color. 🟣🟡
Now your question is?
How To Use Colormap Matplotlib
See below example
import matplotlib.pyplot as plt
import numpy as np
# This is a computer science exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_computer_science = np.array([80, 77, 67, 56, 46])
colors = np.array ([10, 20, 30, 50, 60 ])
plt.scatter (years, pass_exam_computer_science, c = colors, cmap = 'viridis')
plt.title ("This is yearly report computer science exam ")
plt.xlabel("Years")
plt.ylabel("Passing percantage")
plt.grid()
plt.show()
Let’s understand the above code 👆🏻
You can use cmap keyword and pass value of colormap, In this case, I use ‘viridis’ .
Change Scatter Plot Dot Size Matplotlib
See the below example.
import matplotlib.pyplot as plt
import numpy as np
# This is a computer science exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_computer_science = np.array([80, 77, 67, 56, 46])
sizes = np.array ([36, 100, 150, 90, 300])
plt.scatter( years, pass_exam_computer_science, s=sizes)
plt.title ("This is yearly report computer science exam ")
plt.xlabel("Years")
plt.ylabel("Passing percantage")
plt.grid()
plt.show()
Understand the above code.
s is a keyword in matplotlib, you can use to change the size of your plot dot. But first create an array, which size do you want 🔻
sizes = np.array ([36, 100, 150, 90, 300])
Now it’s time to pass, your array in the s argument🔻
plt.scatter( years, pass_exam_computer_science, s=sizes)
Note — Whenever you use colormap or size, your array size must be the same. Mean your x and y is the same.
let’s see this example 🔻
import numpy as np
import matplotlib.pyplot as plt
first_array = np.array ([1, 2, 3, 4])
secound_array = np.array ([1, 2, 3])
plt.scatter (first_array, secound_array)
# We run this code show -- ValueError: x and y must be the same size
How To Draw Bar Plot In Matplotlib
A bar chart is also called a bar graph. 📊
See below example 👇🏻
import numpy as np
import matplotlib.pyplot as plt
bank_name = np.array (["Yes Bank", "Axis Bank", "HDFC Bank", "State Bank"])
bank_growth_this_year = np.array ([10, 60, 40, 88])
plt.bar(bank_name, bank_growth_this_year)
plt.title("Bank growth report in this 2021 Year")
plt.xlabel("Bank Name")
plt.ylabel("Growth percantage")
plt.show()
let’s understand the code 👆🏻
In Pyplot, you can use bar( ) function to create a bar chart ( bar graph )
plt.bar(bank_name, bank_growth_this_year)
Create another plot. 👇🏻
import matplotlib.pyplot as plt
import numpy as np
# This is a computer science exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_computer_science = np.array([80, 77, 67, 56, 46])
sizes = np.array ([36, 100, 150, 90, 300])
plt.bar( years, pass_exam_computer_science)
plt.title ("This is yearly report computer science exam ")
plt.xlabel("Years")
plt.ylabel("Passing percantage")
plt.grid()
plt.show()
Now create one more 👇🏻
import matplotlib.pyplot as plt
import numpy as np
# This is a computer science exam passing data
years = np.array([2008, 2012, 2014, 2018, 2022])
pass_exam_computer_science = np.array([80, 77, 67, 56, 46])
sizes = np.array ([36, 100, 150, 90, 300])
plt.barh( years, pass_exam_computer_science)
plt.title ("This is yearly report computer science exam ")
plt.xlabel("Years")
plt.ylabel("Passing percantage")
plt.grid()
plt.show()
Understand the above code. 👆🏻
It’s time you see, your data are shown in a horizontal bar. Because we are using barh ( ) function.
plt.barh( years, pass_exam_computer_science)
# If you create a bar chart horizontally use barh ( ) function.
Change Bar Color In Matplotlib
import numpy as np
import matplotlib.pyplot as plt
bank_name = np.array (["Yes Bank", "Axis Bank", "HDFC Bank", "State Bank"])
bank_growth_this_year = np.array ([10, 60, 40, 88])
plt.bar(bank_name, bank_growth_this_year, color = "lightgreen")
plt.title("Bank growth report in this 2021 Year")
plt.xlabel("Bank Name")
plt.ylabel("Growth percantage")
plt.show()
You can change the bar and barh color using the keyword color and pass the name of the color.
plt.bar(bank_name, bank_growth_this_year, color = "lightgreen")
# use keyword color and pass color name
See another example
import numpy as np
import matplotlib.pyplot as plt
best_tech_company = np.array (["Apple", "Facebook", "Microsoft", "Amazon", "Google"])
company_growth_this_month = np.array ([60, 45, 30, 85, 70])
plt.barh(best_tech_company, company_growth_this_month, color = "skyblue")
plt.title("Company growth this month report")
plt.xlabel("Company Name")
plt.ylabel("Growth percantage")
plt.show()
How Do I Change The Bar Width In Matplotlib
Now, it’s time to change the bar width. Because without design is not look good our plot.
import numpy as np
import matplotlib.pyplot as plt
best_tech_company = np.array (["Apple", "Facebook", "Microsoft", "Amazon", "Google"])
company_growth_this_month = np.array ([60, 45, 30, 85, 70])
plt.bar(best_tech_company, company_growth_this_month, width = 0.1, color = "#FAF18E")
plt.title("Company growth this month report")
plt.xlabel("Company Name")
plt.ylabel("Growth percantage")
plt.grid()
plt.show()
let’s understand the code 👇🏻
You can change the width value using the keyword width and set value. The default value width is 0.8.
plt.bar(best_tech_company, company_growth_this_month, width = 0.1, color = "#FAF18E")
Create horizontal plot
import numpy as np
import matplotlib.pyplot as plt
best_tech_company = np.array (["Apple", "Facebook", "Microsoft", "Amazon", "Google"])
company_growth_this_month = np.array ([60, 45, 30, 85, 70])
plt.barh(best_tech_company, company_growth_this_month, height = 0.1, color = "#FAF18E")
plt.title("Company growth this month report")
plt.xlabel("Company Name")
plt.ylabel("Growth percantage")
plt.grid()
plt.show()
Note — Vertical time use the width keyword, Horizontal time use height keyword. The default value is vertically and horizontally 0.8
plt.barh(best_tech_company, company_growth_this_month, height = 0.1, color = "#FAF18E")
bar ( ) take keyword argument width ( )
barh ( ) takes keyword argument height ( )
Make Histrogam Plot Matplotlib
A histogram is similar to the bar chart, but a histogram shows a plot in group of range numbers. Each range is a vertical bar. Let’s see example. When I first learn this, I don’t understand this thing first time, but after some practice, then I understand. So why practice is important.
Note — Practice make perfect result ✖️, Perfect practice makes perfect result ✔️
Make a histogram plot
import numpy as np
import matplotlib.pyplot as plt
average_salary_india = np.array([6000, 8000, 9500, 10000, 12500,])
plt.hist(average_salary_india)
# You can create a histogram plot use hist ( ) function in Matplolib.
plt.title("This is a averge salary in India")
plt.xlabel("Salary")
plt.show()
Change The Color Of Histogram Plot In Matplotlib
import numpy as np
import matplotlib.pyplot as plt
average_salary_india = np.array([6000, 8000, 9500, 10000, 12500,])
plt.hist(average_salary_india, color="yellow")
plt.title("This is a averge salary in India")
plt.xlabel("Salary")
plt.show()
Make A Pie Chart In Matplotlib Python
This is my favorite chart. But first, understand what is a pie chart.
What Is A Pie Chart
Pie chart display data in a circular format ⭕.
See below code example 🔻
import matplotlib.pyplot as plt
import numpy as np
pie_chart_i_learn = np.array([21, 33, 30, 45, 65])
plt.pie(pie_chart_i_learn)
#You can use pie ( ) function, to create pie chart.
plt.show()
You notice pie chart draws one piece for each value ( called a wedge ) in our arrays 21, 33, 30, 45, 65.
As you already know, every plot has two axis — X and Y.
In the default pie chart first slice ( wedge 🧀) starts from the x-axis and then moves counterclockwise.
And if you think in your mind, how is each wedge ( slice ) calculated?
The answer is — The size of each wedge show comparing the value with all the other value. This is a formula — x/sum(x)
The x value has divided by the sum of all values.
Create one more plot.
import matplotlib.pyplot as plt
import numpy as np
company_growth_this_year = np.array([68, 75, 21, 40, 33, 80])
company_name = np.array (["Amazon", "Walmart", "Facebook", "Microsoft", "Google", "Apple"])
#You can add labels to your pie chart use label keyword and pass label array
plt.pie(company_growth_this_year, labels=company_name)
plt.show()
Change Angle Of Wedge Pie Chart In Matplotlib
import matplotlib.pyplot as plt
import numpy as np
company_growth_this_year = np.array([68, 75, 21, 40, 33, 80])
company_name = np.array (["Amazon", "Walmart", "Facebook", "Microsoft", "Google", "Apple"])
fig = plt.figure(figsize=(9, 9))
plt.pie(company_growth_this_year, labels=company_name, startangle=90)
# you can change angle use startangle keyword and pass your value
plt.show()
Do you see any difference? See these two picture side by side
As you already know, the default start angle is x-axis. And the default this angle value is 0 degree. But you can change this angle using startangle keyword and pass your value. In this case, I am setting the angle at 90 degrees.
Explode Pie Chart In Matplotlib
import matplotlib.pyplot as plt
import numpy as np
bank_growth_this_year_india = np.array ([80, 60, 30, 50, 88])
bank_name = np.array (["SBI", "Axis Bank", "Yes Bank", "Bank Of Baroda", "HDFC Bank"])
explode_this = [0.1, 0, 0, 0, 0.2]
fig = plt.figure(figsize = (10, 7))
plt.pie(bank_growth_this_year_india, labels=bank_name, explode = explode_this)
plt.show()
let’s understand the code.
If you want to explode your plot use explode parameter and pass value. In this example, I am using the value.
Note — The default value is none.
explode_this = [0.1, 0, 0, 0, 0.2] # This is value explode
Add Shadow To Pie Chart Each Wedge
import matplotlib.pyplot as plt
import numpy as np
bank_growth_this_year_india = np.array ([80, 60, 30, 50, 88])
bank_name = np.array (["SBI", "Axis Bank", "Yes Bank", "Bank Of Baroda", "HDFC Bank"])
explode_this = [0.1, 0, 0, 0, 0.2]
fig = plt.figure(figsize = (9, 6))
plt.pie(bank_growth_this_year_india, labels=bank_name, explode = explode_this, shadow = True)
plt.show()
You can add shadows in your pie chart use shadows paremeter to true. This parameter default value is False.
plt.pie(bank_growth_this_year_india, labels=bank_name, explode = explode_this, shadow = True)
Change Pie Chart Each Wedge Color In Matplotlib
import matplotlib.pyplot as plt
import numpy as np
bank_growth_this_year_india = np.array ([80, 60, 30, 50, 88])
bank_name = np.array (["SBI", "Axis Bank", "Yes Bank", "Bank Of Baroda", "HDFC Bank"])
explode_this = [0.1, 0, 0, 0, 0.2]
change_the_color_wedge = ["Yellow", "Blue", "black", "hotpink", "Magenta"]
# first i create color array
fig = plt.figure(figsize = (9, 6))
plt.pie(bank_growth_this_year_india, labels=bank_name, explode = explode_this, shadow = True, colors = change_the_color_wedge)
plt.show()
Understand code 🔻
You can change the color of each wedge, use color parameter. First, create a color array and then pass this array colors parameter.
change_the_color_wedge = ["Yellow", "Blue", "black", "hotpink", "Magenta"]
Then pass this array colors parameter. 🔻
plt.pie(bank_growth_this_year_india, labels=bank_name, explode = explode_this, shadow = True, colors = change_the_color_wedge)
You can use Hexidicamal color value or use HTML color
Let’s add more details to our plot so that when we share it with someone they can understand easily.
import matplotlib.pyplot as plt
import numpy as np
bank_growth_this_year_india = np.array ([80, 60, 30, 50, 88])
bank_name = np.array (["SBI", "Axis Bank", "Yes Bank", "Bank Of Baroda", "HDFC Bank"])
explode_this = [0.1, 0, 0, 0, 0.2]
fig = plt.figure(figsize = (9, 6))
plt.legend(title= "Bank growth reports 2022");
# You can add a title in your plot use legend function and then pass the title parameter.
plt.pie(bank_growth_this_year_india, labels=bank_name, explode = explode_this, shadow = True);
plt.show();
Save Matplotlib Figure (Plot) As Png
The answer is easy. let’s say you can save this plot 🔻, on your computer.
Just use savefig ( )
function.
import matplotlib.pyplot as plt
import numpy as np
bank_growth_this_year_india = np.array ([80, 60, 30, 50, 88])
bank_name = np.array (["SBI", "Axis Bank", "Yes Bank", "Bank Of Baroda", "HDFC Bank"])
explode_this = [0.1, 0, 0, 0, 0.2]
fig = plt.figure(figsize = (9, 6))
plt.legend(title= "Bank growth reports 2022");
plt.pie(bank_growth_this_year_india, labels=bank_name, explode = explode_this, shadow = True);
plt.savefig("bank_growth_report.png") # This line save this plot in png
plt.show();
Now it’s time to, do some homework and practice more. One thing remembers everything first time is hard but after easy.
Here is your homework
- Download dataset and explore what you learn.