How to install matplotlib,
Using pip,
pip install matplotlib |
How to import matplotlib.pyplot
In Python,
import matplotlib.pyplot as plt |
How to plot two arrays
Plot the two arrays using Plot function
Example:
import matplotlib.pyplot as plt
x = [0,1,2,3,4,5,6]
y = [9,10,11,12,13,14,15]
# Plots the x and y
plt.plot(x,y)
# Display the plot
plt.show()
Additional arguments to Plot function:
marker_symbol: to draw each point with a specified marker
Syntax:
plt.plot(x_points, y_points, marker = 'marker_symbol')
marker_symbol can be 'o','*','+','s','d' etc
line_symbol: to connect different points
Syntax:
plt.plot(x_points, y_points, linestyle = 'line_symbol')
line_symbol can be '-',':','--' etc
color_symbol: Color of the plot
Syntax:
plt.plot(x_points, y_points, color = 'color_symbol')
color_symbol can be 'r','g','b' etc
Shortcut Syntax for all arguments:
plt.plot(x_points,y_points,'marker_symbol:line_symbol:color_symbol')
|
|
|
Create Labels for Plot
xlabel() and ylabel() functions to set a label for the x-axis and y-axis.
title() function to set the title for the plot
Syntax:
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
Additional arguments to Labels function:
Add font details to labels() function
Syntax:
font = {'family':'font_type','color':'color_symbol','size':font_size}
Example:
font = {'family':'serif','color':'b','size':30}
plt.title(title, fontdict=font)
|
Grid of the plot
grid() function to add grid lines to the plot.
Syntax:
plt.grid()
- Gridlines in x and y axis
plt.grid(axis='x')
- Gridlines in x axis alone
plt.grid(axis='y')
- Gridlines in y axis alone |
Display the multiple subplot
subplot() function you can draw multiple plots in single figure itself
Syntax:
plt.subplot(rows,columns,index)
rows - Total number of rows in figure
columns - Total number of cols in figure
index - Index of the current plot
Example:
import matplotlib.pyplot as plt
#plot 1
x = [1, 2, 3, 4]
y = [1, 2, 3, 4]
#First subplot
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2
x = [0, 1, 2, 3]
y = [0, -1, -2, -3]
#Second subplot
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
|
|
|
Different plot types
Scatter plot:
Syntax:
plt.scatter(x,y)
Bar plot:
Vertical plot
Syntax:
plt.bar(x,y,width=size,height=size,color='color_symbol')
Horizontal plot:
Syntax:
plt.barh(x,y,width=size,height=size,color='color_symbol')
Histogram:
Histogram is a graph showing frequency distributions.
Syntax:
plt.hist(x)
Pie chart:
Syntax:
plt.pie(x,labels = labels_list)
|
|
Created By
Metadata
Comments
No comments yet. Add yours below!
Add a Comment