Sunday 14 April 2024

Introduction to Matplotlib library

Matplotlib - Python's library for data visualization

What is Matplotlib?

Matplotlib is a fundamental Python library for data visualization. It is a powerful and versatile open-source library in Python that allows you to create various static, animated, and interactive visualizations. It excels at generating a wide range of plot types, including:

  • Line plots
  • Bar charts
  • Scatter plots
  • Histograms
  • Pie charts
  • 3D plots
  • And many more

Matplotlib is a cornerstone for data analysis and storytelling in Python. By visualizing your data, you can gain deeper insights, identify trends and patterns, and communicate findings effectively.


Getting Started with Matplotlib - Installation:

If you don't have Matplotlib installed, use pip, and import the matplotlib.pyplot submodule.
 

pip install matplotlib
import matplotlib.pyplot as plt

Example: A Line Plot using Matplotlib

This example creates a line plot showing temperature variations over time:


# Sample data (replace with your actual data)
days = [1, 2, 3, 4, 5]
temperatures = [20, 22, 25, 23, 21]

# Create the plot
plt.plot(days, temperatures)

# Add labels and title
plt.xlabel("Days")
plt.ylabel("Temperature (°C)")
plt.title("Temperature Variation Over 5 Days")

# Display the plot
plt.show()

Output of the code

Line Plot
Figure: Line Plot


Example - Bar Chart using Matplotlib: 

Following example creates a bar chart comparing sales figures for different products.

# Sample data (replace with your actual data)
products = ["Product A", "Product B", "Product C"]
sales = [100, 150, 80]

# Create the bar chart
plt.bar(products, sales)

# Add labels and title
plt.xlabel("Products")
plt.ylabel("Sales")
plt.title("Product Sales Comparison")

# Display the plot
plt.show()


Output of the code


Figure: Bar Chart using Matplotlib

Example of Scatter Plot: 

Following example creates a scatter plot to visualize the relationship between weight and height:

# Sample data (replace with your actual data)
weights = [60, 70, 80, 55, 65]
heights = [170, 180, 175, 165, 172]

# Create the scatter plot
plt.scatter(weights, heights)

# Add labels and title
plt.xlabel("Weight (kg)")
plt.ylabel("Height (cm)")
plt.title("Weight vs. Height")

# Display the plot
plt.show()

Output of the code

Figure: Scatter Plot

Remember to replace the sample data in these examples with your actual data to create meaningful visualizations.

Customization and Beyond

Matplotlib offers extensive customization capabilities. You can fine-tune plot elements like:

  • Line styles
  • Marker shapes
  • Color schemes
  • Grid lines
  • Legend placement
  • Font sizes

Explore the official Matplotlib documentation.