0% found this document useful (0 votes)
9 views33 pages

Line Chart

The document provides an overview of data visualization using the Matplotlib library in Python, detailing how to create various types of plots, customize them, and save figures. It includes examples of plotting temperature and weight versus height, along with explanations of different plot components such as titles, labels, legends, and styles. Additionally, it covers the use of Pandas for reading data from CSV files and plotting line charts with customizations.

Uploaded by

reshmaras
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)
9 views33 pages

Line Chart

The document provides an overview of data visualization using the Matplotlib library in Python, detailing how to create various types of plots, customize them, and save figures. It includes examples of plotting temperature and weight versus height, along with explanations of different plot components such as titles, labels, legends, and styles. Additionally, it covers the use of Pandas for reading data from CSV files and plotting line charts with customizations.

Uploaded by

reshmaras
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/ 33

Introduction

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.
Plotting using MatPlotlib
Matplotlib library is used for creating static, animated, and interactive
2D- plots or figures in Python.
It can be installed using the following pip command from the
command prompt:pip install matplotlib

For plotting using Matplotlib, we need to import its Pyplot module using the
following command:
import matplotlib.pyplot as plt
plt is an alias or an alternative name for matplotlib.pyplot.
• 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 is the overall window where the outputs of pyplot functions
are plotted.
• A figure contains a plotting area, legend, axis labels, ticks, title, etc.
• while presenting data we should always give a chart title
• label the axis of the chart and provide legend in case we have more
than one plotted data.
• To plot x versus y, we can write plt.plot(x,y).
• show() function is used to display the figure created using the plot()
function.
Components of a plot
• Program: To demonstrates how to plot temperature values for the
given dates. The output generated is a line chart.
import matplotlib.pyplot as plt
date=["25/12","26/12","27/12"]
temp=[8.5,10.5,6.8]
plt.plot(date, temp)
plt.show()
➢ 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. The name of the
figure is passed to the function as parameter.
For example: plt.savefig('x.png')
List of Pyplot functions to plot different charts
Customisation of Plots-List of Pyplot
functions to customise plots
Program :To Plotting a line chart of date versus temperature by adding
Label on X and Y axis, and adding a Title and Grids to the chart.
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")
plt.ylabel("Temperature")
plt.title("Date wise Temperature")
plt.grid(True) #easy to locate point
plt.yticks(temp)
plt.show() ticks
import numpy as np
import matplotlib.pyplot as plt

# values of x and y axes


valx = [30, 35, 50, 5, 10, 40, 45, 15, 20, 25]
valy = [1, 4, 3, 2, 7, 6, 9, 8, 10, 5]

plt.plot(valx, valy)
plt.xlabel('X-axis')
plt.ylabel('Y-axis’)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# values of x and y axes
valx = [30, 35, 50, 5, 10, 40, 45, 15,
20, 25]
valy = [1, 4, 3, 2, 7, 6, 9, 8, 10, 5]
plt.plot(valx, valy)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.xticks(np.arange(0, 60, 5))
plt.yticks(np.arange(0, 15, 1))
plt.show()
Marker
A marker
is any
symbol
that
represent
s a data
value in a
line chart
or a
scatter
plot.
Colour
We can either use
character codes or
the color names as
values to the
parameter color in
the plot().
Linewidth and Line Style
• The linewidth and linestyle property can be used to change the width
and the style of the line chart.
• Linewidth is specified in pixels.
• The default line width is 1 pixel showing a thin line.
• Thus, a number greater than 1 will output a thicker line depending
on the value provided.
• We can also set the line style of a line chart using the linestyle
parameter.
• It can take a string such as "solid", "dotted", "dashed" or "dashdot"
Program 4-3 Consider the average heights and weights of persons aged
8 to 16 stored in the following two lists
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]
Let us plot a line chart where:
i. x axis will represent weight ii. y axis will represent height
iii. x axis label should be “Weight in kg” iv. y axis label should be
“Height in cm”
v. colour of the line should be green vi. use * as marker
vii. Marker size as10 viii. The title of the chart should be “Average
weight with respect to average height”. ix. Line style should be dashed
x. Linewidth should be 2.
Code:
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})
plt.xlabel('Weight in kg')
plt.ylabel('Height in cm')
plt.title('Average weight with respect to average height')
plt.plot(df.weight,df.height,marker='*',markersize=10,color='g',linewidth
=2, linestyle='dashdot')
plt.show() • can give markeredgecolor=“b”
output
import matplotlib.pyplot as plt
ip=[10,15,59]
acc=[15,17,49]
bs=[9,19,69]
x=["ip","acc","bs"]
plt.plot(x,ip)
plt.plot(x,acc)
plt.plot(x,bs)
plt.show()
import matplotlib.pyplot as plt
ip=[10,15,59]
acc=[15,17,49] Label for legend
bs=[9,19,69]
x=["ip","acc","bs"]
plt.plot(x,ip,color='b',label="IP")
plt.plot(x,acc,color='k',label="acc")
plt.plot(x,bs,color='m',label="bs")
plt.legend()
plt.show()
import matplotlib.pyplot as plt
ip=[10,15,59]
acc=[15,17,49]
bs=[9,19,69]
x=["ip","acc","bs"]
plt.plot(x,ip,color='b',label="IP")
plt.plot(x,acc,color='k',label="acc")
plt.plot(x,bs,color='m',label="bs")
plt.legend(loc="center")
#ValueError: 'left' is not a valid value for loc;
#supported values are 'best', 'upper right', 'upper
left',
#'lower left', 'lower right', 'right', 'center left',
#'center right', 'lower center', 'upper center', 'center'
plt.show()
import matplotlib.pyplot as plt
ip=[10,15,59]
acc=[15,17,49]
bs=[9,19,69]
x=["ip","acc","bs"]
plt.plot(x,ip,color='b',label="IP",linewidth=5)
plt.plot(x,acc,color='k',label="acc")
plt.plot(x,bs,color='m',label="bs")
plt.legend(loc="center")
plt.show()
import matplotlib.pyplot as plt
ip=[10,15,59] can write dashed for – and
acc=[15,17,49] dashdot for -.
bs=[9,19,69]
x=["ip","acc","bs"]
plt.plot(x,ip,color='b',label="IP",linewidth=5,linestyle="--")
plt.plot(x,acc,color='k',label="acc",linestyle="-.")
plt.plot(x,bs,color='m',label="bs")
plt.legend(loc="center")
plt.show()
import matplotlib.pyplot as plt
ip=[10,15,59]
acc=[15,17,49]
bs=[9,19,69]
x=["ip","acc","bs"]
plt.plot(x,ip,color='b',label="IP",linewidth=5,linestyle="")
plt.plot(x,acc,color='k',label="acc",linestyle="-.")
plt.plot(x,bs,color='m',label="bs")
plt.legend(loc="center")
plt.show()
#supported values are '-', '--', '-.', ':', 'None',
#' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
import matplotlib.pyplot as plt
ip=[10,15,59]
acc=[15,17,49]
bs=[9,19,69]
x=["ip","acc","bs"]
plt.plot(x,ip,color='b',label="IP",linewidth=5,
linestyle=“--”,marker='*’,
markeredgecolor='k',markersize=10)
plt.plot(x,acc,color='k',label="acc",linestyle="-.")
plt.plot(x,bs,color='m',label="bs")
plt.legend(loc="center")
plt.show()
Use a shortcut
[color],[marker],[line]
import matplotlib.pyplot as plt
ip=[10,15,59]
acc=[15,17,49]
bs=[9,19,69]
x=["ip","acc","bs"]
plt.plot(x,ip,"y8--",label="IP")
plt.plot(x,acc,color='k',label="acc",linestyle="-.")
plt.plot(x,bs,color='m',label="bs")
plt.legend(loc="center")
plt.show()
Arguments accepted by kind for different
plots
• The plot() method of Pandas accepts a considerable number of
arguments that can be used to plot a variety of graphs.
• It allows customizing different plot types by supplying the kind
keyword arguments.
• The general syntax is: plt.plot(kind),where kind accepts a string
indicating the type of .plot
• In addition, we can use the matplotlib.pyplot methods and
functions also along with the plt() method of Pandas objects.
Arguments accepted by kind for different
plots
Plotting a Line chart
To plot a line chart for data stored in a DataFrame.
Ques: Smile NGO has participated in a three week cultural mela. Using
Pandas, they have stored the sales (in Rs) made day wise for every week in
a CSV file named “MelaSales.csv”
Depict the sales for the three weeks
using a Line chart. It should have the
following:
i. Chart title as “Mela Sales Report”.
ii. axis label as Days.
iii. axis label as “Sales in Rs”.
iv. Line colors are red for week 1, blue
for week 2 and brown for week 3.
Code
import pandas as pd
import matplotlib.pyplot as plt
# reads "MelaSales.csv" to df by giving path to the file
df=pd.read_csv("E:\lms\GRADE_12_IP_notes\matplotlib\MelaSales.csv")
#create a line plot of different color for each week
df.plot(kind='line', color=['red','blue','brown'])
plt.title('Mela Sales Report')
plt.xlabel('Days')
plt.ylabel('Sales in Rs')
plt.show()
Output
Customising Line Plot
Program : Assuming the same CSV file, i.e., MelaSales. CSV, plot the
line chart with following customisations:
Maker ="*"
Marker size=10
linestyle="--"
Linewidth =3
Program
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv("E:\lms\GRADE_12_IP_notes\matplotlib\MelaSales.csv")
#creates plot of different color for each week
df.plot(kind='line',color=['red','blue','brown'],marker="*",markersize=10,linewidth=3,linestyle="--")
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()
Output

You might also like