Python Unit v Matpoltlib
Python Unit v Matpoltlib
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)
A simple line plot connects data points using straight lines to visualize trends in continuous
data.
Syntax: plt.plot(x, y)
A scatter plot represents individual data points as dots to show relationships between two
variables.
Syntax: plt.scatter(x, y)
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)
Binning divides data into intervals (bins). Density scaling makes the histogram represent
probabilities.
Syntax: plt.hist(data, density=True)
Plot legends describe each data series in the graph. They can be customized with parameters
like loc and fontsize.
Syntax: plt.legend(loc='best')
A color bar is a scale that shows the mapping of colors to data values in a plot.
Syntax: plt.colorbar()
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.
These functions add labels to the x-axis and y-axis respectively in a plot.
Syntax: plt.xlabel("X-axis"), plt.ylabel("Y-axis")
It adds a grid to the background of the plot for better visual clarity.
Syntax: plt.grid(True)
This function displays the plot window. It is the final command to render the plot.
Syntax: plt.show()
Used to create multiple plots in the same figure. Syntax: plt.subplot(nrows, ncols, index)
Fills the area between two horizontal curves. Syntax: plt.fill_between(x, y1, y2)
They set the locations and labels of ticks on x and y axes. Syntax: plt.xticks([1,2,3],
['A','B','C'])
These functions set the limits of x and y axes. Syntax: plt.xlim(0, 10), plt.ylim(0, 100)
It clears the current figure, useful for starting fresh. Syntax: plt.clf()
Displays a legend identifying labeled data series in the plot. Syntax: plt.legend()
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:
Use Cases:
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
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:
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.
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.
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.
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
data = [7, 15, 13, 17, 19, 21, 24, 25, 30, 31, 45]
plt.boxplot(data)
plt.title("Boxplot Example")
plt.show()
Center line: median
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
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.
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.
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.
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()
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.
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.
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:
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.
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'.
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()