15octmatplotlib 2024
15octmatplotlib 2024
1. Overview of Matplotlib
- What is Matplotlib?
Matplotlib is a Python library used to create graphs and charts. It's widely
used for
data visualization.
- History:
Matplotlib was created by John D. Hunter in 2003 to make easy, flexible plots.
- Importance in Data Visualization:
Data visualization helps to understand complex data easily by turning numbers
into visual
graphs like line plots, bar charts, etc. Matplotlib is one of the best tools
for this in
Python.
2. Installation
- To use Matplotlib, you need to install it first:
- Using pip (the Python package manager):
bash
pip install matplotlib
3. Basic Structure
- pyplot Module:
Matplotlib has a module called pyplot that makes it easy to create plots.
You can think of pyplot as a set of commands that help you make different
types of plots.
- Creating a Simple Plot:
- Line plot example:
python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4]) Simple line plot
plt.show() Display the plot
This makes the plot appear right after the code in the notebook.
- Standalone Plots:
If you are using a normal Python script (not in Jupyter), the plot will appear
in
a new window when you use plt.show().
5. Multiple Plots
- Subplots:
You can put multiple plots in the same figure using subplot(). This is useful
for comparing different data side by side.
- plt.subplot(2, 1, 1) means 2 rows, 1 column, first plot.
- Sharing Axes:
You can make multiple plots share the same X-axis or Y-axis using plt.subplots()
with the option sharex=True or sharey=True.
- Customizing Layouts:
You can adjust the layout of multiple plots with plt.tight_layout() so they don't
overlap.
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.title('Simple Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
plt.bar(x, y, color='blue')
plt.title('Simple Bar Plot')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
4. Simple Histogram
python
data = [22, 30, 35, 36, 40, 42, 42, 45, 48, 49, 50, 52]
plt.bar(x, y, color='orange')
plt.title('Bar Plot with Grid')
plt.xlabel('Fruits')
plt.ylabel('Quantity')
plt.grid(True)
plt.show()