0% found this document useful (0 votes)
3 views28 pages

5th Module

The document provides an overview of data visualization, emphasizing its importance in representing complex data through various graphical formats such as bar charts, line charts, and scatter plots. It also introduces Matplotlib, a Python library for creating diverse visualizations, detailing its features, customization options, and examples of plotting. Additionally, it explains the interpretation and customization of different types of graphs, including scatter plots, bar graphs, and histograms.

Uploaded by

ksamboji001
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)
3 views28 pages

5th Module

The document provides an overview of data visualization, emphasizing its importance in representing complex data through various graphical formats such as bar charts, line charts, and scatter plots. It also introduces Matplotlib, a Python library for creating diverse visualizations, detailing its features, customization options, and examples of plotting. Additionally, it explains the interpretation and customization of different types of graphs, including scatter plots, bar graphs, and histograms.

Uploaded by

ksamboji001
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

Data Visualiza on Data Analy cs using Python(22MCA31)

Data visualization
It refers to the graphical representation of information and data. It utilizes visual elements such
as charts, graphs, and maps to communicate complex data in a way that is easy to understand
and interpret. The primary goal of data visualization is to make patterns, trends, and insights
apparent from the data, enabling better decision-making and understanding.

Types of data visualizations

1. Bar Charts: These are used to compare categories of data. The length of each bar
represents the value it represents.
2. Line Charts: Line charts are ideal for showing trends over time. They connect
data points with lines, making it easy to see how values change.
3. Pie Charts: Pie charts show the composition of a whole by dividing it into slices.
Each slice represents a proportion of the whole.
4. Scatter Plots: Scatter plots are used to show the relationship between two
variables. Each point represents a single data point, with one variable plotted on
the x-axis and the other on the y-axis.
5. Histograms: Histograms are similar to bar charts but are used for representing
the distribution of continuous data. The bars represent the frequency of data
within predefined intervals.
6. Heatmaps: Heatmaps use color-coding to represent data values in a matrix. They
are particularly useful for visualizing data density or correlations.
7. Treemaps: Treemaps represent hierarchical data as a series of nested rectangles.
Each rectangle represents a category, and its size corresponds to a specific value
or metric.
8. Word Clouds: Word clouds visualize text data by displaying words in varying
sizes based on their frequency or importance within the text.
9. Choropleth Maps: Choropleth maps use color shading to represent data values
within predefined geographical regions, such as countries, states, or counties.
10. Network Diagrams: Network diagrams visualize relationships between entities
as nodes and edges. They are commonly used in social network analysis, systems
biology, and other fields.

Matplotlib

It is a popular Python library used for creating static, animated, and interactive
visualizations in Python. It provides a wide range of plotting functionality for various
types of data visualization tasks. Here's a brief overview of some key features and
functionalities of Matplotlib:

1. Basic Plots: Matplotlib allows you to create a variety of basic plots such as line
plots, scatter plots, bar plots, histogram, pie charts, etc.

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
2. Customization: You can customize almost every aspect of your plot, including
colors, line styles, markers, fonts, axes, labels, and more.
3. Multiple Axes: Matplotlib supports multiple axes on a single figure, allowing you
to create complex layouts with subplots.
4. Annotations and Text: You can add annotations, text, arrows, and shapes to
your plots to highlight specific points or regions of interest.
5. Exporting: Matplotlib supports various file formats for saving plots, including
PNG, PDF, SVG, and more.
6. Integration: Matplotlib can be easily integrated with other libraries such as
NumPy, Pandas, and SciPy, making it suitable for data analysis and scientific
computing tasks.
7. Seaborn Integration: Seaborn is built on top of Matplotlib and provides a
higher-level interface for creating attractive statistical graphics. Matplotlib and
Seaborn can be used together seamlessly.
8. Matplotlib Styles: Matplotlib provides predefined styles to quickly change the
appearance of your plots. You can also create custom styles to maintain
consistency across multiple plots.
9. Object-Oriented Interface: Matplotlib offers both a MATLAB-style stateful
interface and an object-oriented interface. The object-oriented approach is more
flexible and powerful, allowing for finer control over the plot elements.
10. Support for 3D Plots: Matplotlib also supports creating 3D plots and
visualizations using the mplot3d toolkit.

# Example demonstrating how to create a basic line plot using Matplotlib:

import [Link] as plt

# Data

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

y = [2, 3, 5, 7, 11]

# Create a line plot

[Link](x, y)

# Add title and labels

[Link]('Simple Line Plot')

[Link]('X-axis')

[Link]('Y-axis')
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
# Display the plot

[Link]()
Controlling Graphs In MatplotLib
In Matplotlib, you can control various aspects of graphs including the axes, labels, titles,
colors, line styles, markers, and more. Here's a basic guide on how to control different
aspects of graphs using Matplotlib:

1. Creating a Graph:
First, it needs to import Matplotlib and specify the data for your graph. Then, you
can use functions like [Link]() to create a line plot, [Link]() for a scatter
plot, etc.

Example-

import [Link] as plt


x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
[Link](x, y) # Line plot
# or [Link] er(x, y) # Sca er plot
[Link]()

Customizing Axes and Labels:


can customize the axes range, labels, ticks, and more using functions like [Link](),
[Link](), [Link](), [Link]() , [Link]() , and [Link]() .

Example-

[Link](x, y)
[Link]('X Label')
[Link]('Y Label')
[Link](0, 6) # Set x-axis range
[Link](0, 12) # Set y-axis range
plt.x cks([1, 2, 3, 4, 5], ['A', 'B', 'C', 'D', 'E']) # Customizing cks
plt.y cks([0, 5, 10], ['Low', 'Medium', 'High'])
[Link]()

Adding Title and Legend:


can add a title to the graph using [Link]() and a legend using [Link]()

Example-

[Link](x, y, label='Data')
plt. tle('My Plot')
[Link]()
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
[Link]()

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
Changing Line Styles and Colors:
You can change line styles, colors, and markers using parameters in the plot functions.

Example-

[Link](x, y, color='red', linestyle='--', marker='o')


[Link]()

Adding Text and Annotations:


You can add text and annotations using [Link]() and [Link]().

Example-

[Link](x, y)
[Link](3, 6, 'Some Text', fontsize=12)
[Link]('Annota on', xy=(3, 5), xytext=(4, 7),
arrowprops=dict(facecolor='black', arrowstyle='->'))
[Link]()

Saving the Figure:


You can save the figure using [Link]()

Example-

[Link](x, y)
[Link]fig('[Link]')

Adding Text To The Graph

Adding text to a graph in Matplotlib is straightforward. You can use the [Link]() function to
add text at any location on the plot. Here's an example of how to add text to a graph:
import [Link] as plt

x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

[Link](x, y)
[Link](3, 6, 'Example Text', fontsize=12, color='blue') # Add text at coordinates (3, 6)
[Link]()

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
In the above example, [Link]() takes three main arguments:

 x: The x-coordinate where you want to place the text.


 y: The y-coordinate where you want to place the text.
 s: The text string that you want to display.

You can also customize the text appearance by specifying additional parameters like
fontsize, color, fontweight, etc. For instance, fontsize=12 sets the font size to 12 points,
and color='blue' sets the text color to blue.

Types of Graphs
scatter graph

A scatter plot is a type of plot that displays values for typically two variables for a set of
data points. Each point on the plot represents an observation in the dataset, with the x-
coordinate representing one variable and the y-coordinate representing the other
variable. Scatter plots are useful for visualizing relationships between variables and
identifying patterns or trends in the data.

Here's a more detailed explanation of scatter plots:

1. Purpose:
Scatter plots are primarily used to investigate the relationship between two
continuous variables. They help to determine whether there is a correlation or
pattern between the variables. Additionally, scatter plots can be used to identify
outliers or clusters within the data.
2. Components:
 Data Points: Each point on the scatter plot represents a single
observation or data point from the dataset. These points are plotted based
on their values for the two variables being compared.
 X-Axis and Y-Axis: The horizontal axis (x-axis) represents one variable,
while the vertical axis (y-axis) represents the other variable. The range of
values for each axis is determined by the minimum and maximum values
of the respective variables in the dataset.
 Labels and Title: Scatter plots typically include axis labels to provide
context for the variables being plotted. Additionally, a title is often
included to describe the overall purpose or theme of the plot.
3. Interpretation:
 Direction: The overall direction of the points on the scatter plot can
indicate the nature of the relationship between the variables. If the points
tend to slope upwards from left to right, it suggests a positive correlation,

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
while a downward slope indicates a negative correlation. A lack of any
clear pattern suggests no correlation.
 Strength: The spread or dispersion of the points around the general
trendline indicates the strength of the relationship between the variables.
A tight cluster of points suggests a strong correlation, while a more
scattered distribution indicates a weaker correlation.
 Outliers: Outlying points that deviate significantly from the main cluster
may indicate anomalies or special cases within the dataset. These outliers
can sometimes provide valuable insights or raise questions about the data.
4. Customization:
Scatter plots can be customized in various ways to enhance their clarity and visual
appeal. Common customizations include adjusting the color, size, and shape of
the data points, adding annotations or labels to specific points, changing the axis
scales or ranges, and incorporating regression lines or other statistical summaries.

Bar graph
A bar graph, also known as a bar chart or bar plot, is a type of chart that presents
categorical data with rectangular bars. The lengths or heights of the bars represent the
values of the corresponding categories. Bar graphs are commonly used to compare and
display the frequency, distribution, or relative size of different categories or groups.
Here's a detailed explanation of bar graphs:

1. Purpose:
Bar graphs are used to visualize categorical data and compare the values of
different categories. They are particularly useful when there are distinct
categories or groups to be compared, such as sales figures for different products,
scores for different teams, or frequencies of different events.
2. Components:
 Bars: The main components of a bar graph are the rectangular bars, each
representing a specific category or group. The length or height of each bar
corresponds to the value of the category it represents.
 Categories: The categories or groups being compared are typically
displayed along the horizontal axis (x-axis) of the graph. Each bar is
associated with a specific category, and the bars are usually arranged in a
logical order.
 Values: The numerical values or frequencies associated with each category
are displayed along the vertical axis (y-axis) of the graph. The scale of the
y-axis is determined by the range of values in the dataset.
 Labels and Title: Bar graphs often include axis labels to provide context
for the categories and values being plotted. A title is also included to
describe the overall theme or purpose of the graph.
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
3. Types of Bar Graphs:
 Vertical Bar Graph: In a vertical bar graph, the bars are oriented vertically,
with the categories displayed along the horizontal axis and the values
displayed along the vertical axis. Vertical bar graphs are commonly used
when the number of categories is relatively small.
 Horizontal Bar Graph: In a horizontal bar graph, the bars are oriented
horizontally, with the categories displayed along the vertical axis and the
values displayed along the horizontal axis. Horizontal bar graphs are often
used when there are many categories or when the category labels are
long.
4. Interpretation:
 Comparison: The main purpose of a bar graph is to compare the values of
different categories visually. The lengths or heights of the bars make it
easy to see which categories have higher or lower values.
 Trends: Bar graphs can also reveal trends or patterns in the data, such as
increasing or decreasing values across categories or fluctuations in
frequency over time.
 Relative Size: The relative size of the bars provides a sense of proportion
and allows viewers to quickly identify the most significant categories or
groups.
5. Customization:
Bar graphs can be customized in various ways to enhance their clarity and
effectiveness. Common customizations include adjusting the colors, widths, and
spacing of the bars, adding annotations or labels to the bars, changing the axis
scales or ranges, and incorporating additional visual elements such as gridlines or
legends.

Histogram

A histogram is a graphical representation of the distribution of numerical data. It


displays the frequencies of data points that fall into specific ranges, or "bins," of values.
Histograms are particularly useful for visualizing the shape, center, and spread of a
dataset, as well as identifying any potential outliers or patterns within the data. Here's a
detailed explanation of histograms:

1. Purpose:
Histograms are used to summarize the distribution of continuous or numerical
data. They provide insights into the underlying structure of the data by showing
how the values are distributed across different ranges or intervals.
2. Components:
 Bins: The range of values in the dataset is divided into a series of intervals,
or "bins," along the horizontal axis (x-axis) of the histogram. Each bin
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
represents a specific range of values, and the width of the bins can vary
depending on the data and the desired level of detail.
 Frequencies: The vertical axis (y-axis) of the histogram represents the
frequency, or count, of data points that fall within each bin. The height of
each bar corresponds to the number of data points in the corresponding
bin.
 Bars: The bars of the histogram represent the frequencies of the data
points within each bin. The bars are typically contiguous and drawn
adjacent to each other, with no gaps between them, to emphasize the
continuous nature of the data distribution.
 Axis Labels and Title: Histograms often include axis labels to indicate the
range of values represented on each axis, as well as a title to describe the
overall theme or purpose of the histogram.
3. Interpretation:
 Shape: The shape of the histogram provides insights into the distribution
of the data. Common shapes include symmetric (bell-shaped), skewed
(positively or negatively), bimodal (having two peaks), or uniform (flat).
 Center: The center of the distribution, or the central tendency, can be
estimated by identifying the peak or highest point of the histogram. This
represents the most common or typical value in the dataset.
 Spread: The spread of the distribution, or the variability of the data, can
be assessed by examining the width of the histogram and the dispersion
of the bars around the center. A wider histogram indicates greater
variability, while a narrower histogram suggests less variability.
 Outliers: Outlying values, or extreme data points that fall outside the main
body of the distribution, can be identified as bars that are significantly
taller or shorter than the surrounding bars. These outliers may represent
anomalies or errors in the data, or they may provide valuable insights into
unique or unusual observations.
4. Customization:
Histograms can be customized in various ways to enhance their clarity and
effectiveness. Common customizations include adjusting the number and width
of the bins, changing the colors and styles of the bars, adding annotations or
labels to the bars, and incorporating additional visual elements such as gridlines
or legends.

Pie Chart

A pie chart is a circular statistical graphic that is divided into slices to illustrate numerical
proportions. In a pie chart, the size of each slice is proportional to the quantity it
represents. Pie charts are commonly used to represent categorical data and are

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
particularly useful for showing the relative sizes of different categories within a dataset.
Here's a detailed explanation of pie charts:

1. Purpose:
Pie charts are used to visually represent the distribution of categorical data. They
provide a simple and intuitive way to show the relative proportions or
percentages of different categories within a dataset. Pie charts are especially
effective when there are only a few categories to compare, and when the data
can be easily divided into distinct groups.
2. Components:
 Slices: The main components of a pie chart are the slices, or sectors, that
make up the circular shape. Each slice represents a specific category or
group within the dataset, and the size of the slice is proportional to the
value or percentage it represents.
 Categories: The categories being compared are typically displayed as
labels or annotations next to each slice of the pie chart. These labels
provide context for the data and make it easier for viewers to interpret the
chart.
 Center: The center of the pie chart is often left empty or labeled with
additional information, such as the total number of observations or the
overall theme of the chart. This helps to focus the viewer's attention on the
slices and categories of interest.
3. Interpretation:
 Proportions: The main purpose of a pie chart is to show the relative
proportions or percentages of the different categories within the dataset.
The size of each slice corresponds to the proportion of the total dataset
that belongs to that category.
 Comparison: Pie charts make it easy to compare the sizes of different
categories at a glance. Viewers can quickly see which categories are larger
or smaller relative to each other, and identify any significant differences or
patterns in the data.
 Percentages: Pie charts often include labels or annotations that display
the exact percentages or values represented by each slice. This allows
viewers to interpret the data more accurately and make informed
comparisons between categories.
4. Use Cases:
 Market Share: Pie charts are commonly used to illustrate the market
share of different companies or products within a particular industry.
 Budget Allocation: Pie charts can be used to show how a budget is
allocated among different categories or spending priorities, such as
education, healthcare, transportation, etc.

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
 Survey Results: Pie charts are often used to visualize the results of surveys
or polls, showing the distribution of responses across various answer
choices.
5. Customization:
Pie charts can be customized in various ways to enhance their clarity and visual
appeal. Common customizations include adjusting the colors, labels, and sizes of
the slices, adding annotations or legends to provide additional context, and
incorporating visual elements such as shadows or 3D effects to make the chart
more visually engaging.

Line Graph

A line graph, also known as a line plot or line chart, is a type of chart that displays data
points connected by straight lines. It is particularly useful for visualizing the trend or
relationship between two variables over time or any continuous dimension. Here's a
detailed explanation of line graphs:

1. Purpose:
Line graphs are used to illustrate trends, patterns, or relationships in data over
time or other continuous intervals. They are commonly used in various fields,
including economics, finance, science, and engineering, to visualize changes in
variables such as stock prices, temperature, population growth, and more.
2. Components:
 Data Points: The main components of a line graph are the individual data
points representing specific values of the variables being plotted. Each
data point consists of a pair of values, typically representing the
independent variable (e.g., time) and the dependent variable (e.g.,
temperature).
 Lines: The data points are connected by straight lines, forming a
continuous line plot that represents the relationship between the variables.
The lines emphasize the trend or pattern in the data and make it easier to
visualize changes over time or other intervals.
 Axes: The horizontal axis (x-axis) of the line graph typically represents the
independent variable, such as time or another continuous dimension. The
vertical axis (y-axis) represents the dependent variable and displays the
values corresponding to each data point.
 Labels and Title: Line graphs often include axis labels to indicate the
variables being plotted and a title to describe the overall theme or
purpose of the graph. These labels provide context and help viewers
interpret the data more easily.
3. Interpretation:

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
 Trend: The main purpose of a line graph is to show the trend or pattern in
the data over time or other continuous intervals. By connecting the data
points with lines, line graphs make it easy to visualize changes,
fluctuations, or trends in the variables being plotted.
 Direction: The direction of the lines (upward, downward, or horizontal)
indicates the direction of change in the dependent variable relative to the
independent variable. An upward-sloping line indicates an increasing
trend, a downward-sloping line indicates a decreasing trend, and a
horizontal line indicates no change.
 Rate of Change: The steepness or slope of the lines provides information
about the rate of change in the dependent variable relative to the
independent variable. A steeper slope indicates a faster rate of change,
while a shallower slope indicates a slower rate of change.
 Patterns and Relationships: Line graphs can also reveal patterns or
relationships between variables, such as correlations, seasonality, cycles, or
trends over time. These patterns can provide insights into the underlying
dynamics of the data and inform decision-making or forecasting.
4. Customization:
Line graphs can be customized in various ways to enhance their clarity and
effectiveness. Common customizations include adjusting the colors, styles, and
thickness of the lines, adding markers or symbols to the data points, changing
the axis scales or ranges, and incorporating additional visual elements such as
gridlines or legends.

Note: Refer Lab program number 6 for example

Getting and setting values


In the context of programming and data visualization libraries like Matplotlib, getting
and setting values typically refers to accessing or modifying properties of plots, figures,
or specific elements within them. Here's a basic explanation of how you can get and set
values in Matplotlib:

1. Getting Values:
To get the current values of various properties in Matplotlib, you can use specific
getter functions. For example, to get the current limits of the x-axis in a plot, you
can use [Link]() or ax.get_xlim() if you have an Axes object ( ax). Similarly, to
get the current labels of the x-axis, you can use [Link]() or ax.get_xlabel().
Example-
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
import [Link] as plt
# Create a simple plot
[Link]([1, 2, 3], [4, 5, 6])
[Link]('X Label')
[Link]('Y Label')
# Ge ng current values
x_limits = [Link]() # Get x-axis limits
x_label = [Link]() # Get x-axis label

print("Current x-axis limits:", x_limits)


print("Current x-axis label:", x_label)
Setting Values:
To set new values for properties in Matplotlib, you can use setter functions. For example,
to change the limits of the x-axis, you can use [Link](new_min, new_max) or
ax.set_xlim(new_min, new_max) if you have an Axes object. Similarly, to set a new label for
the x-axis, you can use [Link]('New Label') or ax.set_xlabel('New Label').

Example
import [Link] as plt
# Create a simple plot
[Link]([1, 2, 3], [4, 5, 6])
[Link]('X Label')
[Link]('Y Label')
# Se ng new values
[Link](0, 4) # Set new x-axis limits
[Link]('New X Label') # Set new x-axis label

For Specific Elements:


If you have multiple elements in a plot (e.g., lines, markers, annotations), you can also
get and set properties specific to those elements. For example, if you have a line plot

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
and you want to change the color of a specific line, you can get the line object and set
its color property.
import [Link] as plt

# Create a simple plot


line, = [Link]([1, 2, 3], [4, 5, 6])

# Ge ng current color
current_color = line.get_color()
print("Current color:", current_color)

# Se ng new color
line.set_color('red')

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
Patches
In Matplotlib, a "patch" refers to an object that represents a shape or collection of
shapes drawn on a plot. Patches are fundamental building blocks for creating various
geometric shapes such as rectangles, circles, polygons, and ellipses, as well as more
complex shapes like paths and collections of primitives.

Here's a breakdown of the main aspects of patches in Matplotlib:

1. Basic Shapes:
Matplotlib provides classes for creating basic geometric shapes as patches. Some
of the commonly used patch classes include:
 [Link] : Represents a rectangle with specified width
and height.
 [Link] : Represents a circle with specified radius.
 [Link] : Represents a polygon defined by a sequence of
vertices.
 [Link] : Represents an ellipse with specified width and
height.
 [Link] : Represents a wedge-shaped region of a circle.
2. Properties and Styling:
Each patch object has various properties that can be customized to control its
appearance, such as color, edge color, linewidth, transparency (alpha), and more.
These properties can be set directly when creating the patch object or modified
later using setter methods.
import [Link] as plt
import [Link] as patches

# Create a rectangle patch


rect = [Link]((0.1, 0.1), 0.5, 0.3, edgecolor='red', facecolor='blue',
alpha=0.5, linewidth=2)

# Add the patch to the current axes


[Link]().add_patch(rect)

[Link]('equal') # Equal aspect ra o


[Link]()

3. Collection of Patches:
Sometimes, you may need to create a collection of patches, such as a collection
of rectangles or circles. Matplotlib provides classes like
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
[Link] to efficiently handle such scenarios. This
allows you to create and manage a large number of patches more easily.
4. Advanced Shapes:
Matplotlib also supports more advanced shapes and paths using the
[Link] class. This allows you to define custom shapes using Bézier
curves and other path operations. You can then use these paths to create patches
or draw directly on the plot.
5. Usage:
Patches are commonly used to annotate plots with additional information,
highlight specific regions of interest, or create custom legends. They are also
useful for creating visualizations of geometric objects, such as maps, charts, and
diagrams.

Seaborn
Seaborn is a Python data visualization library based on Matplotlib, which provides a higher-level
interface for creating attractive and informative statistical graphics. It is particularly well-suited
for working with complex datasets and generating advanced visualizations with minimal code.
Here are some examples of advanced data visualizations that you can create using Seaborn:

Pairplot:
Seaborn's pairplot function creates a grid of scatter plots for pairwise relationships
between multiple variables in a dataset. It also includes histograms along the diagonal
to visualize the distribution of each variable.

import seaborn as sns


import pandas as pd

# Load example dataset


iris = sns.load_dataset('iris')

# Create pairplot
[Link](iris, hue='species')

Clustermap:
Seaborn's clustermap function creates a hierarchical clustering heatmap to visualize
similarities between observations in a dataset. It is useful for identifying clusters or
patterns in the data.
[Link]([Link]('species', axis=1), cmap='viridis')
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
Violin Plot:
Seaborn's violinplot function creates a violin plot to visualize the distribution of a
numerical variable across different categories. It combines elements of a box plot and a
kernel density plot.

[Link](x='species', y='sepal_length', data=iris)

FacetGrid:
Seaborn's FacetGrid class allows you to create a grid of plots based on the unique values
of one or more categorical variables. This is useful for visualizing relationships within
subsets of the data.
# Create FacetGrid
g = [Link](iris, col='species')
[Link]([Link] erplot, 'sepal_length', 'sepal_width')

Jointplot:
Seaborn's jointplot function creates a joint plot to visualize the relationship between
two variables, including scatter plots, histograms, and regression lines.
[Link](x='sepal_length', y='sepal_width', data=iris, kind='reg')

Datasets in seaborn
Seaborn comes with some built-in datasets that are useful for practicing data
visualization and learning about statistical relationships. These datasets are conveniently
accessible through Seaborn's load_dataset() function. Here are some of the datasets
available in Seaborn:

1. iris:
This dataset contains measurements of various iris flowers, including sepal length,
sepal width, petal length, petal width, and species. It's a classic dataset used in
machine learning and data analysis tutorials.
import seaborn as sns
# Load the iris dataset
iris = sns.load_dataset('iris')
tips:
This dataset contains information about tips given by customers in a restaurant. It
includes variables such as total bill, tip amount, gender of the payer, whether they are a
smoker, day of the week, and time of day.
import seaborn as sns
# Load the ps dataset
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
ps = sns.load_dataset(' ps')

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
titanic:
This dataset contains information about passengers aboard the Titanic, including their
survival status, age, sex, passenger class, fare, and more. It's commonly used for survival
analysis and predictive modeling tasks.
import seaborn as sns

# Load the tanic dataset


tanic = sns.load_dataset(' tanic')

These are just a few examples of the datasets available in Seaborn. You can explore more
datasets and their descriptions in the Seaborn documentation. These datasets are convenient for
practicing data visualization techniques and experimenting with different types of plots offered
by Seaborn.

Note- Refer related Lab Programs for detailed example

Time Series analysis with pandas


Performing time series analysis with Pandas involves working with time-indexed data,
which could represent, for instance, stock prices, temperature readings, or any other
time-series data. Here's a basic overview of how to conduct time series analysis using
Pandas:

1. Loading Time-Series Data:


The first step is to load your time-series data into a Pandas DataFrame. Ensure
that one of the columns contains time-related information, such as dates or
timestamps, and set that column as the index of the DataFrame.
import pandas as pd

# Load me-series data


df = pd.read_csv('your_ me_series_data.csv')

# Convert date column to date me type and set as index


df['Date'] = pd.to_date me(df['Date'])
df.set_index('Date', inplace=True)

print([Link]())
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
Resampling and Aggregating:
You may need to resample your data to a different frequency (e.g., daily to monthly) or
aggregate it (e.g., taking the mean of daily values). You can use the resample() function
followed by an aggregation function such as mean(), sum(), or max().

# Resample daily data to monthly and calculate mean


df_monthly = [Link]('M').mean()

print(df_monthly.head())

Plotting Time Series Data:


Pandas provides convenient methods for plotting time-series data. You can use the
plot() method on a DataFrame or Series object to generate a basic line plot.
import [Link] as plt
# Plot me series data
df['Value'].plot(figsize=(10, 6), tle='Time Series Plot')
[Link]('Date')
[Link]('Value')
[Link]()

Rolling Statistics:
Rolling statistics such as rolling mean and rolling standard deviation can help smooth
out fluctuations and identify trends in the data. You can use the rolling() function
followed by an aggregation function.
# Calculate 30-day rolling mean
df['Rolling_Mean'] = df['Value'].rolling(window=30).mean()

print([Link]())
Time-Series Decomposition:
Time-series decomposition is a method for separating time-series data into trend,
seasonal, and residual components. Pandas provides a seasonal_decompose() function for
this purpose.
from [Link] import seasonal_decompose
# Decompose me series data
decomposi on = seasonal_decompose(df['Value'], model='addi ve')
# Plot decomposed components
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
decomposi [Link]()
[Link]()
Forecasting:
For forecasting future values, you can use various techniques such as exponential
smoothing, ARIMA (AutoRegressive Integrated Moving Average), or machine learning
models. Libraries like statsmodels and scikit-learn provide tools for building forecasting
models.
from [Link] import ARIMA
# Fit ARIMA model
model = ARIMA(df['Value'], order=(1, 1, 1))
fi ed_model = model.fit()
# Forecast future values
forecast = fi ed_model.forecast(steps=30)
print(forecast)

Other Ques ons-


1. python program to plot sinusoid and cosine waves using matplotlib and
label them with necessary title and labels

import numpy as np
import [Link] as plt

# Generate x values from 0 to 2*pi with 100 points


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

# Calculate sinusoid and cosine values


sin_wave = [Link](x)
cos_wave = [Link](x)

# Plot sinusoid and cosine waves


[Link](x, sin_wave, label='Sinusoid', color='blue')
[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
[Link](x, cos_wave, label='Cosine', color='red')

# Add tle and labels


plt. tle('Sinusoid and Cosine Waves')
[Link]('X')
[Link]('Amplitude')

# Add legend
[Link]()

# Show plot
[Link]()

(Trace and write an output of above program)

2. Explain with necessary coding creating a error bars and continuous errors
Error bars are used in statistical or scientific graphs to indicate the uncertainty or
variability of data points. They can represent standard deviation, standard error,
confidence intervals, or any other measure of uncertainty. Matplotlib provides
functions to easily add error bars to your plots.

import numpy as np
import [Link] as plt

# Sample data
x = [Link](0, 10, 20)
y = [Link](x)
errors = [Link](0, 0.1, size=[Link]) # Random errors

# Plot with error bars


[Link](x, y, yerr=errors, fmt='o', label='Data with Error Bars')

# Con nuous error bands


[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
plt.fill_between(x, y-errors, y+errors, alpha=0.3, color='gray',
label='Con nuous Error Bands')

# Add tle and labels


plt. tle('Plot with Error Bars and Con nuous Error Bands')
[Link]('X')
[Link]('Y')

# Add legend
[Link]()

# Show plot
[Link](True)
[Link]()

In this example:

 We generate some sample data x and y.


 We introduce some random errors using [Link]() and store them in the
errors variable.
 We plot the data with error bars using [Link]() with the yerr parameter set
to errors. The fmt='o' argument specifies that data points should be plotted as
circles.
 We plot continuous error bands using plt.fill_between() , specifying the region
between y-errors and y+errors for each x value. We set the alpha parameter to
control the transparency of the bands and choose the color as gray.
 We add a title, x-axis label, y-axis label, and legend to the plot.
 Finally, we display the plot using [Link]().

3. What is seabornplot? Explain pair plots for iris dataset and kernel desnsity estimation
using kdeplot and displot
seaborn is a Python data visualization library based on matplotlib that provides a high-
level interface for creating attractive and informative statistical graphics. It simplifies the
process of creating complex visualizations and provides functions for visualizing
relationships in data, including pair plots and kernel density estimation (KDE) plots.

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
Here's an explanation of pair plots for the Iris dataset and kernel density estimation
using kdeplot and displot in Seaborn:

1. Pair Plots for Iris Dataset:


The Iris dataset is a classic dataset in machine learning and consists of
measurements of various iris flowers. A pair plot is a grid of scatterplots for
pairwise relationships between variables in a dataset.

import seaborn as sns


import [Link] as plt

# Load the Iris dataset


iris = sns.load_dataset("iris")

# Create pair plot


[Link](iris, hue="species", markers=["o", "s", "D"])
[Link]()

1. In the pair plot:


 The diagonal contains histograms showing the distribution of each
variable.
 Off-diagonal elements show scatterplots of pairs of variables, with
different colors representing different species of iris flowers.
2. Kernel Density Estimation (KDE) using kdeplot:
Kernel density estimation is a non-parametric method for estimating the
probability density function of a random variable. The kdeplot function in Seaborn
is used to plot univariate or bivariate kernel density estimates.
# Univariate KDE plot
[Link](data=iris['petal_length'], shade=True)
[Link]()
# Bivariate KDE plot
[Link](data=iris, x="petal_length", y="petal_width", shade=True)
[Link]()
1. In KDE plots:
 The density of points is represented by colors, with darker regions
indicating higher density.

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
 The shade=True argument fills the area under the curve, creating a filled
contour plot.
2. Kernel Density Estimation using displot:
The displot function in Seaborn is a figure-level function for visualizing
distributions. It can create histograms, kernel density plots, and more.

# Univariate KDE plot with histogram


[Link](data=iris, x="petal_length", kind="kde")
[Link]()

[Link] T Module-5
Data Visualiza on Data Analy cs using Python(22MCA31)
# Bivariate KDE plot with marginal histograms
[Link](data=iris, x="petal_length", y="petal_width", kind="kde")
[Link]()
In displot:
 The kind="kde" argument specifies that a kernel density estimate should be
plotted.
 By default, displot also displays marginal histograms along the axes.

[Link] T Module-5

You might also like