Day 14: Matplotlib for Data Visualization

Topics to Cover:

  • Introduction to Matplotlib
  • Basic Plotting

Introduction to Matplotlib

Matplotlib is a popular plotting library for Python. It provides an object-oriented API for embedding plots into applications.

Installing Matplotlib:
If you don’t have Matplotlib installed, you can install it using pip:

pip install matplotlib

Basic Plotting with Matplotlib

Matplotlib allows you to create various types of plots, such as line plots and scatter plots.

Creating a Simple Line Plot:

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Creating a line plot
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()

Creating a Simple Scatter Plot:

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Creating a scatter plot
plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Scatter Plot')
plt.show()

Visualizing Data from a Pandas DataFrame

Matplotlib works seamlessly with Pandas DataFrames, making it easy to visualize data directly from a DataFrame.

Example: Visualizing Data from a DataFrame:

import pandas as pd
import matplotlib.pyplot as plt

# Sample data
data = {
    'Year': [2010, 2011, 2012, 2013, 2014],
    'Sales': [100, 120, 140, 160, 180]
}

df = pd.DataFrame(data)

# Creating a line plot from DataFrame
plt.plot(df['Year'], df['Sales'])
plt.xlabel('Year')
plt.ylabel('Sales')
plt.title('Yearly Sales')
plt.show()

Potential Problems to Solve

Problem 1: Create a Line Plot and Scatter Plot

Task: Create a line plot and scatter plot using Matplotlib.

Solution:

import matplotlib.pyplot as plt

# Line plot
x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]

plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot of y = x^2')
plt.show()

# Scatter plot
plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot of y = x^2')
plt.show()

Problem 2: Visualize Data from a Pandas DataFrame

Task: Visualize data from a Pandas DataFrame.

Solution:

import pandas as pd
import matplotlib.pyplot as plt

# Sample data
data = {
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    'Revenue': [200, 220, 250, 270, 300]
}

df = pd.DataFrame(data)

# Creating a bar plot from DataFrame
plt.bar(df['Month'], df['Revenue'])
plt.xlabel('Month')
plt.ylabel('Revenue')
plt.title('Monthly Revenue')
plt.show()

Conclusion

Matplotlib is a versatile tool for creating a wide range of plots and visualizations in Python. By mastering the basics, you can effectively visualize and communicate data insights.


Stay tuned for Day 15 of the python4ai 30-day series, where we will continue exploring advanced Python topics to enhance our programming skills!

Team
Team

This account on Doubtly.in is managed by the core team of Doubtly.

Articles: 384