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

UNIT-IV - Matplotlib

Python libraries

Uploaded by

Raja shree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

UNIT-IV - Matplotlib

Python libraries

Uploaded by

Raja shree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Matplotlib

 Matplotlib is a popular Python library used for creating static, animated, and interactive
visualizations in python.
 It provides a comprehensive set of tools for creating high-quality 2D and 3D plots, charts,
and graphs.
 It also offers customization options, and integration with other libraries like NumPy and
Pandas.

Key Features:
 Plotting: Line plots, scatter plots, histograms, bar charts, pie charts, and more.
 Customization: Control over colors, fonts, labels, titles, axes, and more.
 Output: Save plots to files (PNG, PDF, EPS, SVG) or display interactively.
 Integration: Works well with other popular libraries like NumPy, Pandas, and Scikit-
learn.

Getting Started with Matplotlib


1. Installation: To install Matplotlib, use pip:
pip install matplotlib
2. Basic Import:
import matplotlib.pyplot as plt

Basic Steps to Create a Plot:

1. Import the necessary library:

import matplotlib.pyplot as plt


import numpy as np

2. Prepare your data:


o Create a list or NumPy array for your x-axis and y-axis values.

3. Create the plot:


o Use a specific plotting function like plt.plot( ), plt.scatter( ), plt.bar( ),
etc.
o Customize the plot with various parameters like labels, titles, colors, line styles,
and markers.
4. Display the plot:
o Use plt.show( ) to display the plot on your screen.
Basic Plotting
Here’s an example of a simple line plot:

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

# Create plot
plt.plot(x, y)

# Add title and labels


plt.title('Line Plot Example')
plt.xlabel('X')
plt.ylabel('Y')

# Display plot
plt.show()
OUTPUT:

Common Plot Types

1. Line Plot: Useful for visualizing trends over a continuous interval.

plt.plot(x, y)

plt.show()

2. Scatter Plot: Useful for displaying individual data points

plt.scatter(x, y)

plt.show()
3. Bar Chart: Suitable for comparing discrete categories.
categories = ["A", "B", "C"]
values = [5, 7, 3]
plt.bar(categories, values)
plt.show()

4. Histogram: Ideal for showing the distribution of data.

data = [1, 2, 2, 3, 3, 3, 4, 4, 5]

plt.hist(data, bins=5)

plt.show()

5. Pie Chart: Useful for showing proportions.


labels = ['Category A', 'Category B', 'Category C']
sizes = [30, 40, 30]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.show()

Customizing Plots

 Labels and Titles: Use plt.xlabel(), plt.ylabel(), and plt.title() to


add descriptive text.
 Grid: Enable grids with plt.grid(True).
 Legends: Use plt.legend() to add a legend to your plot.
 Colors: 'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', or color names like 'blue', 'green', etc
 Line styles: '-', '--', '-.', ':', etc.

Saving Figures

Save plots directly as image files (e.g., PNG, JPG, PDF):

plt.savefig("plot.png")

Advanced Features

 Annotations: Add text to specific points in the plot with plt.annotate().


 3D Plotting: Use mpl_toolkits.mplot3d for 3D plots.
 Interactivity: Matplotlib can be combined with other libraries like seaborn and
plotly for enhanced interactive capabilities.
EXAMPLES

import matplotlib.pyplot as plt


import numpy as np

# Sample data
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 9, 16, 25])

# Create the plot


plt.plot(x, y, marker="o", linestyle="--")
# marker="o" - style of the marker for data points in a plot
# linestyle="--" means Dashed line

# Add annotations
for i in range(len(x)):
plt.annotate(f"({x[i]}, {y[i]})", (x[i], y[i]), textcoords="offset points",
xytext=(0,10), ha='center')

plt.show()

Note:-

plt.annotate(f"({x[i]}, {y[i]})", (x[i], y[i]), textcoords="offset points",


xytext=(0,10), ha='center')

f"({x[i]}, {y[i]})"

- This is an f-string (formatted string literal) shows the coordinates of the point in the
format (x, y).

(x[i], y[i])

- This specifies the (x, y) coordinate of the point where you want the annotation to
appear.

(x[i], y[i])

- This specifies the (x, y) coordinate of the point where you want the annotation to
appear.

xytext=(0, 10)
- This specifies the offset for the annotation text in points, relative to the specified data
point (x[i], y[i]).

 (0, 10) means the text will be positioned 0 points horizontally (no shift left or right)
and 10 points vertically above the point.
 This offset helps prevent the annotation text from overlapping directly on the point,
making it more readable.

 ha='center'

 This controls the horizontal alignment of the annotation text relative to its position.
 'center' means the annotation text will be centered horizontally above the point.

OUTPUT
Example of Bar Chart
import matplotlib.pyplot as plt

# Sample data
x = ["Apples", "Bananas", "Cherries", "Dates"]
y = [10, 15, 7, 12]

# Creating the bar chart


plt.bar(x, y, color="blue")

# Adding labels and title


plt.xlabel("Fruits")
plt.ylabel("Quantity")
plt.title("Fruit Quantities in Inventory")
for i in range(len(x)):
plt.annotate(f"({x[i]}, {y[i]})", (x[i], y[i]), textcoords="offset points",
xytext=(0,5), ha='center')

# Display the chart


plt.show()

OUTPUT
Example of HISTOGRAM

import matplotlib.pyplot as plt


import numpy as np
data = [1, 2, 2, 3, 3, 3, 4, 4, 5]
plt.hist(data, bins=5,edgecolor="black")
plt.show()

# bins=5: This specifies the number of bins (intervals) to use for the histogram. In this case,
the data will be divided into 5 equal-width bins.

subplot

A subplot in Matplotlib allows you to create multiple plots (axes) in a single figure, enabling
you to visualize different datasets or aspects of a dataset side-by-side. This is especially useful
when comparing multiple charts or examining various facets of data in one view.

Basic Syntax for Subplots

The plt.subplot() function creates a subplot within a grid of a specified number of rows and
columns. The syntax is as follows:

plt.subplot(nrows, ncols, index)

 nrows: The number of rows in the subplot grid.


 ncols: The number of columns in the subplot grid.
 index: The position of the subplot within the grid, numbered from left to right, top to
bottom, starting at 1.

For example, plt.subplot(2, 2, 1) will create a 2x2 grid of subplots and place the plot in the
first (top-left) position.
Example: Creating a 2x2 Grid of Subplots

Here’s how to create four subplots in a 2x2 grid, each with its own data and title:

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [25, 16, 9, 4, 1]
y3 = [1, 2, 3, 4, 5]
y4 = [5, 4, 3, 2, 1]

# Creating a 2x2 grid of subplots


plt.subplot(2, 2, 1) # First subplot in a 2x2 grid
plt.plot(x, y1)
plt.title("y = x^2")

plt.subplot(2, 2, 2) # Second subplot


plt.plot(x, y2)
plt.title("y = (5 - x)^2")

plt.subplot(2, 2, 3) # Third subplot


plt.plot(x, y3)
plt.title("y = x")

plt.subplot(2, 2, 4) # Fourth subplot


plt.plot(x, y4)
plt.title("y = 5 - x")

plt.tight_layout() # Adjust layout to prevent overlapping


plt.show()

OUTPUT
Explanation of Code

 plt.subplot(2, 2, 1): This creates a 2x2 grid and places the first plot in the top-left
position.
 plt.plot(x, y1): Plots the data for the first subplot.
 plt.title("y = x^2"): Sets the title for the first subplot.
 plt.tight_layout(): Automatically adjusts the spacing between subplots to prevent
overlapping labels and titles.

Subplots with plt.subplots()

Matplotlib also provides a more flexible method, plt.subplots(), which creates a grid and
returns a figure and an array of axes objects, making it easier to loop over subplots or access
them individually.

fig, axs = plt.subplots(2, 2) # Creates a 2x2 grid

# Assign data to each subplot


axs[0, 0].plot(x, y1)
axs[0, 0].set_title("y = x^2")

axs[0, 1].plot(x, y2)


axs[0, 1].set_title("y = (5 - x)^2")

axs[1, 0].plot(x, y3)


axs[1, 0].set_title("y = x")

axs[1, 1].plot(x, y4)


axs[1, 1].set_title("y = 5 - x")

plt.tight_layout()
plt.show()
Summary

 Subplots allow multiple plots within a single figure.


 plt.subplot() sets up each subplot individually.
 plt.subplots() creates a grid layout and returns handles for both the figure and
individual subplots for easier access.

You might also like