Introduction to Matplotlib

Pandas Operations for Beginners

Introduction to Matplotlib for Beginners

Learn Matplotlib step by step with outputs


Pandas Logo

🧠 What is Matplotlib?

Matplotlibis a popular Python library used for data visualization. It helps you create static, animated, and interactive plots easily. It’s especially useful for exploring data, reporting insights, and building dashboards.

🎯 Key Features of Matplotlib

  • Wide range of plotting options: Matplotlib supports a vast array of plotting types, from simple line plots to complex 3D visualizations.
  • Customization: Matplotlib allows for extensive customization of plots, including labels, titles, colors, and styles.
  • Line, bar, scatter, histogram, and many other plots
  • Customizable plots (labels, legends, colors, styles)
  • Supports multiple backends (notebook, GUI, PNG, etc.)
  • Works well with NumPy and Pandas

1. Installing Matplotlib

You can install Matplotlib using pip:

pip install matplotlib

Example

import matplotlib.pyplot as plt

# Sample data for the plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Creating the line plot
plt.plot(x, y)

# Adding a title and labels
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# Displaying the plot
plt.show()

Output:

Simple Line Plot

Explanation

  • pyplot is a module in Matplotlib that provides a MATLAB-like interface.
  • plot() draws a line graph.
  • title(), xlabel(), and ylabel() add labels to the plot.
  • show() displays the plot in a new window or notebook output.

2. Customizing Line Styles and Colors

You can make your plots more informative and visually appealing by customizing the line style, color, and marker.

Example 1: Change Line Color

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y, color='green')  # Line color
plt.title("Line Color Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

Output:

Line Color Example

Try This Code Yourself & See the Result

Change Line Style :

import matplotlib.pyplot as plt

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

plt.plot(x, y, linestyle='--')  # Dashed line
plt.title("Dashed Line Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

Add Markers to Points

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [5, 7, 6, 8, 7]

# Circle marker on points
plt.plot(x, y, marker='o')  
plt.title("Markers Example") 
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

3. Customize Multiple Properties

You can combine style, color, and marker in one line using short format:

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

plt.plot(x, y, 'r--o')  # red dashed line with circle markers
plt.title("Combined Style Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Combined Style Example

4. Creating a Histogram

A histogram shows the distribution of a dataset. It divides the data into bins (ranges) and counts how many values fall into each bin.

🧠 What is a Histogram?

  • Imagine you have a list of students' scores: data = [45, 50, 50, 55, 55, 55, 60, 60, 65, 65, 65, 65, 70, 70, 75]
  • A histogram will group similar scores together into ranges (called bins), like:
    • 40-49
    • 50-59
    • 60-69
    • 70-79
  • Then it will count how many scores fall in each range and display that count as a bar.

Example: Basic Histogram

    
import matplotlib.pyplot as plt

# Sample data
data = [1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 7]

# Create a histogram with 5 bins
plt.hist(data, bins=5)

# Add title and axis labels
plt.title("Histogram")
plt.xlabel("Value Range")
plt.ylabel("Frequency")

# Show the plot
plt.show()
    
  • 🔍 What does this code do?
    • plt.hist(data, bins=5) → Tells Python to group the data into 5 ranges (bins) and count how many values fall in each.
    • plt.title("Histogram") → Adds a title to your chart.
    • plt.xlabel("Value Range") → Labels the X-axis (the horizontal line) with the value ranges.
    • plt.ylabel("Frequency") → Labels the Y-axis (the vertical line) with how many times the values occur.
  • 🖼️ What will the graph look like?
    • The x-axis shows value ranges like 1–2, 3–4, etc.
    • The y-axis shows how many values were in each range.
    • Each bar height tells you how common values in that range are.

📌 Notes:

  • data is a list of numbers.
  • bins=5 divides the data into 5 value ranges (or "bins").
  • The y-axis shows how many data points fall into each bin.
Histogram

Try This Code Yourself & See the Result

import matplotlib.pyplot as plt

# Example: Test scores of students
scores = [55, 60, 61, 65, 65, 66, 68, 70, 72, 72, 73, 75, 78, 80, 82, 85, 85, 87, 90, 92]

# Create histogram with 6 bins
plt.hist(scores, bins=6, color='skyblue', edgecolor='black')

# Add title and labels
plt.title("Distribution of Student Scores")
plt.xlabel("Score Range")
plt.ylabel("Number of Students")

# Show the plot
plt.show()

5. Creating a Bar Plot

A bar plot is used to compare different categories or groups by showing rectangular bars with lengths proportional to the values they represent.

  • 🧠 What is a Bar Plot?
    • Imagine you want to compare how many fruits of each type you have:
    • Apple: 5
    • Banana: 7
    • Cherry: 3
    • Date: 8
    • Elderberry: 4

A bar plot will create one bar for each fruit, and the height of the bar shows how many you have.

Example: Basic Bar Plot

import matplotlib.pyplot as plt

# Categories and their quantities
categories = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry']
values = [5, 7, 3, 8, 4]

# Create a bar plot
plt.bar(categories, values)

# Add title and axis labels
plt.title("Simple Bar Plot")
plt.xlabel("Fruits")
plt.ylabel("Quantity")

# Show the plot
plt.show()
Simple Bar Plot
  • 🔍 What does this code do?
    • plt.bar(categories, values) → Draws vertical bars for each fruit with heights based on their quantities.
    • plt.title("Simple Bar Plot") → Adds a title to the chart.
    • plt.xlabel("Fruits") → Labels the horizontal axis with category names.
    • plt.ylabel("Quantity") → Labels the vertical axis with numbers.
  • 🖼️ What will the graph look like?
    • The x-axis shows the names of the fruits.
    • The y-axis shows how many of each fruit you have.
    • Each bar’s height visually represents the quantity for that fruit.
  • 📌 Notes:
    • Bar plots are great for comparing different groups or categories side by side.
    • The categories can be anything — fruits, countries, product types, etc.
    • You can change the color or orientation to customize the plot further (we’ll see that later).

Try This Code Yourself & See the Result

import matplotlib.pyplot as plt

# Example: Number of students in different classes
classes = ['Class A', 'Class B', 'Class C', 'Class D']
students = [30, 45, 20, 35]

plt.bar(classes, students, color='orange')
plt.title("Number of Students per Class")
plt.xlabel("Classes")
plt.ylabel("Number of Students")
plt.show()

Quiz Time

1. What library is commonly used in Python to create plots like histograms and bar charts?

2. Which function is used to create a line plot in matplotlib?

3. What does plt.show() do in matplotlib?

4. In a histogram, what does each bar represent?

5. Which matplotlib function creates a histogram?

6. What does the 'bins' parameter do in plt.hist()?

7. What type of data is best visualized by a bar chart?

8. Which matplotlib function is used to create a vertical bar chart?

9. How can you add a title to your matplotlib plot?

10. Which axes label represents the horizontal axis in a plot?

11. What will plt.bar(["A", "B"], [3, 5]) do?

12. Can you change the color of bars in plt.bar()?

13. What does plt.xlabel() do?

14. How do you display the plot after creating it?

15. What type of plot is best for showing frequency distribution of numeric data?

Matplotlib Practice Questions

  • 🎨 Matplotlib Practice Questions (Beginner Level)
    • Simple Line Plot
      Plot x = [0, 1, 2, 3, 4] and y = [0, 1, 4, 9, 16]. Add labels and a title.
      📌 Try changing the line color to red.
    • Multiple Lines in One Plot
      Plot two lines on the same chart:
      Line 1: x = [1, 2, 3], y = [1, 4, 9]
      Line 2: x = [1, 2, 3], y = [2, 3, 5]
      Add a legend for both lines.
    • Histogram of Random Data
      Use the following data: [5, 7, 7, 8, 9, 10, 10, 10, 11, 12]
      Create a histogram with 4 bins and a light blue color.
    • Bar Plot of Favorite Fruits
      Categories = ["Apple", "Banana", "Mango", "Orange"]
      Values = [15, 25, 10, 20]
      Use different colors and add title/axis labels.
    • Custom Line Styles
      Plot y = x² for x in range(1, 6)
      Change the line style to dashed and add markers to each point.
    • Grid Lines and Styling
      Plot any line plot and add gridlines using plt.grid(True)
      Try different line colors and widths.
    • Vertical vs Horizontal Bar Chart
      Create a vertical bar chart with student names and marks.
      Then, create the same chart as a horizontal bar chart using plt.barh().
    • Pie Chart of Activities
      Create a pie chart showing your daily routine: Sleep, Study, Play, Eat
      Add percentage labels and use the explode parameter for fun effect.
    • Bar Plot with Edge Color
      Reuse a bar plot and make the bars green with black edges using edgecolor='black'.
    • Line Plot with Annotations
      Create a simple line plot and add a text label on one of the points using plt.text().

💡 Need help? See the GitHub Page For AnswersGitHub.

Tip: Try running these codes in your Python editor or Google Colab.

Post a Comment

Previous Post Next Post

POST ADS1