Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Matplotlib

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

MATPLOTLIB

1. Matplotlib is a Python library that is specially designed for the development of


graphs, charts etc., in order to provide interactive data visualisation
2. Matplotlib is inspired from the MATLAB software and reproduces many of it's
features.

# Import Matplotlib submodule for plotting


import matplotlib.pyplot as plt
Plotting in Matplotlib

plt.plot([1,2,3,4]) # List of vertical co-ordinates of the points plotted


plt.show() # Displays plot
# Implicit X-axis values from 0 to (N-1) where N is the length of the list
# We can specify the values for both axes
x = range(5) # Sequence of values for the x-axis
# X-axis values specified - [0,1,2,3,4]
plt.plot(x, [x1**2 for x1 in x]) # vertical co-ordinates of the points plotted: y = x^2
plt.show()

# We can use NumPy to specify the values for both axes with greater precision
x = np.arange(0, 5, 0.01)
plt.plot(x, [x1**2 for x1 in x]) # vertical co-ordinates of the points plotted: y = x^2
plt.show()
Multiline Plots
# Multiple functions can be drawn on the same plot
x = range(5)
plt.plot(x, [x1 for x1 in x])
plt.plot(x, [x1*x1 for x1 in x])
plt.plot(x, [x1*x1*x1 for x1 in x])
plt.show()

# Different colours are used for different lines


x = range(5)
plt.plot(x, [x1 for x1 in x],
x, [x1*x1 for x1 in x],
x, [x1*x1*x1 for x1 in x])
plt.show()
Grids
# The grid() function adds a grid to the plot
# grid() takes a single Boolean parameter
# grid appears in the background of the plot
x = range(5)
plt.plot(x, [x1 for x1 in x],
x, [x1*2 for x1 in x],
x, [x1*4 for x1 in x])
plt.grid(True)
plt.show()
Limiting the Axes
# The scale of the plot can be set using axis()
x = range(5)
plt.plot(x, [x1 for x1 in x],
x, [x1*2 for x1 in x],
x, [x1*4 for x1 in x])
plt.grid(True)
plt.axis([-1, 5, -1, 10]) # Sets new axes limits
plt.show()
# The scale of the plot can also be set using xlim() and ylim()
x = range(5)
plt.plot(x, [x1 for x1 in x],
x, [x1*2 for x1 in x],
x, [x1*4 for x1 in x])
plt.grid(True)
plt.xlim(-1, 5)
plt.ylim(-1, 10)
plt.show()
Adding Labels
# Labels can be added to the axes of the plot
x = range(5)
plt.plot(x, [x1 for x1 in x],
x, [x1*2 for x1 in x],
x, [x1*4 for x1 in x])
plt.grid(True)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
Adding the Title
# The title defines the data plotted on the graph
x = range(5)
plt.plot(x, [x1 for x1 in x],
x, [x1*2 for x1 in x],
x, [x1*4 for x1 in x])
plt.grid(True)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("Polynomial Graph") # Pass the title as a parameter to title()
plt.show()
Adding a Legend
# Legends explain the meaning of each line in the graph
x = np.arange(5)
plt.plot(x, x, label = 'linear')
plt.plot(x, x*x, label = 'square')
plt.plot(x, x*x*x, label = 'cube')
plt.grid(True)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("Polynomial Graph")
plt.legend()
plt.show()
Adding Markers
x = [1, 2, 3, 4, 5, 6]
y = [11, 22, 33, 44, 55, 66]
plt.plot(x, y, 'bo')
for i in range(len(x)):
x_cord = x[i]
y_cord = y[i]
plt.text(x_cord, y_cord, (x_cord, y_cord), fontsize = 10)
plt.show()
Saving Plots
# Plots can be saved using savefig()
x = np.arange(5)
plt.plot(x, x, label = 'linear')
plt.plot(x, x*x, label = 'square')
plt.plot(x, x*x*x, label = 'cube')
plt.grid(True)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("Polynomial Graph")
plt.legend()
plt.savefig('plot.png') # Saves an image names 'plot.png' in the current directory
plt.show()
Plot Types
Matplotlib provides many types of plot formats for visualising information
1. Scatter Plot
2. Histogram
3. Bar Graph
4. Pie Chart
Histogram
# Histograms display the distribution of a variable over a range of frequencies or v
alues
y = np.random.randn(100, 100) # 100x100 array of a Gaussian distribution
plt.hist(y) # Function to plot the histogram takes the dataset as the parameter
plt.show()
# Histogram groups values into non-overlapping categories called bins
# Default bin value of the histogram plot is 10
y = np.random.randn(1000)
plt.hist(y, 100)
plt.show()
Bar Chart
# Bar charts are used to visually compare two or more values using rectangular ba
rs
# Default width of each bar is 0.8 units
# [1,2,3] Mid-point of the lower face of every bar
# [1,4,9] Heights of the successive bars in the plot
plt.bar([1,2,3], [1,4,9])
plt.show()
dictionary = {'A':25, 'B':70, 'C':55, 'D':90}
for i, key in enumerate(dictionary):
plt.bar(i, dictionary[key]) # Each key-value pair is plotted individually as diction
aries are not iterable
plt.show()
dictionary = {'A':25, 'B':70, 'C':55, 'D':90}
for i, key in enumerate(dictionary):
plt.bar(i, dictionary[key])
plt.xticks(np.arange(len(dictionary)), dictionary.keys()) # Adds the keys as labels o
n the x-axis
plt.show()
Pie Chart
plt.figure(figsize = (3,3)) # Size of the plot in inches
x = [40, 20, 5] # Proportions of the sectors
labels = ['Bikes', 'Cars', 'Buses']
plt.pie(x, labels = labels)
plt.show()

Scatter Plot
# Scatter plots display values for two sets of data, visualised as a collection of poin
ts
# Two Gaussion distribution plotted
x = np.random.rand(1000)
y = np.random.rand(1000)
plt.scatter(x, y)
plt.show()
Styling
# Matplotlib allows to choose custom colours for plots
y = np.arange(1, 3)
plt.plot(y, 'y') # Specifying line colours
plt.plot(y+5, 'm')
plt.plot(y+10, 'c')
plt.show()

Color code:
1. b = Blue
2. c = Cyan
3. g = Green
4. k = Black
5. m = Magenta
6. r = Red
7. w = White
8. y = Yellow
# Matplotlib allows different line styles for plots
y = np.arange(1, 100)
plt.plot(y, '--', y*5, '-.', y*10, ':')
plt.show()
# - Solid line
# -- Dashed line
# -. Dash-Dot line
# : Dotted Line
# Matplotlib provides customization options for markers
y = np.arange(1, 3, 0.2)
plt.plot(y, '*',
y+0.5, 'o',
y+1, 'D',
y+2, '^',
y+3, 's') # Specifying line styling
plt.show()

You might also like