0% found this document useful (0 votes)
10 views6 pages

Description of Matplotlib

Matplotlib is a powerful Python library for creating a variety of plots including line plots, bar charts, histograms, and pie charts. It offers extensive customization options for visualizations, allowing users to modify colors, styles, and labels. The document provides examples of different plot types and their syntax, along with practical problems to illustrate how to use Matplotlib effectively.

Uploaded by

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

Description of Matplotlib

Matplotlib is a powerful Python library for creating a variety of plots including line plots, bar charts, histograms, and pie charts. It offers extensive customization options for visualizations, allowing users to modify colors, styles, and labels. The document provides examples of different plot types and their syntax, along with practical problems to illustrate how to use Matplotlib effectively.

Uploaded by

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

Description of Matplotlib  x: X-axis data (e.g.

, time, categories)
 y: Y-axis data (e.g., values)
Matplotlib is a comprehensive and widely used  options: Optional formatting for line color,
data visualization library for the Python style, width, etc.
programming language. It provides functions and
tools for creating static, animated, and Simple Example
interactive plots in Python.
import matplotlib.pyplot as plt
Commonly Used Module # Sample data
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]
Simple Example y = [10, 12, 8, 14, 20]
import matplotlib.pyplot as plt # Create line plot
x = [1, 2, 3, 4] plt.plot(x, y)
y = [10, 20, 25, 30] # Add labels and title
plt.plot(x, y) # Create a line plot plt.xlabel('Time (days)')
plt.title("Simple Line Plot") # Title plt.ylabel('Value')
plt.xlabel("X Axis") # X-axis label plt.title('Simple Line Plot')
plt.ylabel("Y Axis") # Y-axis label # Show grid and display the plot(This is outline
plt.grid(True) # Show grid of Graph)
plt.show() # Display plot plt.grid(True)

Types of Plots in Matplotlib plt.show()


Customization Options
plt.plot() – Line plot

plt.scatter() – Scatter plot 🔹 Line Style and Color

plt.bar() – Bar chart plt.plot(x, y, color='green', linestyle='--',


linewidth=2, marker='o')
plt.hist() – Histogram
 color='red' – Line color
plt.pie() – Pie chart  linestyle='--' – Dashed line
 linewidth=2 – Thickness of the line
plt.boxplot() – Box plot
Multiple Line Plots
Line Plots: y2 = [5, 7, 9, 13, 17]
 To show trends over time (e.g., stock plt.plot(x, y, label="Series A")
prices, temperature, population).
plt.plot(x, y2, label="Series B")
 To compare multiple data series.
 To visualize changes, slopes, and patterns plt.title("Multiple Line Plots")
in data.
plt.legend()
Basic Syntax plt.show()
import matplotlib.pyplot as plt Problem: Given temperatures of a city over 7
plt.plot(x, y, options) days, create a line plot.
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] plt.ylabel("Price ($)")
temperature = [30, 32, 33, 31, 29, 28, 27] plt.show()
import matplotlib.pyplot as plt Website Visitors Per Hour
plt.plot(days, temperature)
Problem: Plot visitors from 8AM to 8PM
plt.title("Temperature Over a Week")
hours = list(range(8, 21))
plt.xlabel("Days")
visitors = [10, 15, 25, 30, 45, 50, 40, 35, 30, 20, 15,
plt.ylabel("Temperature (°C)")
10, 5]
plt.grid(True)
plt.plot(hours, visitors)
plt.show()
plt.title("Website Visitors Per Hour")
Compare Sales of Two Products
plt.xlabel("Hour of Day")
Problem: Plot and compare sales of Product A
and Product B for 5 months. plt.ylabel("Visitors")

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'] plt.xticks(hours)

product_a = [100, 120, 140, 160, 180] plt.grid(True)

product_b = [90, 110, 130, 150, 170] plt.show()

plt.plot(months, product_a, label="Product A") Heart Rate During Exercise


plt.plot(months, product_b, label="Product B") Problem: Plot heart rate during a 10-minute run.

plt.title("Monthly Sales Comparison") minutes = list(range(1, 11))

plt.xlabel("Months") heart_rate = [80, 85, 90, 100, 110, 115, 120, 125, 130,
135]
plt.ylabel("Sales")
plt.plot(minutes, heart_rate, color='red')
plt.legend()
plt.title("Heart Rate Over Time")
plt.show()
plt.xlabel("Minutes")
Stock Price Visualization plt.ylabel("Heart Rate (bpm)")
Problem: Show the fluctuation of a stock over 5 plt.show()
days.
Problem : Age vs Screen Time
Data:
Q: Show how screen time changes with age.
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
price = [150, 155, 153, 160, 158] age = [10, 15, 20, 25, 30, 35, 40]
plt.plot(days, price, marker='o', color='green') screen_time = [3, 4, 5, 4.5, 4, 3.5, 3]
plt.scatter(age, screen_time,
color='orange')
plt.title("Stock Price Over 5 Days") plt.title("Age vs Screen Time")
plt.xlabel("Age")
plt.xlabel("Days") plt.ylabel("Screen Time (hours/day)")
plt.show()
Problem : Heart Rate vs Calories Burned
plt.bar(products, sales)
plt.title("Product Sales")
Q: Plot heart rate vs calories burned during exercise. plt.xlabel("Product")
plt.ylabel("Sales")
heart_rate = [80, 90, 100, 110, 120, 130] plt.show()
calories = [50, 70, 90, 110, 130, 160]
plt.scatter(heart_rate, calories,
color='crimson')
plt.title("Heart Rate vs Calories") Problem : Vertical and Horizontal Bar Chart
plt.xlabel("Heart Rate (bpm)")
plt.ylabel("Calories Burned") Q: Convert the above chart into a horizontal bar chart.
plt.grid(True)
plt.show()
python
CopyEdit
plt.barh(products, sales, color='green')
Create a Bar Chart plt.title("Horizontal Bar Chart")
plt.xlabel("Sales")
A bar chart represents categorical data with rectangular plt.ylabel("Product")
plt.show()
bars. The height (or length) of each bar is proportional to
the value it represents.
Problem : Show Different Colors for Each
import matplotlib.pyplot as plt Bar
plt.bar(x, height)
Q: Display different colors for each bar.
plt.show()
python
CopyEdit
Common Parameters: colors = ['red', 'blue', 'yellow',
Parameter Description 'orange']

Color plt.bar(products, sales, color=colors)


Bar color
plt.title("Colored Bars")
plt.show()
width Width of bars

label Label for legend Problem : Add Bar Value Labels

Q: Add values above each bar.


Basic Bar Chart
python
import matplotlib.pyplot as plt CopyEdit
bars = plt.bar(products, sales)
fruits = ['Apple', 'Banana', 'Mango', 'Grapes'] plt.title("Bar Values")
quantities = [10, 15, 7, 12] for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x() +
bar.get_width()/2, yval + 5, str(yval),
plt.bar(fruits, quantities) ha='center')
plt.title("Fruit Quantities") plt.show()
plt.xlabel("Fruits")
Monthly Expenses Bar Chart
plt.ylabel("Quantity")
Q: Plot monthly expenses.
plt.show()
python
Problem : Plot Sales of Products CopyEdit
months = ['Jan', 'Feb', 'Mar', 'Apr']
expenses = [3000, 2800, 3500, 3300]
Q: Plot sales of 4 products using a bar chart.
plt.bar(months, expenses, color='purple')
plt.title("Monthly Expenses")
python plt.ylabel("Amount (INR)")
CopyEdit plt.grid(axis='y')
products = ['A', 'B', 'C', 'D'] plt.show()
sales = [100, 150, 90, 200]
Problem : Show Population of Cities plt.ylabel("Frequency")
plt.show()
Q: Display population data.
scores = [45, 55, 62, 48, 52, 67, 70, 65, 60, 59]
python
CopyEdit
cities = ['Delhi', 'Mumbai', 'Chennai', Problem : Exam Scores Distribution
'Kolkata']
population = [19000000, 18000000, 10000000, Q: Create a histogram for the given exam scores.
15000000]
python
plt.bar(cities, population, CopyEdit
color='steelblue') scores = [45, 55, 62, 48, 52, 67, 70, 65,
plt.title("City Population") 60, 59]
plt.ylabel("Population")
plt.xticks(rotation=45) plt.hist(scores, bins=5,
plt.show() color='lightgreen', edgecolor='black')
plt.title("Exam Score Distribution")
Problem : Subject-wise Student Marks plt.xlabel("Score Ranges")
plt.ylabel("Number of Students")
plt.show()
Q: Plot marks in different subjects.

python
Problem : Custom Bin Ranges
CopyEdit
subjects = ['Math', 'Science', 'English', Q: Use custom bins [40, 50, 60, 70, 80] to group
'History'] data.
marks = [95, 88, 75, 80]
python
plt.bar(subjects, marks, color='coral')
CopyEdit
plt.title("Subject-wise Marks")
bins = [40, 50, 60, 70, 80]
plt.ylabel("Marks")
plt.ylim(0, 100)
plt.hist(scores, bins=bins, color='orange',
plt.show()
edgecolor='black')
plt.title("Custom Bins")
plt.xlabel("Score Range")
Histogram in Python (Matplotlib) plt.ylabel("Frequency")
plt.show()

A Histogram is a type of bar chart that shows the


distribution of a dataset. It groups values into bins Problem : Age Distribution
(intervals) and counts how many values fall into each
bin. Q: Plot the age distribution of 20 people.

ages = [22, 25, 29, 24, 30, 35, 40, 38, 31,
 X-axis: Data bins (e.g., 0–10, 10–20, etc.) 29, 27, 25, 24, 30, 33, 36, 28, 34, 32, 26]
 Y-axis: Frequency (count) of values in each
bin plt.hist(ages, bins=5, color='blue',
edgecolor='white')
plt.title("Age Distribution")
Basic Syntax of Histogram in Matplotlib plt.xlabel("Age Groups")
import matplotlib.pyplot as plt plt.ylabel("Frequency")
plt.show()
plt.hist(data, bins=number_of_bins,
color='color_name', edgecolor='black')
plt.show()
Problem : Show Normalized Histogram
Simple Example (Probability)
import matplotlib.pyplot as plt
plt.hist(ages, bins=5, density=True,
data = [56, 45, 67, 59, 62, 70, 72, 55, 61, 68] color='salmon', edgecolor='black')
plt.title("Normalized Histogram")
plt.hist(data, bins=5, color='skyblue', edgecolor='black') plt.ylabel("Probability")
plt.show()
plt.title("Score Distribution")
plt.xlabel("Score") Problem : Temperature Distribution
Q: Plot frequency of daily temperatures. Q: Plot the preference of programming languages
among 5 students.
temps = [28, 30, 32, 31, 29, 33, 35, 36,
30, 31, 29, 28, 34, 35] languages = ['Python', 'Java', 'C++',
'JavaScript', 'Go']
plt.hist(temps, bins=4, color='navy', students = [40, 25, 15, 10, 10]
edgecolor='white')
plt.title("Temperature Frequency") plt.pie(students, labels=languages,
plt.xlabel("Temperature (°C)") autopct='%1.1f%%')
plt.ylabel("Days") plt.title("Programming Language
plt.show() Preferences")
plt.show()

Pie Chart Problem : Survey of Transport Modes


A pie chart is a circular statistical diagram, divided into Q: Display the survey result of preferred transport
slices to illustrate numerical proportion. modes.
Each slice represents a category’s contribution to the
whole (100%) modes = ['Car', 'Bus', 'Bike', 'Train']
votes = [50, 30, 10, 10]
Basic Syntax of Pie Chart in Matplotlib plt.pie(votes, labels=modes,
import matplotlib.pyplot as plt autopct='%1.1f%%')
plt.title("Preferred Transport Modes")
plt.pie(values, labels=labels) plt.show()
plt.show()

Problem : Sales Percentage of Products


 values: List of numbers (quantities or percentages)
Q: Show sales share among 3 products.
 labels: Corresponding category names
products = ['Product A', 'Product B',
Common Parameters 'Product C']
sales = [5000, 3000, 2000]
Parameter Description
plt.pie(sales, labels=products,
labels Labels for each slice autopct='%1.1f%%')
plt.title("Sales Distribution")
colors plt.show()
Custom colors for slices

autopct Format string to display percentages


Problem : Budget Allocation
startangle Rotation angle of the chart (in degrees)
Q: Visualize budget distribution across departments.
explode "Explodes" one or more slices
departments = ['HR', 'IT', 'Marketing',
shadow Adds a shadow to the pie 'R&D']
budget = [20000, 40000, 25000, 15000]

Simple Example: Pie Chart plt.pie(budget, labels=departments,


import matplotlib.pyplot as plt autopct='%1.1f%%', startangle=140)
plt.title("Department Budget Allocation")
labels = ['Apples', 'Bananas', 'Cherries', plt.show()
'Dates']
sizes = [25, 35, 20, 20] Problem : Gender Distribution in a Class
plt.pie(sizes, labels=labels,
autopct='%1.1f%%') Q: Plot pie chart for gender representation.
plt.title("Fruit Distribution")
plt.show() genders = ['Male', 'Female']
counts = [18, 22]
Problem : Student Choices of Programming plt.pie(counts, labels=genders,
Languages autopct='%1.1f%%', colors=['blue', 'pink'])
plt.title("Gender Distribution")
plt.show()
plt.boxplot([math, science],
Box Plot labels=['Math', 'Science'])
plt.title("Math vs Science Scores")
A Box Plot displays the spread and skewness of a plt.show()
dataset by showing:
Problem 3: Horizontal Box Plot
 Minimum (Q0)
 First Quartile (Q1) – 25% plt.boxplot(scores, vert=False)
plt.title("Horizontal Box Plot")
 Median (Q2) – 50% plt.xlabel("Score")
 Third Quartile (Q3) – 75% plt.show()
 Maximum (Q4) – 100%
 Outliers (if any) Problem 4: Show Mean in Box Plot

Basic Syntax plt.boxplot(scores, showmeans=True)


plt.title("Box Plot with Mean")
import matplotlib.pyplot as plt plt.ylabel("Score")
plt.show()
plt.boxplot(data)
plt.show()
Problem 5: Box Plot with Notches
Common Parameters
Parameter Description plt.boxplot([math, science],
labels=['Math', 'Science'], notch=True)
plt.title("Box Plot with Notch")
vert Vertical (default) or horizontal plot plt.show()
patch_artist Fill box with color

labels Custom labels for multiple data series Problem 6: Multiple Box Plots with Colors

meanline Show mean line instead of mean marker data = [math, science]
plt.boxplot(data, patch_artist=True,
showmeans Show mean in the box
boxprops=dict(facecolor='skyblue',
color='black'),
medianprops=dict(color='red'),
labels=['Math', 'Science'])
Simple Box Plot Example plt.title("Colored Box Plots")
import matplotlib.pyplot as plt plt.show()

data = [10, 20, 25, 30, 35, 40, 50, 55]

plt.boxplot(data)
plt.title("Basic Box Plot")
plt.ylabel("Value")
plt.show()

Q: Plot a box plot of students' test scores.

scores = [55, 67, 73, 60, 80, 85, 70, 90,


95, 100]

plt.boxplot(scores)
plt.title("Student Test Scores")
plt.ylabel("Score")
plt.show()

Problem 2: Compare Two Datasets

Q: Compare math and science scores using a single


box plot.

math = [70, 75, 80, 60, 85, 90, 95]


science = [65, 70, 75, 80, 85, 90, 95]

You might also like