UNIT V
Plotting Functions in Python (Google Colab)
Introduction
Plotting is a vital skill in data visualization. In Python, the Matplotlib library is the most
widely used tool for creating static, animated, and interactive plots. Google Colab
provides an excellent environment for running and visualizing Python code directly in the
browser.
1. Getting Started with Matplotlib
Import the necessary libraries:
import [Link] as plt
import numpy as np
%matplotlib inline
- [Link] is used for 2D plotting.
- %matplotlib inline displays plots within the notebook.
Basic structure of a plot:
[Link](x, y)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Plot Title')
[Link]()
2. Line Plot
Used to represent continuous data or trends over time.
import numpy as np
import [Link] as plt
x_line = [1, 2, 3, 4, 5]
y_line = [2, 4, 6, 8, 10]
[Link](figsize=(6, 4))
[Link](x_line, y_line)
[Link]('Simple Line Plot')
[Link]('X-axis')
[Link]('Y-axis')
[Link]()
3. Scatter Plot
Used to visualize the relationship between two numerical variables.
import numpy as np
import [Link] as plt
x_line = [1, 2, 3, 4, 5]
y_line = [2, 4, 6, 8, 10]
[Link](figsize=(6, 4))
[Link](x_line, y_line)
[Link]('Simple Line Plot')
[Link]('X-axis')
[Link]('Y-axis')
[Link]()
4. Bar Chart
Represents categorical data with rectangular bars.
import [Link] as plt
categories = ['A', 'B', 'C', 'D']
values = [10, 7, 12, 5]
[Link](figsize=(6, 4))
[Link](categories, values)
[Link]('Simple Bar Plot')
[Link]('Category')
[Link]('Value')
[Link]()
5. Histogram
Used to show the frequency distribution of data.
import numpy as np
import [Link] as plt
data = [Link](1000)
[Link](data, bins=30, color='lightgreen', edgecolor='black')
[Link]('Histogram Example')
[Link]('Value')
[Link]('Frequency')
[Link]()
6. Box Plot
Displays spread and identifies outliers.
import numpy as np
import [Link] as plt
categories = ['A', 'B', 'C', 'D']
values = [10, 7, 12, 5]
[Link](figsize=(6, 4))
[Link](categories, values)
[Link]('Simple Bar Plot')
[Link]('Category')
[Link]('Value')
[Link]()
7. Pie Chart
Represents data as proportions of a whole.
import numpy as np
import [Link] as plt
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
sizes = [20, 35, 30, 15]
[Link](sizes, labels=labels, autopct='%1.1f%%', startangle=90)
[Link]('Pie Chart Example')
[Link]()
8. Subplots
Used for multiple plots within one figure.
import [Link] as plt
import numpy as np
# 1. Create a figure and a grid of subplots (1 row, 2 columns)
fig, axes = [Link](1, 2, figsize=(10, 5))
# Sample data
x_line = [Link](0, 10, 100)
y_line = [Link](x_line)
x_scatter = [Link](50) * 10
y_scatter = [Link](50) * 10
# 2. On the first subplot, generate a simple line plot
axes[0].plot(x_line, y_line)
# 4. Add a title to the first subplot
axes[0].set_title('Line Plot')
# 5. Add labels to the x and y axes of the first subplot
axes[0].set_xlabel('X-axis')
axes[0].set_ylabel('Y-axis')
# 3. On the second subplot, generate a simple scatter plot
axes[1].scatter(x_scatter, y_scatter)
# 4. Add a title to the second subplot
axes[1].set_title('Scatter Plot')
# 5. Add labels to the x and y axes of the second subplot
axes[1].set_xlabel('X-axis')
axes[1].set_ylabel('Y-axis')
# Adjust layout to prevent labels overlapping
plt.tight_layout()
# 6. Display the figure containing the subplots
[Link]()
9. Styling and Customization
Common attributes:
- Colors: 'r', 'g', 'b', 'k', 'c', 'm', 'y'
- Line styles: '-', '--', ':', '-.'
- Markers: 'o', 's', '^', '*', 'x'
Example:
[Link](x, [Link](x), 'r--o', label='sin(x)')
[Link](x, [Link](x), 'b-.s', label='cos(x)')
[Link]()
[Link]()
Customization in various graphs
import numpy as np
import [Link] as plt
# 1. Create sample data
x_data = [Link](0, 10, 100)
y_data_1 = [Link](x_data)
y_data_2 = [Link](x_data)
categories = ['Category A', 'Category B', 'Category C', 'Category D',
'Category E']
values = [25, 40, 30, 35, 50]
# 2. Generate a line plot and customize it
[Link](figsize=(8, 5))
[Link](x_data, y_data_1)
[Link]('Customized Line Plot', fontsize=16)
[Link]('X-axis Label', fontsize=12)
[Link]('Y-axis Label', fontsize=12)
[Link](True)
[Link]()
# 3. Generate a scatter plot and customize marker style and color
[Link](figsize=(8, 5))
[Link](x_data[::10], y_data_1[::10], marker='X', color='red', s=100)
# Using a subset of data for scatter
[Link]('Customized Scatter Plot', fontsize=16)
[Link]('X-axis Label', fontsize=12)
[Link]('Y-axis Label', fontsize=12)
[Link](True)
[Link]()
# 4. Generate a bar plot and change the bar color
[Link](figsize=(8, 5))
[Link](categories, values, color=['skyblue', 'lightcoral', 'lightgreen' , 'gold', 'orchid'])
[Link]('Customized Bar Plot', fontsize=16)
[Link]('Categories', fontsize=12)
[Link]('Values', fontsize=12)
[Link]()
# 5. Create a plot with multiple lines and add a legend
[Link](figsize=(8, 5))
[Link](x_data, y_data_1, label='sin(x)', linestyle='--')
[Link](x_data, y_data_2, label='cos(x)', linestyle='-.')
[Link]('Plot with Multiple Lines and Legend', fontsize=16)
[Link]('X-axis Label', fontsize=12)
[Link]('Y-axis Label', fontsize=12)
[Link](loc='upper right')
[Link](True)
[Link]()
10. Text and Annotations
import numpy as np
import [Link] as plt
x = [Link](0, 2*[Link], 100)
y = [Link](x)
[Link](x, y)
[Link]('Max Point', xy=([Link]/2, 1), xytext=(2, 1.2),
arrowprops=dict(facecolor='black', shrink=0.05))
[Link]()
11. Saving Figures
[Link]('plot_example.png', dpi=300, bbox_inches='tight')
12. Interactive Plotting (Optional – Plotly)
!pip install plotly
import [Link] as px
import pandas as pd
df = [Link]()
fig = [Link](df, x='sepal_width', y='sepal_length', color='species')
[Link]()
13. Practice Exercises
1. Plot quadratic and cubic functions with proper titles and legends.
2. Create a histogram of 1000 random numbers.
3. Draw a grouped bar chart comparing two datasets.
4. Generate a 2×2 subplot (line, scatter, histogram, boxplot).
5. Add annotations to mark the maximum point in a sine curve.
Summary Table
Plot Type Function Purpose
Line Plot [Link]() Shows trends or changes
Scatter Plot [Link]() Correlation between
variables
Bar Chart [Link]() Comparison of categories
Histogram [Link]() Frequency distribution
Box Plot [Link]() Spread and outliers
Pie Chart [Link]() Composition or percentage
Matplotlib offers flexible tools to visualize data effectively. Start with simple plots, learn
customization, and then move to subplots and interactive charts.