0% found this document useful (0 votes)
4 views21 pages

Python 9

The document outlines an experiment for a Programming Laboratory course focused on implementing data visualizations using Python's Matplotlib library. It details the installation process, key components of Matplotlib (Figure, Axes, Axis, Artist), and provides examples of various types of plots including line plots, bar graphs, pie charts, histograms, scatter plots, and 3D plots. Additionally, it includes a question for students to create a line plot from data in a text file.
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)
4 views21 pages

Python 9

The document outlines an experiment for a Programming Laboratory course focused on implementing data visualizations using Python's Matplotlib library. It details the installation process, key components of Matplotlib (Figure, Axes, Axis, Artist), and provides examples of various types of plots including line plots, bar graphs, pie charts, histograms, scatter plots, and 3D plots. Additionally, it includes a question for students to create a line plot from data in a text file.
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

Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY


COURSE CODE: DJS23IPC253L Name: Mohammad
Shaikh
COURSE NAME: Programming Laboratory CLASS: S.Y. B. Tech
ROLLNO: I172 BATCH: I3-2
EXPERIMENT NO. 9
CO/LO: CO2.
AIM / OBJECTIVE: To implement data visualizations using the Python library Matplotlib.
DESCRIPTION OF EXPERIMENT:
Data visualization is the process of translating numerical data, text, or large data sets into
various types of graphs, making it easier to understand and interpret. Python's Matplotlib
library is a versatile tool for creating visualizations like line plots, bar charts, histograms, pie
charts, scatter plots, box plots, and 3D plots. These visualizations help in exploring data,
identifying patterns, and communicating insights effectively.
INSTALLATION OF MATPLOTLIB:
To install Matplotlib, use the following command:
pip install matplotlib
Verify the installation:
import matplotlib
print(matplotlib.__version__)

MATPLOTLIB COMPONENTS:
• Figure: The main container holding all the plots. Acts like a canvas.
• Axes: The area where data is plotted. A Figure can have multiple Axes.
• Axis: The number line-like objects representing x, y, or z-axes.
• Artist: Any visible element on the plot (lines, text, markers, etc.).
Figure: This is the overall window or page on which everything is drawn. It's like a blank
canvas. A figure can contain multiple plots (axes) to create complex visualizations.
Example:
import [Link] as plt
fig = [Link](figsize=(6, 4)#Create a blank figure with specific size
[Link]()

Output:
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY


Axes: These are the individual plots or graphs inside a figure. Each Axes object can have
multiple plots, labels, titles, and ticks. An Axes is often what we think of as a plot.
Example:
ax = fig.add_subplot(1, 1, 1) # Add one Axes to the figure
ax.set_title("Sample Axes")
[Link]()
Axis: These are the x-axis and y-axis that form the border of the plot. They define the
coordinate system and can be customized (labels, limits, grids).
Example:
ax.set_xlim(0, 10) # Set x-axis limits
ax.set_ylim(0, 20) # Set y-axis limits
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
[Link]()
Ar st:Every visible element in a Matplotlib plot (like text, lines, markers) is an artist.
Artists are used to customize the appearance of the [Link] of artists include
Line2D, Text, Patch, etc.
Example:
line, = [Link]([1, 2, 3], [4, 5, 6], label='Line Artist')
[Link]() # Display the legend (an artist)
[Link]()

In summary, think of a Figure as the overall container, Axes as the specific plotting areas
within the container, and Axis as the numeric scales for each plot. Ar sts are the visual
elements that bring the plot to life. Matplotlib visualizations are structured using several
essential components. Understanding these components will help you create effective and
accurate plots.
• Figure: This is the overall window or page on which everything is drawn. It's like a
blank canvas. A figure can contain multiple plots (axes) to create complex
visualizations.
ti
ti
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY


• Axes: These are the individual plots or graphs inside a figure. Each axes object can
have multiple plots, labels, titles, and ticks. An Axes is often what we think of as a
plot.
• Axis: These are the x-axis and y-axis that form the border of the plot. They define the
coordinate system and can be customized (labels, limits, grids).
• Ar st: Every visible element in a Matplotlib plot (like text, lines, markers) is an artist.
Artists are used to customize the appearance of the plot.
BASIC PLOTTING CONCEPTS:
• Pyplot Module: Simplifies plot creation with methods like plot(), bar(),
scatter(), etc.
• Figure Size: Use [Link](figsize=(width, height)) to set plot dimensions.
• Colors and Line Styles: Specify color and style with strings (e.g., 'b-' for a blue
line).
• Multiple Plots: Combine multiple plots with additional (x, y) pairs in the plot()
method.
TYPES OF PLOTS AND EXAMPLES:
1. Line Plot:
Line plots are used to display data points connected by straight lines. They help visualize
trends over time or ordered data.
Line plots are ideal for tracking changes over periods. If the line shows an upward trend, it
suggests growth, while a downward trend indicates decline. Sharp spikes may indicate
anomalies.
[Link](x, y, format): Creates a line plot with various formatting options:
• x, y: Arrays representing data points.
• format: A combination of color, marker, and line style:
o Colors: 'b' (blue), 'g' (green), 'r' (red), 'c' (cyan), 'm' (magenta), 'y' (yellow), 'k'
(black), 'w' (white)
o Markers: 'o' (circle), 's' (square), '^' (triangle), '*' (star)
o Line Styles: '-' (solid), '--' (dashed), '-.' (dash-dot), ':' (dotted)
Examples of format strings:
• 'ro-': Red solid line with circle markers
• 'g^--': Green dashed line with triangle markers
• 'bs:': Blue dotted line with square markers
[Link]() and [Link](): Labels for X and Y axes. [Link](): Displays
gridlines.
ti
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY


import [Link] as plt
import numpy as np

x = [Link]([1, 2, 3, 4])
y = [Link]([10, 20, 25, 30])
[Link](x, y, 'ro-', label='Red Solid Circle')
[Link](x, y + 5, 'g^--', label='Green Dashed Triangle')
[Link](x, y - 5, 'bs:', label='Blue Dotted Square')
[Link]("Line Plot with Multiple Formats")
[Link]("X-axis")
[Link]("Y-axis")
[Link](True)
[Link]()
[Link]()
Line plots are used to display data points connected by straight lines. They help visualize
trends over time or ordered data.
[Link](x, y, format): Creates a line plot with various formatting options:
• x, y: Arrays representing data points.
• format: A combination of color, marker, and line style:
o Colors: 'b' (blue), 'g' (green), 'r' (red), 'c' (cyan), 'm' (magenta), 'y' (yellow), 'k'
(black), 'w' (white)
o Markers: 'o' (circle), 's' (square), '^' (triangle), '*' (star)
o Line Styles: '-' (solid), '--' (dashed), '-.' (dash-dot), ':' (dotted)
Examples of format strings:
• 'ro-': Red solid line with circle markers
• 'g^--': Green dashed line with triangle markers
• 'bs:': Blue dotted line with square markers
[Link]() and [Link](): Labels for X and Y axes. [Link](): Displays
gridlines.
import [Link] as plt
import numpy as np

x = [Link]([1, 2, 3, 4])
y = [Link]([10, 20, 25, 30])
[Link](x, y, 'ro-', label='Red Solid Circle')
[Link](x, y + 5, 'g^--', label='Green Dashed Triangle')
[Link](x, y - 5, 'bs:', label='Blue Dotted Square')
[Link]("Line Plot with Multiple Formats")
[Link]("X-axis")
[Link]("Y-axis")
[Link](True)
[Link]()
[Link]()
• [Link](x, y, format): Creates a line plot with x and y data.
o x, y: Arrays representing data points.
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY


o format: Optional string
for color and style (e.g., 'go--' for green dashed
line).
• [Link]() and [Link](): Labels for X and Y axes.
• [Link](): Displays gridlines.

import [Link] as plt


import numpy as np

x = [Link]([1, 2, 3, 4])
y = [Link]([10, 20, 25, 30])
[Link](x, y, 'go--')
[Link]("Simple Line Plot")
[Link]("X-axis")
[Link]("Y-axis")
[Link](True)
[Link]()

2. Bar Graphs:
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY


Bar graphs represent categorical data with rectangular bars. They compare different
categories or track changes over time.
Interpretation: Bar graphs make it easy to compare categories. Taller bars represent higher
values, while shorter ones indicate lower values. They can also reveal patterns or outliers.
[Link](x, height, color): Creates vertical bars. [Link](y, width, color):
Creates horizontal bars.
• x, y: Categories or labels.
• height, width: Values or counts.
• color: Specifies bar color.
languages = ["Java", "Python", "PHP", "JavaScript"]
popularity = [22.2, 17.6, 8.8, 8.0]
[Link](languages, popularity, color='blue')
[Link]("Vertical Bar Graph")
[Link]()

[Link](languages, popularity, color='orange')


[Link]("Horizontal Bar Graph")
[Link]()
• [Link](x, height, color): Creates vertical bars.
• [Link](y, width, color): Creates horizontal bars.
o x, y: Categories or labels.
o height, width: Values or counts.
o color: Specifies bar color.
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

3. Stacked Bar Graphs:


• [Link](x, height, bottom, label): Stacks bars on top of each other.
o bottom: The position from where the bar starts.
o label: The legend label for each segment.
A = [3, 4, 5]
B = [2, 3, 4]
x = [Link](3)
[Link](x, A, color='blue', label='A')
[Link](x, B, bottom=A, color='green', label='B')
[Link]()
[Link]("Stacked Bar Graph")
[Link]()
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

4. Pie Charts:
Pie charts display proportions of a whole. Each slice represents a category, and its size
corresponds to the proportion.
Interpretation: Pie charts help visualize percentage distribution. They are useful when
comparing the parts of a whole, but may become unclear with many categories.
[Link](sizes, labels, autopct, shadow, startangle): Creates a pie chart.
• sizes: Data values.
• labels: Categories.
• autopct: Percentage format.
• shadow: Adds shadow.
• startangle: Start angle of the chart.
sizes = [20, 30, 25, 25]
labels = ["A", "B", "C", "D"]
[Link](sizes, labels=labels, autopct='%1.1f%%', shadow=True,
startangle=140)
[Link]("Pie Chart Example")
[Link]()
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

• [Link](sizes, labels, autopct, shadow, startangle): Creates a pie chart.


o sizes: Data values.
o labels: Categories.
o autopct: Percentage format.
o shadow: Adds shadow.
o startangle: Start angle of the chart.
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

5. Histograms:
Histograms show the distribution of data over a range. Useful for analyzing the frequency of
observations within defined bins.
Interpretation: Histograms help identify data distribution patterns like normal distribution,
skewness, and data spread. Gaps or isolated bars may indicate outliers.
[Link](data, bins, color, edgecolor): Creates a histogram.
• data: Array of data values.
• bins: Number of intervals.
• edgecolor: Border color.
data = [Link](1000)
[Link](data, bins=30, color='purple', edgecolor='black')
[Link]("Histogram Example")
[Link](True)
[Link]()
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

• [Link](data, bins, color, edgecolor): Creates a histogram.


o data: Array of data values.
o bins: Number of intervals.
o edgecolor: Border color.

6. Scatter Plots:
Scatter plots depict relationships between two variables. They help identify correlations,
clusters, and outliers.
Interpretation: A clear upward or downward pattern suggests a correlation. No clear pattern
may indicate independence. Outliers are evident as isolated points.
[Link](x, y, color): Plots data points.
• x, y: Coordinate arrays.
math_marks = [88, 92, 80, 89, 100]
science_marks = [35, 79, 79, 48, 100]
[Link](math_marks, science_marks, color='red')
[Link]("Math Marks")
[Link]("Science Marks")
[Link]("Scatter Plot of Marks")
[Link](True)
[Link]()
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

• [Link](x, y, color): Plots data points.


o x, y: Coordinate arrays.

7. Subplots:
• [Link](rows, cols): Creates a grid of subplots.
o ax1, ax2: Subplot objects for individual plots.
fig, (ax1, ax2) = [Link](1, 2)
[Link](x, [Link](x))
[Link](x, [Link](x))
[Link]("Subplots Example")
[Link]()
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY


8. 3D Plots:
• fig.add_subplot(111, projection='3d'): Creates a 3D subplot.
• [Link](x, y, z, color): Plots 3D scatter points.
from mpl_toolkits.mplot3d import Axes3D
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
x = [Link]([1, 2, 3])
y = [Link]([10, 20, 25])
z = [Link]([5, 15, 10])
[Link](x, y, z, color='green')
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
[Link]("3D Scatter Plot")
[Link]()

QUESTIONS:
1. Line Plot from a Text File:
Write a Python program to draw a line plot using data from a text file. The text file
should contain pairs of x and y values separated by spaces.
Test Data:
1 2
2 4
3 1
4 3
Solution:
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

2. Financial Data Line Plot:


Write a Python program to draw a line chart of the daily closing price of a company's
stock for a week. Use data from a CSV file with the following format:
Date,Open,High,Low,Close
01-01-2023,100,110,95,105
01-02-2023,108,115,102,110
01-03-2023,112,118,107,115
01-04-2023,116,122,111,120
01-05-2023,120,125,115,123
Solution :
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

3. Vertical and Horizontal Bar Charts:


Write a Python program to create both vertical and horizontal bar charts comparing
the sales of three products in four regions.
Sample Data:
Products: A, B, C
Sales in regions: [40, 50, 60], [55, 65, 75], [30, 40, 50], [70, 80, 90]
Solution:
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

4. Stacked Bar Graph:


Create a stacked bar chart showing the marks obtained by three students in Math,
Science, and English.
Test Data:
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY


Students: Student 1, Student 2, Student 3
Math: [75, 85, 90]
Science: [80, 78, 92]
English: [88, 79, 84]
Solution:

5. Pie Chart for Market Share:


Write a Python program to display a pie chart of the market share of five smartphone
brands. Include labels and percentages.
Sample Data:
Brands: Apple, Samsung, Xiaomi, Oppo, Vivo
Market Share: 25%, 30%, 20%, 15%, 10%
Solution:

6. Histogram of Exam Scores:


Create a histogram to visualize the distribution of exam scores for a class of 30
students. Use 5 bins for categorization.
Test Data:
Scores: [56, 60, 62, 65, 68, 70, 72, 75, 78, 80, 82, 85, 87, 90, 92,
95, 97, 100]
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

Solution:
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

7. Scatter Plot - Subject Marks Comparison:


Write a Python program to draw a scatter plot comparing Mathematics and Science
marks of 10 students. Include labels and a title.
Test Data:
Math: [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
Science: [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]

Solution:

8. Subplots - Multiple Visualizations:


Create a figure with two subplots. The first subplot should display a line plot of
monthly temperatures, and the second should show a bar chart of monthly rainfall.
Test Data:
Temperatures: [30, 32, 35, 33, 31, 29, 28, 30, 32, 35, 34, 33]
Rainfall: [100, 120, 140, 150, 130, 100, 90, 80, 70, 75, 85, 95]
Solution:
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

9. 3D Scatter Plot:
Create a 3D scatter plot displaying the relationship between three variables: hours
studied, test scores, and sleep duration.
Test Data:
Hours Studied: [1, 2, 3, 4, 5, 6, 7]
Test Scores: [55, 60, 65, 70, 75, 80, 85]
Sleep Duration: [8, 7, 6, 7, 8, 6, 7]
Solution:
Academic Year:2025-26 SAP ID:60003240302

DEPARTMENT OF INFORMATION TECHNOLOGY

WRITE-UP QUESTIONS:
Explain the significance and differences between a line plot, bar graph, pie chart, and
histogram in Matplotlib.
• Discuss when it is appropriate to use each type of plot.
• Provide examples of real-world scenarios where these plots can be applied effectively.
• Mention the interpretation and insights that can be drawn from each plot.

CONCLUSION:
Therefore we successfully implemented data visualizations using the Python library
Matplotlib.
***

You might also like