1 of 21

Line Graphs

import matplotlib.pyplot as plt

#create data for plotting�x_values = [0, 1, 2, 3, 4, 5 ]�y_values = [0, 1, 4, 9, 16,25]

#the default graph style for plot is a line�plt.plot(x_values, y_values)

#display the graph�plt.show()

2 of 21

More on Line Graph

  • Note: if you provide a single list or array to the plot() command,

    • then matplotlib assumes it is a sequence of y values, and

    • automatically generates the�x values for you.

  • Since python ranges start with 0,�the default x vector has the same length as y but starts with 0.

    • Hence the x data are[0, 1, 2, 3].

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4])

plt.ylabel('some numbers')

plt.show()

3 of 21

import matplotlib.pyplot as plt

y1 =[]

y2 =[]

x = range(-100,100,10)

for i in x: y1.append(i**2)

for i in x: y2.append(-i**2)

plt.plot(x, y1)

plt.plot(x, y2)

plt.xlabel("x")

plt.ylabel("y")

plt.savefig("quad.png")

plt.show()

Incrementally modify the figure.

Show it on the screen

Save your figure to a file

4 of 21

Simple line

# importing the required module

import matplotlib.pyplot as plt

# x axis values

x = [1,2,3]

# corresponding y axis values

y = [2,4,1]

# plotting the points

plt.plot(x, y)

# naming the x axis

plt.xlabel('x - axis')

# naming the y axis

plt.ylabel('y - axis')

# giving a title to my graph

plt.title('My first graph!')

# function to show the plot

plt.show()

  • Define the x-axis and corresponding y-axis values as lists.
  • Plot them on canvas using .plot() function.
  • Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions.
  • Give a title to your plot using .title() function.
  • Finally, to view your plot, we use .show() function.

5 of 21

Simple 2 lines

import matplotlib.pyplot as plt

# line 1 points

x1 = [1,2,3]

y1 = [2,4,1]

# plotting the line 1 points

plt.plot(x1, y1, label="line 1")

# line 2 points

x2 = [1,2,3]

y2 = [4,1,3]

# plotting the line 2 points

plt.plot(x2, y2, label = "line 2")

# naming the x axis

plt.xlabel('x - axis')

# naming the y axis

plt.ylabel('y - axis')

# giving a title to my graph

plt.title('Two lines on same graph!')

# show a legend on the plot

plt.legend()

# function to show the plot

plt.show()

  • Here, we plot two lines on same graph. We differentiate between them by giving them a name(label) which is passed as an argument of .plot() function.
  • The small rectangular box giving information about type of line and its color is called legend. We can add a legend to our plot using .legend() function.

6 of 21

Customization of Plots

import matplotlib.pyplot as plt

# x axis values

x = [1,2,3,4,5,6]

# corresponding y axis values

y = [2,4,1,5,2,6]

# plotting the points

plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,

marker='o', markerfacecolor='blue', markersize=12)

# naming the x axis

plt.xlabel('x - axis')

# naming the y axis

plt.ylabel('y - axis')

# giving a title to my graph

plt.title('Some cool customizations!')

# function to show the plot

plt.show()

7 of 21

Bar graphs

A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally.

A bar graph shows comparisons among discrete categories. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value.

8 of 21

Type of Bar Graph

9 of 21

Bar graphs

bar(x, height, width=0.8, bottom=None, *, align='center')

Parameters

----------

x : x coordinates of the bars

height : The height(s) of the bars :- y coordinates

width : The width(s) of the bars (default: 0.8).

bottom : scalar or array-like, optional

The y coordinate(s) of the bars bases (default: 0).

align : {'center', 'edge'}, optional, default: 'center'

Alignment of the bars to the *x* coordinates:

- 'center': Center the base on the *x* positions.

- 'edge': Align the left edges of the bars with the *x* positions.

10 of 21

Bar graphs

  • When using a bar graph, the change in code will be from�plt.plot() to plt.bar() changes it into a bar chart.

import matplotlib.pyplot as plt

#Create data for plotting

values = [5, 6, 3, 7, 2]

names = ["A", "B", "C", "D", "E"]

plt.bar(names, values, color="green")

plt.show()

11 of 21

Bar Chart

import matplotlib.pyplot as plt

# heights of bars

height = [10, 24, 36, 40, 5]

# labels for bars

names = ['one','two','three','four','five']

# plotting a bar chart

c1 =['red', 'green']

# we can use this for color

plt.bar(names, height, width=0.8, color=c1)

# naming the x-axis

plt.xlabel('x - axis')

# naming the y-axis

plt.ylabel('y - axis')

# plot title

plt.title('My bar chart!')

# function to show the plot

plt.show()

  • Here, we use plt.bar() function to plot a bar chart.

12 of 21

Bar Chart

import matplotlib.pyplot as plt

# heights of bars

st=["up", "bihar", "asam", "bengal"]

# labels for bars

dist=[150, 140, 100, 160]

# plotting a bar chart

plt.bar(st, dist, width=.5,

bottom=[50,20,40,60],

color=["g", "b", "r", "y"])

# naming the x-axis

plt.xlabel('states')

# naming the y-axis

plt.ylabel('no of districts')

# plot title

plt.title("Title of graph")

# function to show the plot

plt.show()

13 of 21

Bar Chart

import matplotlib.pyplot as plt

# heights of bars

st=["up", "bihar", "asam", "bengal"]

# labels for bars

dist=[150, 140, 100, 160]

# plotting a bar chart

plt.bar(st, dist, width=.5,

align='edge‘,

color=["g", "b", "r", "y"])

# naming the x-axis

plt.xlabel('states')

# naming the y-axis

plt.ylabel('no of districts')

# plot title

plt.title("Title of graph")

# function to show the plot

plt.show()

14 of 21

Bar Chart

import matplotlib.pyplot as plt

# heights of bars

st=["up", "bihar", "asam", "bengal"]

# labels for bars

dist=[150, 140, 100, 160]

# plotting a bar chart

plt.bar(st, dist, width=-.5,

align='edge‘,

color=["g", "b", "r", "y"])

# naming the x-axis

plt.xlabel('states')

# naming the y-axis

plt.ylabel('no of districts')

# plot title

plt.title("Title of graph")

# function to show the plot

plt.show()

15 of 21

Bar Chart

import matplotlib.pyplot as plt

# heights of bars

st=["up", "bihar", "asam", "bengal"]

# labels for bars

dist=[150, 140, 100, 160]

# plotting a bar chart

plt.bar(st, dist, width=.5,

color=["g", "b", "r", "y"],

edgecolor=["k","g", "b","r"],

linewidth=2)

# naming the x-axis

plt.xlabel('states')

# naming the y-axis

plt.ylabel('no of districts')

# plot title

plt.title("Title of graph")

# function to show the plot

plt.show()

16 of 21

Bar Chart

import matplotlib.pyplot as plt

import numpy as np

# heights of bars

data0 = [30, 25, 50, 20]

data1 = [40, 23, 51, 17]

data2 = [35, 22, 45, 19]

# labels for bars

X = np.array([1,2,3,4])

# plotting a bar chart

plt.bar(X + 0.00, data0, color = 'b', width = 0.25)

plt.bar(X + 0.25, data1, color = 'g', width = 0.25)

plt.bar(X + 0.50, data2, color = 'r', width = 0.25)

# labels for bars

plt.xticks([1.25,2.25,3.25,4.25], [2015,2016,2017,2018])

# naming the x-axis

plt.legend(labels=['CS','IT','E&TC'])

plt.show()

17 of 21

Bar Chart

import matplotlib.pyplot as plt

import numpy as np

# heights of bars

data0 = [30, 25, 50, 20]

data1 = [40, 23, 51, 17]

# labels for bars

X = np.array([1,2,3,4])

# plotting a bar chart

plt.bar(X , data0, color = 'b', width = 0.25)

plt.bar(X , data1, bottom=data0 color = 'g', width = 0.25)

# labels for bars

plt.xticks([1,2,3,4], [2015,2016,2017,2018])

# naming the x-axis

plt.legend(labels=['CS','IT','E&TC'])

plt.show()

18 of 21

Bar graphs

We can also flip the bar graph horizontally with the following

import matplotlib.pyplot as plt

#Create data for plotting�values = [5,6,3,7,2]�names = ["A", "B", "C", "D", "E"]

# Adding an "h" after bar will flip the graph�plt.barh(names, values, color="yellowgreen")�plt.show()

19 of 21

pyplot

  • text() : adds text in an arbitrary location
  • xlabel(): adds text to the x-axis
  • ylabel(): adds text to the y-axis
  • title() : adds title to the plot
  • clear() : removes all plots from the axes.
  • savefig(): saves your figure to a file
  • legend() : shows a legend on the plot

All methods are available on pyplot and on the axes instance generally.

20 of 21

Histogram

import matplotlib.pyplot as plt

# frequencies

ages=[2,5,70,40,30,45,50,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]

# setting the ranges and no. of intervals

range = (0, 100)

bins = 10

# plotting a histogram

plt.hist(ages, bins, range, color='green',histtype='bar',rwidth=0.8)

# x-axis label

plt.xlabel('age')

# frequency label

plt.ylabel('No. of people')

# plot title

plt.title('My histogram')

# function to show the plot

plt.show()

21 of 21

Histograms

  • Looking at the code snippet, I added two new arguments:

    • Bins — is an argument specific to a histogram and allows the user to customize how many bins they want.

    • Alpha — is an argument that displays the level of transparency of the data points.

import matplotlib.pyplot as plt

#generate fake data

x = [2,1,6,4,2,4,8,9,4,2,4,10,6,4,5,7,7,3,2,7,5,3,5,9,2,1]

#plot for a histogram

plt.hist(x, bins = 10, color='blue', alpha=0.5)

plt.show()