0% found this document useful (0 votes)
6 views18 pages

Data Visualization With Python

This document provides an overview of data visualization using Python, highlighting the importance of visual representation for data analysis. It introduces four key libraries: Matplotlib, Seaborn, Bokeh, and Plotly, and demonstrates how to use Matplotlib for creating various types of graphs, including scatter plots and line charts. The tutorial also includes examples using a tips database to illustrate the plotting techniques.

Uploaded by

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

Data Visualization With Python

This document provides an overview of data visualization using Python, highlighting the importance of visual representation for data analysis. It introduces four key libraries: Matplotlib, Seaborn, Bokeh, and Plotly, and demonstrates how to use Matplotlib for creating various types of graphs, including scatter plots and line charts. The tutorial also includes examples using a tips database to illustrate the plotting techniques.

Uploaded by

ybbharani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Data Visualization with Python




In today's world, a lot of data is being generated on a daily basis. And
sometimes to analyze this data for certain trends, patterns may become
difficult if the data is in its raw format. To overcome this data
visualization comes into play. Data visualization provides a good,
organized pictorial representation of the data which makes it easier to
understand, observe, analyze. In this tutorial, we will discuss how to
visualize data using Python.

Python provides various libraries that come with different features for
visualizing data. All these libraries come with different features and can
support various types of graphs. In this tutorial, we will be discussing
four such libraries.
Matplotlib
Seaborn
Bokeh
Plotly
We will discuss these libraries one by one and will plot some most
commonly used graphs.
Before diving into these libraries, at first, we will need a database to plot
the data. We will be using the tips database for this complete tutorial.
Let's discuss see a brief about this database.
Database Used

Tips Database

Tips database is the record of the tip given by the customers in a


restaurant for two and a half months in the early 1990s. It contains 6
columns such as total_bill, tip, sex, smoker, day, time, size.
You can download the tips database from here.
Example:
import pandas as pd

# reading the database


data = pd.read_csv("[Link]")

# printing the top 10 rows


display([Link](10))
Output:

Matplotlib
Matplotlib is an easy-to-use, low-level data visualization library that is
built on NumPy arrays. It consists of various plots like scatter plot, line
plot, histogram, etc. Matplotlib provides a lot of flexibility.
To install this type the below command in the terminal.
pip install matplotlib
Scatter Plot

Scatter plots are used to observe relationships between variables and


uses dots to represent the relationship between them.
The scatter() method in the matplotlib library is used to draw a scatter
plot.
Example:
import pandas as pd
import [Link] as plt

# reading the database


data = pd.read_csv("[Link]")

# Scatter plot with day against tip


[Link](data['day'], data['tip'])

# Adding Title to the Plot


[Link]("Scatter Plot")

# Setting the X and Y labels


[Link]('Day')
[Link]('Tip')

[Link]()
Output:
This graph can be more meaningful if we can add colors and also change
the size of the points. We can do this by using the c and
s parameter respectively of the scatter function. We can also show the
color bar using the colorbar() method.
Example:
import pandas as pd
import [Link] as plt

# reading the database


data = pd.read_csv("[Link]")

# Scatter plot with day against tip


[Link](data['day'], data['tip'], c=data['size'],
s=data['total_bill'])

# Adding Title to the Plot


[Link]("Scatter Plot")

# Setting the X and Y labels


[Link]('Day')
[Link]('Tip')

[Link]()

[Link]()
Output:
Matplotlib Scatter



Scatter plots are one of the most fundamental tools for visualizing
relationships between two numerical variables.
[Link]() plots points on a Cartesian plane defined by X
and Y coordinates. Each point represents a data observation, allowing us
to visually analyze how two variables correlate, cluster or distribute.
For example:
import [Link] as plt
import numpy as np

x = [Link]([12, 45, 7, 32, 89, 54, 23, 67, 14, 91])


y = [Link]([99, 31, 72, 56, 19, 88, 43, 61, 35, 77])

[Link](x, y)
[Link]("Basic Scatter Plot")
[Link]("X Values")
[Link]("Y Values")
[Link]()
Output
Using [Link]()
Explanation: [Link](x, y) creates a scatter plot on a 2D plane to
visualize the relationship between two variables, with a title and axis
labels added for clarity and context.

Syntax

[Link](x, y, s=None, c=None, marker=None,


cmap=None, label=None)
Parameters:
Paramet
er Description

x, y Sequences of data points to plot

s Marker size (scalar or array-like)

c Marker color

marker Shape of the marker

Colormap for mapping numeric values to


cmap
colors

label Legend label for the dataset

Returns: This function returns a PathCollection object representing the


scatter plot points. This object can be used to further customize the plot
or to update it dynamically.
Examples
Example 1: In this example, we compare the height and weight of two
different groups using different colors for each group.
x1 = [Link]([160, 165, 170, 175, 180, 185, 190, 195, 200,
205])
y1 = [Link]([55, 58, 60, 62, 64, 66, 68, 70, 72, 74])

x2 = [Link]([150, 155, 160, 165, 170, 175, 180, 195, 200,


205])
y2 = [Link]([50, 52, 54, 56, 58, 64, 66, 68, 70, 72])

[Link](x1, y1, color='blue', label='Group 1')


[Link](x2, y2, color='red', label='Group 2')

[Link]('Height (cm)')
[Link]('Weight (kg)')
[Link]('Comparison of Height vs Weight between two
groups')
[Link]()
[Link]()
Output

Using [Link]()
Explanation: We define NumPy arrays x1, y1 and x2, y2 for height and
weight data of two groups. Using [Link](), Group 1 is plotted in blue
and Group 2 in red, each with labels. The x-axis and y-axis are labeled
"Height (cm)" and "Weight (kg)" for clarity.

Example 2: This example demonstrates how to customize a scatter plot


using different marker sizes and colors for each point. Transparency and
edge colors are also adjusted.
x = [Link]([3, 12, 9, 20, 5, 18, 22, 11, 27, 16])
y = [Link]([95, 55, 63, 77, 89, 50, 41, 70, 58, 83])

a = [20, 50, 100, 200, 500, 1000, 60, 90, 150, 300] # size
b = ['red', 'green', 'blue', 'purple', 'orange', 'black',
'pink', 'brown', 'yellow', 'cyan'] # color
[Link](x, y, s=a, c=b, alpha=0.6, edgecolors='w',
linewidths=1)
[Link]("Scatter Plot with Varying Colors and Sizes")
[Link]()
Output

Using [Link]()
Explanation: NumPy arrays x and y set point coordinates, a defines
marker sizes and b assigns colors. [Link]() plots the points with
transparency, white edges and linewidth. A title is added before
displaying the plot.

Line Chart

Line Chart is used to represent a relationship between two data X and Y


on a different axis. It is plotted using the plot() function. Let’s see the
below example.
Example:
import pandas as pd
import [Link] as plt

# reading the database


data = pd.read_csv("[Link]")

# Scatter plot with day against tip


[Link](data['tip'])
[Link](data['size'])

# Adding Title to the Plot


[Link]("Scatter Plot")

# Setting the X and Y labels


[Link]('Day')
[Link]('Tip')

[Link]()
Output:

Line chart in Matplotlib - Python




A line chart or line plot is a graphical representation used to show the
relationship between two continuous variables by connecting data points
with a straight line. It is commonly used to visualize trends, patterns or
changes over time.
In Matplotlib line charts are created using the pyplot sublibrary which
provides simple and flexible functions for plotting data. In a line chart,
the x-axis typically represents the independent variable while the y-axis
represents the dependent variable.
Syntax: [Link](x, y, color, linestyle, linewidth, marker)
where:
 x : The values for the x-axis
 y : The corresponding values for the y-axis
 color: Specifies the color of the line
 linestyle: Defines the style of the line
 linewidth: Controls the thickness of the line
 marker: Adds markers at data points
Consider a simple example where we visualise the weekly temperature
using a line chart in Matplotlib
import [Link] as plt
import numpy as np

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']


temperature = [22, 24, 23, 26, 25]
[Link](days, temperature, marker='o')
[Link]('Weekly Temperature')
[Link]('Days')
[Link]('Temperature (°C)')
[Link]()
Output:

Line Chart
1. Matplotlib Simple Line Plot
A line plot is used to represent the relationship between two continuous
variables. Matplotlib provides the plot() function through its pyplot
module to create simple and advanced line charts efficiently.

Simple Line Plot

For creating a basic line chart, you can use the plot() function. This
function draws a line by connecting data points on the x-axis and y-axis,
making it easy to visualize relationships between two continuous
variables.
import [Link] as plt
import numpy as np

x = [Link]([1, 2, 3, 4])
y = x * 2

[Link](x, y)
[Link]()
Output:
Simple Line chart

Adding Labels and Title to a Line Plot

To improve readability, you can use the xlabel(), ylabel() and title()
functions. These functions help in clearly identifying the axes and the
purpose of the line chart.
import [Link] as plt
import numpy as np

x = [Link]([1, 2, 3, 4])
y = x * 2

[Link](x, y)
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Simple Line Plot with Labels")
[Link]()
Output:
Simple line plot with axis labels and title.

Using Markers in Line Plots

Markers help highlight individual data points on a line plot making it


easier to identify exact values. They are especially useful for small
datasets or precise comparisons. The marker parameter in [Link]()
specifies the shape of symbols used to mark each data point.
import [Link] as plt
import numpy as np

x = [Link]([1, 2, 3, 4, 5])
y = [3, 6, 9, 12, 15]

[Link](x, y, marker='o', linestyle='-', label='Data


Points')
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Line Plot with Markers")
[Link]()
[Link]()
Output:

Markers in Line Plots


2. Adding Grid to a Line Chart
Grids make it easier to read values and follow trends across the chart.
You can enable grids using the grid() function
import [Link] as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
[Link](x, y)
[Link](True)
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Line Plot with Grid")
[Link]()
Output:

Grid
3. Line Chart with Annotations
For adding annotations to a line chart you can use the annotate()
function. This function allows you to display additional information such
as the exact x and y values directly on the data points, improving clarity
and data interpretation.
import [Link] as plt

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

[Link](figsize=(8, 6))
[Link](x, y, marker='o', linestyle='-')

for xi, yi in zip(x, y):


[Link](f'({xi}, {yi})',
(xi, yi),
textcoords="offset points",
xytext=(0, 10),
ha='center')

[Link]('Line Chart with Annotations')


[Link]('X-axis')
[Link]('Y-axis')
[Link](True)
[Link]()
Output:
Line chart with annotated data points.
4. Multiple Line Charts Using Matplotlib
To create multiple line charts in separate containers you can use the
figure() function. Each call to figure() generates a new plotting area,
making it easier to visualize and compare different datasets
independently.
import [Link] as plt
import numpy as np

x = [Link]([1, 2, 3, 4])
y = x * 2

[Link](x, y)
[Link]("First Line Chart")
[Link]()

[Link]()
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
[Link](x1, y1, '-.')
[Link]("Second Line Chart")
[Link]()
Output:
Multiple Line Charts
5. Multiple Plots on the Same Axis
To plot multiple lines on the same axis, you can call the plot() function
multiple times before displaying the graph. This approach is useful for
comparing different datasets within the same coordinate system.
import [Link] as plt
import numpy as np

x = [Link]([1, 2, 3, 4])
y = x * 2

x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]

[Link](x, y, label='y = 2x')


[Link](x1, y1, '-.', label='Second Line')

[Link]("X-axis data")
[Link]("Y-axis data")
[Link]("Multiple Plots on Same Axis")
[Link]()
[Link]()
Output:

Multiple Plots on the Same Axis


6. Fill the Area Between Two Lines
To fill the region between two line plots, you can use the fill_between()
function. This function shades the area between two curves, helping
visualize the difference or range between datasets.
import [Link] as plt
import numpy as np

x = [Link]([1, 2, 3, 4])
y = x * 2
y1 = [3, 5, 7, 9]

[Link](x, y, label='y = 2x')


[Link](x, y1, '-.', label='y1')

plt.fill_between(x, y, y1, color='green', alpha=0.4)

[Link]("X-axis data")
[Link]("Y-axis data")
[Link]("Filled Area Between Two Lines")
[Link]()
[Link]()
Output:
Filled Area Between Two Lines
7. Saving a Line Chart to a File
Instead of displaying a plot you can save it as an image using the
savefig() function.
import [Link] as plt

x = [1, 2, 3, 4]
y = [2, 4, 6, 8]

[Link](x, y)
[Link]("Saved Line Plot")
[Link]("line_plot.png")
[Link]()
Output:

8. Plotting Trigonometric Functions


Trigonometric functions such as sine, cosine and tangent can be
visualized using [Link]() by generating input values over a continuous
range. The [Link]() function creates evenly spaced values,
allowing smooth and accurate curves.
import numpy as np
import [Link] as plt

x = [Link](0, 2 * [Link], 100)


y_sin = [Link](x)
y_cos = [Link](x)

[Link](x, y_sin, label="sin(x)")


[Link](x, y_cos, label="cos(x)")
[Link]("X values")
[Link]("Function value")
[Link]("Trigonometric Functions")
[Link]()
[Link]()
Output:

You might also like