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

Python Unit v Matpoltlib

The document provides lecture notes on data visualization using Matplotlib for a programming course. It covers various types of plots such as line plots, scatter plots, histograms, and 3D plots, along with their syntax and usage. Additionally, it includes explanations of customizing plots, legends, color bars, and annotations, along with practical examples for each type of visualization.

Uploaded by

amalamargret.cse
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)
2 views

Python Unit v Matpoltlib

The document provides lecture notes on data visualization using Matplotlib for a programming course. It covers various types of plots such as line plots, scatter plots, histograms, and 3D plots, along with their syntax and usage. Additionally, it includes explanations of customizing plots, legends, color bars, and annotations, along with practical examples for each type of visualization.

Uploaded by

amalamargret.cse
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/ 12

U23ADTC01 –Programming in Python 2024-2025

Lecture Notes
UNIT V - DATA VISUALIZATION WITH MATPLOTLIB

Prepared By:
Dr. M. Shanmugam
Mr. D. Rajesh
Mrs. M. Hemalatha
Mrs. S. Deeba
Ms. Amala Margret

PART- A (2 Marks)

1. Define Simple Line Plot.

A simple line plot connects data points using straight lines to visualize trends in continuous
data.
Syntax: plt.plot(x, y)

2. What is a Scatter Plot?

A scatter plot represents individual data points as dots to show relationships between two
variables.
Syntax: plt.scatter(x, y)

3. Define Density and Contour Plots.

Density Plot shows the concentration of data values. Contour Plot represents equal value
lines across a 2D grid.
Syntax: plt.contour(X, Y, Z) or plt.contourf()

4. What is a Histogram?

A histogram displays the frequency distribution of numeric data by grouping it into bins.
Syntax: plt.hist(data, bins=n)

5. Define Binning and Density.

Binning divides data into intervals (bins). Density scaling makes the histogram represent
probabilities.
Syntax: plt.hist(data, density=True)

6. What is Customizing Plot Legends?

Plot legends describe each data series in the graph. They can be customized with parameters
like loc and fontsize.
Syntax: plt.legend(loc='best')

7. Define Color Bars.

Sri Manakula Vinayagar Engineering College Department of CSE


U23ADTC01 –Programming in Python 2024-2025

A color bar is a scale that shows the mapping of colors to data values in a plot.
Syntax: plt.colorbar()

8. What is 3D Plotting in Matplotlib?

3D plotting allows visualizing data in three dimensions using Axes3D from


mpl_toolkits.mplot3d.
Syntax: ax.plot3D(x, y, z)

9. Define Problem Solving using Matplotlib.

Problem-solving involves using visual tools like line, scatter, and histogram plots to analyze
and interpret data.
Example: Plot student scores to understand performance trends.

10. What is the purpose of plt.xlabel() and plt.ylabel()?

These functions add labels to the x-axis and y-axis respectively in a plot.
Syntax: plt.xlabel("X-axis"), plt.ylabel("Y-axis")

11. Define plt.title().

The plt.title() function is used to set a title for the graph.


Syntax: plt.title("Graph Title")

12. What is plt.grid() used for?

It adds a grid to the background of the plot for better visual clarity.
Syntax: plt.grid(True)

13. What is the use of plt.show()?

This function displays the plot window. It is the final command to render the plot.
Syntax: plt.show()

14. What is the function of plt.savefig()?

It saves the plot as an image file. Syntax: plt.savefig("filename.png")

15. Define plt.bar().

Creates a vertical bar chart. Syntax: plt.bar(x, height)

16. Define plt.pie().

Draws a pie chart. Syntax: plt.pie(values, labels=labels)

17. What is the use of plt.boxplot()?

It creates a box-and-whisker plot to show distribution and outliers. Syntax: plt.boxplot(data)

18. Define plt.subplot().

Used to create multiple plots in the same figure. Syntax: plt.subplot(nrows, ncols, index)

19. What does plt.errorbar() do?

Plots data with error bars. Syntax: plt.errorbar(x, y, yerr=error)


Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

20. What is plt.fill_between()?

Fills the area between two horizontal curves. Syntax: plt.fill_between(x, y1, y2)

21. What is the role of plt.xticks() and plt.yticks()?

They set the locations and labels of ticks on x and y axes. Syntax: plt.xticks([1,2,3],
['A','B','C'])

22. Define plt.xlim() and plt.ylim().

These functions set the limits of x and y axes. Syntax: plt.xlim(0, 10), plt.ylim(0, 100)

23. What is the use of plt.clf()?

It clears the current figure, useful for starting fresh. Syntax: plt.clf()

24. What is plt.legend() used for?

Displays a legend identifying labeled data series in the plot. Syntax: plt.legend()

25. What is the function of plt.annotate()?

Adds text annotation to a plot at a specified point. Syntax: plt.annotate('label', xy=(x, y))
PART B (5 MARKS)

1. Explain the use of line plots and how to customize them in Matplotlib.
A line plot is used to represent data trends over a continuous interval or time span. The plt.plot()
function draws lines connecting points. You can customize line color, width, style, and markers:

plt.plot(x, y, color='red', linewidth=2, linestyle='--', marker='o')


Additional customization:

plt.title(), plt.xlabel(), plt.ylabel() for labeling

plt.grid(True) for background grid

plt.legend() to add a legend

plt.savefig() to save the plot

2. Describe scatter plots with an example. When are they used?


Scatter plots are used to display the relationship or correlation between two numeric variables. Each
point represents an observation. Example:

x = [10, 20, 30, 40]


y = [5, 15, 25, 35]
plt.scatter(x, y, color='green', marker='^')
plt.title("Scatter Plot Example")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.grid(True)
plt.show()
Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

Use Cases:

Examining correlations (e.g., height vs weight)

Identifying clusters, outliers, and trends

3. Write about histograms and how binning affects the plot.


A histogram is a graphical representation that organizes data into bins (intervals). It shows frequency
distribution.

import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(1000)
plt.hist(data, bins=20, color='skyblue', edgecolor='black')
plt.title("Histogram with 20 Bins")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
Fewer bins = broader intervals, less detail

More bins = narrower intervals, more detail

density=True converts it to a probability density histogram

4. Explain 3D plotting in Matplotlib with an example.


Matplotlib provides 3D plotting using mpl_toolkits.mplot3d. Useful for visualizing surfaces,
wireframes, and scatter plots in three dimensions.

from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
z = [100, 200, 300, 400]
ax.plot3D(x, y, z, 'red')
plt.title("3D Line Plot")
plt.show()
Can also use ax.scatter3D() or ax.plot_surface() for other 3D plots.

5. How can legends and color bars be customized in a Matplotlib plot?


Legends: Used to describe each element in the plot. Add labels inside plot() or scatter(), then call
plt.legend().

plt.plot(x, y, label="Line A")


plt.legend(loc='upper right', fontsize=10)
Color Bars: Used in plots like imshow() or contourf() to show color scale.

import numpy as np
x = np.random.rand(10, 10)
Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

plt.imshow(x, cmap='viridis')
plt.colorbar(label='Intensity')
plt.title("Color Bar Example")
plt.show()
Customization includes:

label for text

shrink, aspect for size adjustments

6. Explain the concept of subplots with an example.


Subplots allow multiple plots to appear in a single figure for comparison. Use plt.subplot(rows, cols,
index).

plt.subplot(1, 2, 1)
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("Plot 1")

plt.subplot(1, 2, 2)
plt.plot([1, 2, 3], [6, 5, 4])
plt.title("Plot 2")

plt.tight_layout()
plt.show()
The above example creates two plots side-by-side.

tight_layout() adjusts spacing to avoid overlap.

7. Discuss contour and density plots. Provide a sample plot.


Contour and density plots visualize 3D data in 2D using contour lines or filled regions. Often used in
terrain or statistical maps.

import numpy as np
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.exp(-X**2 - Y**2)

plt.contour(X, Y, Z)
plt.title("Contour Plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Use plt.contourf() for filled contour.

8. What is the role of bar() and barh() functions in data visualization?


bar() creates vertical bar charts, and barh() creates horizontal bars. Ideal for categorical comparisons.

categories = ['A', 'B', 'C']


values = [10, 15, 7]
Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

plt.bar(categories, values, color='purple')


plt.title("Bar Chart")
plt.show()
Use barh() when category names are long or vertical space is limited.

9. Explain pie charts and how they can be customized in Matplotlib.


Pie charts represent data proportions in a circular format.

labels = ['A', 'B', 'C']


sizes = [30, 40, 30]
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title("Pie Chart Example")
plt.axis('equal')
plt.show()
autopct shows percentages

startangle rotates the chart

axis('equal') keeps the pie as a circle

10. How do you annotate data points in a plot?


Use plt.annotate() to add labels or descriptions to specific data points.

x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
plt.annotate("Important", xy=(2, 5), xytext=(2.5, 5.5),
arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.show()
Useful for highlighting outliers or trends

11. What are the main features of customizing axis ticks and limits?
xticks()/yticks() control tick location and labels.

xlim()/ylim() control viewing window.

plt.plot([1, 2, 3], [4, 5, 6])


plt.xticks([1, 2, 3], ['One', 'Two', 'Three'])
plt.xlim(0, 4)
plt.ylim(3, 7)
plt.show()
Helps with readability and focus

12. Discuss imshow() for image data visualization.


imshow() is used to display image or 2D matrix data as a colored grid.

import numpy as np
image = np.random.rand(10,10)
plt.imshow(image, cmap='hot', interpolation='nearest')
plt.colorbar()
Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

plt.title("Random Image Data")


plt.show()
cmap changes color scheme

interpolation affects image smoothing

13. Explain how to use fill_between() for shading in plots.


fill_between() highlights the area between two lines or a line and the x-axis.

x = np.linspace(0, 10, 100)


y = np.sin(x)
plt.plot(x, y)
plt.fill_between(x, y, alpha=0.3)
plt.title("Filled Area Under Curve")
plt.show()
Useful for showing range, confidence intervals, etc.

14. How is boxplot() used to show statistical data?


Boxplots visualize median, quartiles, and outliers of data.

data = [7, 15, 13, 17, 19, 21, 24, 25, 30, 31, 45]
plt.boxplot(data)
plt.title("Boxplot Example")
plt.show()
Center line: median

Box: interquartile range (IQR)

Whiskers and points show spread and outliers

15. What is the use of errorbar() in scientific plots?


errorbar() displays data with uncertainty or variability.

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
errors = [1.5, 2.0, 1.0, 2.5]
plt.errorbar(x, y, yerr=errors, fmt='-o')
plt.title("Error Bar Plot")
plt.show()
Useful in experimental or statistical analysis

Sri Manakula Vinayagar Engineering College Department of CSE


U23ADTC01 –Programming in Python 2024-2025

PART C (10 MARKS)


1. Explain the various types of plots available in Matplotlib. Provide examples of when each
type should be used.
Matplotlib offers a variety of plotting functions, each suited to different kinds of data
visualization:

Line Plots: Used to visualize trends over continuous data. Example: Showing temperature over
time.

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.title("Line Plot Example")
plt.show()
Scatter Plots: Best for showing the relationship between two variables. Ideal for correlation
analysis.

x = [10, 20, 30, 40]


y = [5, 15, 25, 35]
plt.scatter(x, y)
plt.title("Scatter Plot Example")
plt.show()
Bar Charts: Used to compare quantities across different categories.

categories = ['A', 'B', 'C']


values = [10, 15, 7]
plt.bar(categories, values)
plt.title("Bar Chart Example")
plt.show()
Histograms: Show the frequency distribution of a dataset, often used for continuous data.

data = np.random.randn(1000)
plt.hist(data, bins=20)
plt.title("Histogram Example")
plt.show()
Pie Charts: Used to show proportions of a whole.

labels = ['A', 'B', 'C']


sizes = [30, 40, 30]
plt.pie(sizes, labels=labels)
plt.title("Pie Chart Example")
plt.show()
3D Plots: Visualize data in three dimensions. Useful for surface, wireframe, and scatter plots.

from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter([1, 2], [10, 20], [100, 200])
plt.show()

2. What is the use of subplots in Matplotlib? How can you arrange multiple plots in a figure?
Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

Subplots allow you to arrange multiple plots in a grid-like structure within the same figure.
This is useful for comparing different datasets or visualizing related data together.

Creating Subplots: You can use plt.subplot() or plt.subplots() to create multiple plots in one
figure.

Example using plt.subplot():

plt.subplot(2, 1, 1)
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("Subplot 1")

plt.subplot(2, 1, 2)
plt.plot([1, 2, 3], [1, 2, 3])
plt.title("Subplot 2")

plt.tight_layout() # Automatically adjusts spacing


plt.show()
Using plt.subplots():

fig, axs = plt.subplots(2, 1)


axs[0].plot([1, 2, 3], [1, 4, 9])
axs[0].set_title("Subplot 1")

axs[1].plot([1, 2, 3], [1, 2, 3])


axs[1].set_title("Subplot 2")

plt.tight_layout()
plt.show()

3. Explain the concept of customizing the axis, including tick marks, labels, and limits.
Customizing the axis enhances the readability of plots and allows for better data interpretation.
In Matplotlib, you can adjust axis ticks, labels, and limits.

Tick Marks: Use xticks() and yticks() to customize the positions and labels of ticks.

plt.plot([1, 2, 3], [1, 4, 9])


plt.xticks([1, 2, 3], ['One', 'Two', 'Three'])
plt.yticks([1, 4, 9], ['Low', 'Medium', 'High'])
plt.show()
Axis Limits: xlim() and ylim() control the range of data shown on the axes.

plt.plot([1, 2, 3], [1, 4, 9])


plt.xlim(0, 4)
plt.ylim(0, 10)
plt.show()
Axis Labels: Use xlabel() and ylabel() to add axis labels.

plt.plot([1, 2, 3], [1, 4, 9])


plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

4. What is a contour plot, and how do you create one in Matplotlib?


A contour plot displays the relationship between three continuous variables in 2D, using
contour lines to represent values of a third variable.

Creating a Contour Plot:

import numpy as np
x = np.linspace(-3.0, 3.0, 100)
y = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2)

plt.contour(X, Y, Z)
plt.title("Contour Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
Filled Contours: Use contourf() to create filled contour plots.

plt.contourf(X, Y, Z)
plt.title("Filled Contour Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()

5. Discuss the concept and creation of a bar chart in Matplotlib. Provide an example with
customization.
Bar charts are used to represent categorical data with rectangular bars, where the length of each
bar corresponds to a value.

Creating a Bar Chart:

categories = ['A', 'B', 'C']


values = [10, 15, 7]
plt.bar(categories, values, color='purple')
plt.title("Bar Chart Example")
plt.xlabel('Category')
plt.ylabel('Value')
plt.show()
Customization:

categories = ['A', 'B', 'C']


values = [10, 15, 7]
plt.bar(categories, values, color='purple', edgecolor='black', linewidth=2)
plt.title("Customized Bar Chart")
plt.xlabel('Category')
plt.ylabel('Value')
plt.xticks(rotation=45) # Rotate x-axis labels
plt.show()

6. How does Matplotlib handle 3D plotting? Demonstrate how to plot a 3D scatter plot and
Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

surface plot.
Matplotlib supports 3D plotting through the mpl_toolkits.mplot3d module.

3D Scatter Plot:

from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
z = [100, 200, 300, 400]
ax.scatter(x, y, z)
plt.show()
3D Surface Plot:

from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

ax.plot_surface(X, Y, Z, cmap='viridis')
plt.show()
7. Explain the use of plt.fill_between() for creating shaded regions. Provide an example.
The fill_between() function in Matplotlib is used to fill the area between two horizontal curves
or a curve and the x-axis. This can help visualize ranges or areas under curves.

Example of Using fill_between():

x = np.linspace(0, 10, 100)


y = np.sin(x)
plt.plot(x, y)
plt.fill_between(x, y, color='skyblue', alpha=0.5)
plt.title("Shaded Area Under Curve")
plt.show()

8. What is the role of color maps in Matplotlib? How are color maps used with contour plots
and images?
Color maps provide a color gradient to represent values in data, helping to highlight variations.
Matplotlib offers a variety of color maps, like 'viridis', 'plasma', and 'inferno'.

Using Color Maps with imshow():

import numpy as np
image = np.random.rand(10, 10)
plt.imshow(image, cmap='viridis')
plt.colorbar()
plt.title("Image with Color Map")
plt.show()
Using Color Maps with Contour Plots:
Sri Manakula Vinayagar Engineering College Department of CSE
U23ADTC01 –Programming in Python 2024-2025

x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.exp(-X**2 - Y**2)
plt.contourf(X, Y, Z, cmap='plasma')
plt.colorbar()
plt.title("Contour Plot with Color Map")
plt.show()

9. What are the different ways to save a plot in Matplotlib? Explain and demonstrate with code.
You can save a plot using plt.savefig() in various formats such as PNG, PDF, SVG, etc.

x = [1, 2, 3]
y = [1, 4, 9]
plt.plot(x, y)
plt.title("Save Plot as PNG")
plt.savefig("plot.png")
plt.plot(x, y)
plt.title("Save Plot as PDF")
plt.savefig("plot.pdf")

10. Explain how to add annotations to a plot in Matplotlib. Provide an example with arrows
and text.
Annotations add textual information or arrows to specific parts of a plot, helping highlight key
features.

x = [1, 2, 3]
y = [1, 4, 9]
plt.plot(x, y)
plt.annotate("Max Value", xy=(3, 9), xytext=(2, 8),
arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.title("Plot with Annotation")
plt.show()

Sri Manakula Vinayagar Engineering College Department of CSE

You might also like