Mat Plot Lib
Mat Plot Lib
• What is Matplotlib?
• Matplotlib is one of the most widely used libraries for creating visual
representations of data in Python.
• It allows for the creation of various plots (line plots, bar charts, scatter
plots, histograms, etc.) and is highly customizable.
• Use Case: Whether you're doing exploratory data analysis (EDA) or
preparing visual reports, Matplotlib helps in visualizing trends,
distributions, and relationships in your data.
Installing Matplotlib
• You need to install Matplotlib using pip if it's not already installed. Use
the following command:
pip install matplotlib
To Import:
Import matplotlib.pyplot
Basic Plotting
• Example: Line PlotExample Scenario:
import matplotlib.pyplot as plt
Data: Numbers and their squares, x = [1, 2, 3, 4, 5], y = [1, 4, 9, 16, 25]
Create a line plotplt.plot(x, y)
• import matplotlib.pyplot as plt
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Customized Line Plot')
plt.show()
Saving a Plot
• plt.plot(x, y)
• plt.title('Save Plot Example')
• plt.savefig('my_plot.png')
Introduction to OOP in Matplotlib
OOP Approach
• Provides more control over plot elements.
• Directly works with Figure and Axes objects, allowing for fine-tuning
and complex visualizations.
OOP Interface
• Involves using objects like Figure and Axes to customize and control
plots.
• fig, ax = plt.subplots()
• ax.plot(x, y)
OOP Components in Matplotlib
Content:
1.Figure
•The entire figure or canvas where the plots live.
•Like a window or page containing one or more subplots.
2.Axes
•Represents an individual plot or graph.
•Contains axis labels, ticks, title, and the plot elements (like lines, bars, etc.).
3.Axis
•Refers to the x-axis and y-axis within an Axes object.
•Controls the ticks, labels, and ranges for the plot.
Creating a Figure and Axes in OOP
Matplotlib
•import matplotlib.pyplot as plt
• # Show plot
• plt.show()
•
Multiple Subplots in OOP
import matplotlib.pyplot as plt
• # Plotting a line
• ax.plot([1, 2, 3], [1, 4, 9])
• # Adding gridlines
• ax.grid(True)
• # Customizing ticks
• ax.set_xticks([1, 2, 3])
• ax.set_yticks([1, 4, 9])
• # Show plot
• plt.show()
Saving Figures in OOP
• fig, ax = plt.subplots()
• ax.plot([1, 2, 3], [1, 4, 9])