0% found this document useful (0 votes)
147 views

Plotting Data Using Matplotlib

Uploaded by

rajeev0305
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views

Plotting Data Using Matplotlib

Uploaded by

rajeev0305
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Plotting Data Using

matplotlib

© KIIT 2014
Objectives
After completing this lesson, you should be able to do
the following:
• Explain Visualizations
• Plotting using Matplotlib
• Customisation of Plots
• The Pandas Plot Function (Pandas Visualisation)

© KIIT 2014
Introduction
• Data visualization is the discipline of trying to
understand data by placing it in a visual context so
that patterns, trends and correlations that might not
otherwise be detected can be exposed.
• Data visualisation means graphical or pictorial
representation of the data using graph, chart, etc.
The purpose of plotting data is to visualise variation
or show relationships between variables.

© KIIT 2014
Contd..
• Visualisation also helps to effectively communicate
information to intended users.
• Visualisation of data is effectively used in fields like
health, finance, science, mathematics, engineering,
etc.
• Python offers multiple great graphing libraries that
come packed with lots of different features.

© KIIT 2014
Data Visualization
• To get a little overview here are a few popular
plotting libraries:
– Matplotlib: low level, provides lots of freedom
– Pandas Visualization: easy to use interface, built on
Matplotlib
– Seaborn: high-level interface, great default styles
– ggplot: based on R’s ggplot2, uses Grammar of Graphics
– Plotly: can create interactive plots

© KIIT 2014
Plotting Using matplotlib

• Matplotlib library is used for creating static,


animated, and interactive 2D- plots or figures in
Python.
• Install
pip install matplotlib

• For Plotting
import matplotlib.pyplot as plt

© KIIT 2014
Components of a Plot

© KIIT 2014
Plotting Using matplotlib
• The pyplot module of matplotlib contains a
collection of functions that can be used to work on a
plot.
• The plot() function of the pyplot module is used
to create a figure.
• A figure contains a plotting area, legend, axis labels,
ticks, title, etc.

© KIIT 2014
Plotting Using matplotlib

• Example:
import matplotlib.pyplot as plt
#list storing date in string format
date=["25/12","26/12","27/12"]
#list storing temperature values
temp=[8.5,10.5,6.8]
#create a figure plotting temp versus
date
plt.plot(date, temp)
#show the figure
plt.show()

© KIIT 2014
Plotting Using matplotlib

• The plot() function by default plots a line chart.


• We can click on the save button on the output
window and save the plot as an image.
• A figure can also be saved by using savefig()
function.
• Example:

plt.savefig(‘line.png')

© KIIT 2014
pyplot Functions
• List of pyplot functions to plot different charts

© KIIT 2014
Customization of Plots
• Pyplot library gives us numerous functions to customise
charts such as adding titles or legends.

© KIIT 2014
Customization of Plots
• Example:
import matplotlib.pyplot as plt
date=["25/12","26/12","27/12"]
temp=[8.5,10.5,6.8]
plt.plot(date, temp)
plt.xlabel("Date") #add the Label on x-axis
plt.ylabel("Temperature") #add the Label on y-axis
plt.title("Date wise Temperature") #add the title
to the chart
plt.grid(True) #add gridlines to the background
plt.yticks(temp)
plt.show()

© KIIT 2014
Marker
• Other changes can be made into plots by passing
various parameters to the plot() function.
• It is also possible to specify each point in the line
through a marker.
• A marker is any symbol that represents a data value
in a line chart or a scatter plot.

© KIIT 2014
matplotlib Markers

© KIIT 2014
Colour
• It is possible to format the plot further be changing
the colour of the plotted area.

© KIIT 2014
Linewidth and Line Style
• The width and style of line chart can also be changed
• Example:

import matplotlib.pyplot as plt


import pandas as pd
height=[121.9,124.5,129.5,134.6,139.7,147.3,152.4,
157.5,162.6]
weight=[19.7,21.3,23.5,25.9,28.5,32.1,35.7,39.6,43
.2]
df=pd.DataFrame({"height":height,"weight":weight})
#Set xlabel for the plot
plt.xlabel('Weight in kg‘)

© KIIT 2014
Linewidth and Linestyle
• Example..

#Set ylabel for the plot


plt.ylabel('Height in cm')
#Set chart title:
plt.title('Average weight with respect to average
height')
#plot using marker'-*' and line colour as green
plt.plot(df.weight,df.height,marker='*',markersize
=10,color='green
',linewidth=2, linestyle='dashdot')
plt.show()

© KIIT 2014
The Pandas Plot function (Pandas
Visualisation)
• Pandas objects Series and DataFrame come
equipped with their own .plot() methods.
• This plot() method is just a simple wrapper
around the plot() function of pyplot.
• The plot() method of Pandas accepts a
considerable number of arguments that can be used
to plot a variety of graphs.

© KIIT 2014
plot() Method of Pandas
• The general syntax is: plt.plot(kind).

© KIIT 2014
Plotting a Line Chart
• Line plot graph shows the frequency of data along a
line number. Example:
import pandas as pd
import matplotlib.pyplot as plt
# reads "MelaSales.csv" to df by giving
path to the file
df=pd.read_csv("MelaSales.csv")
#create a line plot of different color for
each week
df.plot(kind='line',
color=['red','blue','brown'])

© KIIT 2014
Plotting a Line Chart
• Example..

# Set title to "Mela Sales Report"


plt.title('Mela Sales Report')
# Label x axis as "Days"
plt.xlabel('Days')
# Label y axis as "Sales in Rs"
plt.ylabel('Sales in Rs')
#Display the figure
plt.show()

© KIIT 2014
Customizing Line Plot
• Substitute the ticks at x axis with a list of values of
our choice by using plt.xticks(ticks,label)
Maker ="*"
Marker size=10
linestyle="--"
Linewidth =3
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv("MelaSales.csv")
#creates plot of different color for each week
df.plot(kind='line',
color=['red','blue','brown'],marker="*",marke
rsize=10,linewidth=3,linestyle="--")

© KIIT 2014
Customizing Line Plot
• Example Conti..
plt.title('Mela Sales Report')
plt.xlabel('Days')
plt.ylabel('Sales in Rs')
#store converted index of DataFrame to a list
ticks = df.index.tolist()
#displays corresponding day on x axis
plt.xticks(ticks,df.Day)
plt.show()

© KIIT 2014
Plotting Bar Chart
• To show comparisons, we prefer Bar charts. Unlike
line plots, bar charts can plot strings on the x axis.
import pandas as pd
df= pd.read_csv('MelaSales.csv')
import matplotlib.pyplot as plt
# plots a bar chart with the column "Days"
as x axis
df.plot(kind='bar',x='Day',title='Mela
Sales Report')
#set title and set ylabel
plt.ylabel('Sales in Rs')
plt.show()

© KIIT 2014

You might also like