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

Basic Line Plot Using Matplotlib

Uploaded by

myprojectai9
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)
0 views

Basic Line Plot Using Matplotlib

Uploaded by

myprojectai9
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/ 9

1.

Basic Plotting Functions

Function Description

plt.plot(x, y) Line plot

plt.scatter(x, y) Scatter plot

plt.bar(x, height) Vertical bar chart

plt.barh(y, width) Horizontal bar chart

plt.hist(data) Histogram

plt.pie(sizes) Pie chart

plt.boxplot(data) Box and whisker plot

plt.stackplot(x, y) Stack plot

2. Labels and Titles

Function Description

plt.title("Title") Add title to graph

plt.xlabel("X Label") Label for X-axis

plt.ylabel("Y Label") Label for Y-axis

plt.legend() Show legend for labels in plot

plt.grid(True) Show grid

plt.text(x, y, "text") Place custom text on plot

3. Styling and Customization

Function Description

plt.plot(x, y, 'r--') Red dashed line (r-- = red + dashed)

plt.style.use('ggplot') Use predefined plot styles

plt.figure(figsize=(w,h)) Set figure size

plt.axis([xmin, xmax, ymin, ymax]) Set axis limits

plt.xlim() / plt.ylim() Set X or Y limits

plt.xticks() / plt.yticks() Customize tick marks

4. Subplots and Layouts


Function Description

plt.subplot(nrows, ncols, index) Add subplot (e.g. plt.subplot(2,2,1))

plt.subplots() Create figure and axes (object-oriented)

plt.tight_layout() Prevent overlapping elements

Basic Plotting Functions

# 1. Line Plot

x=[2, 4, 6, 12, 9]

y = [10, 15, 13, 18, 16]

plt.figure(figsize=(6,4))

plt.plot(x, y, marker='o')

plt.title("Line Plot: Stock Price Over Days")

plt.xlabel("Day")

plt.ylabel("Stock Price")

plt.grid(True)

plt.show()

x---------------------------------------------------------------------x

# 2. Scatter Plot

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

scores = [50, 55, 65, 70, 85]

plt.figure(figsize=(6,4))

plt.scatter(study_hours, scores, color='red')

plt.title("Scatter Plot: Study Hours vs Exam Score")

plt.xlabel("Study Hours")

plt.ylabel("Exam Score")

plt.grid(True)

plt.show()

x---------------------------------------------------------------------x

# 3. Bar Chart (Vertical)

products = ['A', 'B', 'C', 'D']

sales = [150, 200, 300, 250]

plt.figure(figsize=(6,4))
plt.bar(products, sales, color='green')

plt.title("Bar Chart: Product Sales")

plt.xlabel("Product")

plt.ylabel("Sales")

plt.show()

x---------------------------------------------------------------------x

# 4. Horizontal Bar Chart

countries = ['USA', 'India', 'China', 'Brazil']

population = [331, 1391, 1441, 213]

plt.figure(figsize=(6,4))

plt.barh(countries, population, color='orange')

plt.title("Horizontal Bar Chart: Country Population (Millions)")

plt.xlabel("Population")

plt.ylabel("Country")

plt.show()

x---------------------------------------------------------------------x

# 5. Histogram

ages = [22, 25, 27, 25, 30, 35, 40, 23, 33, 25, 29, 40, 50]

plt.figure(figsize=(6,4))

plt.hist(ages, bins=5, color='purple', edgecolor='black')

plt.title("Histogram: Age Distribution")

plt.xlabel("Age")

plt.ylabel("Frequency")

plt.show()

x---------------------------------------------------------------------x

# 6. Pie Chart

departments = ['HR', 'R&D', 'Marketing', 'IT']

budget = [20, 40, 25, 15]

plt.figure(figsize=(6,6))

plt.pie(budget, labels=departments, autopct='%1.1f%%', startangle=140)

plt.title("Pie Chart: Budget Allocation")


plt.show()

x---------------------------------------------------------------------x

# 7. Box and Whisker Plot

scores = [65, 70, 72, 68, 75, 80, 85, 90, 88, 95, 100]

plt.figure(figsize=(6,4))

plt.boxplot(scores)

plt.title("Boxplot: Test Scores")

plt.ylabel("Score")

plt.show()

x---------------------------------------------------------------------x

# 8. Stack Plot

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']

food = [200, 220, 250, 270, 300]

rent = [800, 800, 800, 800, 800]

utilities = [150, 160, 170, 180, 190]

plt.figure(figsize=(6,4))

plt.stackplot(months, food, rent, utilities, labels=['Food', 'Rent', 'Utilities'])

plt.title("Stack Plot: Monthly Expenses")

plt.xlabel("Month")

plt.ylabel("Cost")

plt.legend(loc='upper left')

plt.show()

Styling and Customization

import matplotlib.pyplot as plt

import numpy as np

days = np.arange(1, 6)

actual = [10, 15, 13, 18, 16]

predicted = [11, 14, 14, 17, 17]


plt.figure(figsize=(6, 4))

plt.plot(days, actual, 'b-', label='Actual') # Solid blue line

plt.plot(days, predicted, 'r--', label='Predicted') # Red dashed line

plt.title("Stock Price: Actual vs Predicted")

plt.xlabel("Day")

plt.ylabel("Price")

plt.legend()

plt.grid(True)

plt.show()

x---------------------------------------------------------------------x

plt.style.use('ggplot') # Apply global styling

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

scores = [50, 55, 65, 70, 85]

plt.figure(figsize=(6, 4))

plt.scatter(study_hours, scores, color='purple')

plt.title("Study Hours vs Exam Score")

plt.xlabel("Study Hours")

plt.ylabel("Score")

plt.grid(True)

plt.show()

x------------------------------------------------------------------------x

countries = ['USA', 'India', 'China', 'Brazil']

population = [331, 1391, 1441, 213]

plt.figure(figsize=(10, 6)) # Increase width and height

plt.barh(countries, population, color='orange')

plt.title("Population by Country")

plt.xlabel("Population (Millions)")

plt.ylabel("Country")
plt.show()

Numpy
arr = np.arange(0, 11, 2)

print("Array with step 2:", arr)

x----------------------------------------------------------------x

arr = np.linspace(0, 1, 5)

print("Linearly spaced array:", arr)

x-----------------------------------------------------------------x

data = np.array([10, 20, 30, 40])

print("Sum:", np.sum(data))

print("Min:", np.min(data))

print("Max:", np.max(data))
Bar Chart Example

import matplotlib.pyplot as plt

# Data

categories = ['Math', 'Science', 'English', 'History']

scores = [88, 92, 79, 85]

# Plot
plt.bar(categories, scores, color='skyblue')

plt.title('Student Scores')

plt.xlabel('Subjects')

plt.ylabel('Marks')

plt.show()

Pie Chart Example

import matplotlib.pyplot as plt

#Data

activities = ['Sleep', 'Work', 'Exercise', 'Leisure']

hours = [8, 9, 2, 5]

# Plot

plt.pie(hours, labels=activities, autopct='%1.1f%%', startangle=90)

plt.title('Daily Activity Breakdown')

plt.axis('equal') # Makes pie a circle

plt.show()

Scatter Plot Example

python

CopyEdit

import matplotlib.pyplot as plt

# Data

x = [5, 7, 8, 7, 2, 17, 2, 9]

y = [99, 86, 87, 88, 100, 86, 103, 87]

# Plot

plt.scatter(x, y, color='red', marker='o')

plt.title('Age vs Score')

plt.xlabel('Age')

plt.ylabel('Score')

plt.grid(True)
plt.show()

Multiple Lines on One Graph

import matplotlib.pyplot as plt

# Data

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

temperature = [30, 32, 34, 33, 31]

humidity = [60, 65, 63, 62, 64]

# Plot multiple lines

plt.plot(days, temperature, label='Temperature (°C)', color='orange', marker='o')

plt.plot(days, humidity, label='Humidity (%)', color='blue', marker='s')

plt.title('Weather Report')

plt.xlabel('Day')

plt.ylabel('Measurement')

plt.legend()

plt.grid(True)

plt.show()

You might also like