Pandas Plotting

Introduction

Pandas Plotting allows you to create charts and graphs directly from a DataFrame or Series. It uses the plot() method to visualize data and make comparisons easier. You can create line charts, bar charts, histograms, scatter plots, and other types of graphs for data analysis.

What Is Pandas Plotting?

Pandas Plotting is a feature that helps you represent numerical data visually.

Instead of reading large tables of numbers, you can use charts to understand patterns, trends, and comparisons.

For example:

  • A line chart can show monthly sales trends.
  • A bar chart can compare product sales.
  • A histogram can show the distribution of student marks.
  • A scatter plot can show the relationship between two numerical columns.

Pandas uses the plot() method to create charts. It uses Matplotlib in the background, so Matplotlib must also be installed.

Install Matplotlib:

pip install matplotlib

Import Pandas and Matplotlib:

import pandas as pd
import matplotlib.pyplot as plt

Creating a Line Plot

A line plot connects data points with lines. It is useful for showing changes over time.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Sales": [10000, 15000, 12000, 18000, 22000]
}

df = pd.DataFrame(data)

df.plot(x="Month", y="Sales", kind="line")

plt.show()

Explanation:

  • x="Month" displays months on the horizontal axis.
  • y="Sales" displays sales values on the vertical axis.
  • kind="line" creates a line chart.
  • plt.show() displays the chart.

Creating a Bar Plot

A bar plot uses rectangular bars to compare values between different categories.

It is useful for comparing product sales, department performance, or monthly revenue.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Product": ["Laptop", "Mobile", "Tablet", "Printer"],
    "Sales": [50000, 75000, 30000, 25000]
}

df = pd.DataFrame(data)

df.plot(x="Product", y="Sales", kind="bar")

plt.show()

Explanation:

  • x="Product" displays product names.
  • y="Sales" displays sales values.
  • kind="bar" creates a vertical bar chart.
  • plt.show() displays the chart.

Creating a Horizontal Bar Plot

A horizontal bar plot displays bars from left to right. It is useful when category names are long or when you want to compare categories vertically.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Department": ["Sales", "HR", "IT", "Marketing"],
    "Employees": [25, 10, 30, 20]
}

df = pd.DataFrame(data)

df.plot(x="Department", y="Employees", kind="barh")

plt.show()

Explanation:

  • x="Department" displays department names.
  • y="Employees" displays employee counts.
  • kind="barh" creates a horizontal bar chart.

Creating a Histogram

A histogram shows how numerical values are distributed across different ranges.

For example, you can use a histogram to understand how students’ marks are distributed.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Marks": [
        25, 35, 40, 42, 45,
        48, 50, 52, 55, 58,
        60, 62, 65, 68, 70,
        72, 75, 78, 80, 85,
        88, 90, 92, 95, 98
    ]
}

df = pd.DataFrame(data)

df["Marks"].plot(kind="hist", bins=5, edgecolor="black")

plt.title("Student Marks Distribution")
plt.xlabel("Marks")
plt.ylabel("Number of Students")

plt.show()

Explanation:

  • df["Marks"] selects the Marks column.
  • kind="hist" creates a histogram.
  • bins=5 divides the values into five groups.
  • plt.show() displays the histogram.

Creating a Scatter Plot

A scatter plot displays individual points to show the relationship between two numerical columns.

It is useful for analyzing relationships between sales and advertising expenses, study hours and marks, or price and demand.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Study_Hours": [1, 2, 3, 4, 5],
    "Marks": [35, 45, 55, 70, 85]
}

df = pd.DataFrame(data)

df.plot(
    x="Study_Hours",
    y="Marks",
    kind="scatter"
)

plt.show()

Explanation:

  • x="Study_Hours" displays study hours on the horizontal axis.
  • y="Marks" displays marks on the vertical axis.
  • kind="scatter" creates a scatter plot.
  • Each point represents one student’s study hours and marks.

Creating a Box Plot

A box plot helps you understand the distribution of numerical data. It displays the median, quartiles, and potential outliers.

It is useful for comparing salary ranges, student marks, and product prices.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Salary": [20000, 25000, 28000, 30000, 35000,
               40000, 45000, 50000, 55000, 100000]
}

df = pd.DataFrame(data)

df.plot(y="Salary", kind="box")

plt.show()

Explanation:

  • y="Salary" selects the Salary column.
  • kind="box" creates a box plot.
  • The box shows the middle portion of the data.
  • The line inside the box represents the median.
  • Individual points outside the whiskers may indicate potential outliers.

Creating a Pie Chart

A pie chart represents values as slices of a circle. It helps compare how different categories contribute to a total.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Department": ["Sales", "HR", "IT", "Marketing"],
    "Employees": [25, 10, 30, 15]
}

df = pd.DataFrame(data)

df.plot(
    y="Employees",
    labels=df["Department"],
    kind="pie",
    autopct="%1.1f%%"
)

plt.show()

Explanation:

  • y="Employees" selects the employee values.
  • labels=df["Department"] assigns department names to the slices.
  • kind="pie" creates a pie chart.
  • autopct="%1.1f%%" displays percentages on the chart.

Adding a Chart Title and Axis Labels

You can customize your charts by adding a title and labels to the horizontal and vertical axes.

This makes charts easier to understand.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Revenue": [10000, 15000, 12000, 18000, 22000]
}

df = pd.DataFrame(data)

df.plot(
    x="Month",
    y="Revenue",
    kind="line",
    title="Monthly Revenue"
)

plt.xlabel("Month")
plt.ylabel("Revenue")

plt.show()

Explanation:

  • title="Monthly Revenue" adds a chart title.
  • plt.xlabel("Month") adds a horizontal axis label.
  • plt.ylabel("Revenue") adds a vertical axis label.
  • plt.show() displays the customized chart.

Saving a Pandas Plot

You can save a chart as an image file using Matplotlib’s savefig() method.

This is useful when you want to use charts in reports, presentations, or websites.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Product": ["Laptop", "Mobile", "Tablet"],
    "Sales": [50000, 75000, 30000]
}

df = pd.DataFrame(data)

df.plot(x="Product", y="Sales", kind="bar")

plt.title("Product Sales")

plt.savefig("product_sales.png")

plt.show()

Explanation:

  • plt.savefig("product_sales.png") saves the chart as a PNG image.
  • The image is saved in the current working directory unless you provide another file path.
  • plt.show() displays the chart.

Types of Plots Available in Pandas

Pandas supports several chart types through the kind parameter.

Plot TypeDescriptionParameter
Line PlotShows changes and trendsline
Bar PlotCompares categoriesbar
Horizontal Bar PlotCompares categories horizontallybarh
HistogramShows data distributionhist
Scatter PlotShows relationships between two numerical columnsscatter
Box PlotShows data distribution and potential outliersbox
Pie ChartShows proportions of a totalpie
Area PlotShows trends with filled areasarea
Hexbin PlotShows the concentration of pointshexbin
Density PlotShows an estimated distributiondensity

Student Task

Create a Pandas DataFrame using the following sales data:

MonthLaptopMobileTablet
Jan203515
Feb254020
Mar304525
Apr355030
May405535

Complete these tasks:

  1. Create a DataFrame using the given data.
  2. Create a line plot for Laptop sales.
  3. Create a bar plot for Mobile sales.
  4. Create a horizontal bar plot for Tablet sales.
  5. Create a histogram using the Laptop column.
  6. Create a scatter plot using Laptop and Mobile columns.
  7. Add a title to one of your charts.
  8. Save one chart as sales_report.png.

Key Takeaways

  • Pandas uses the plot() method to create charts.
  • Matplotlib is used by Pandas for plotting.
  • kind="line" creates a line chart.
  • kind="bar" creates a vertical bar chart.
  • kind="barh" creates a horizontal bar chart.
  • kind="hist" creates a histogram.
  • kind="scatter" creates a scatter plot.
  • kind="box" creates a box plot.
  • kind="pie" creates a pie chart.
  • plt.savefig() saves a chart as an image.

Frequently Asked Questions (FAQs)

1. What Is Pandas Plotting in Python?

Pandas Plotting is a feature that allows users to create visual representations of data directly from Pandas Series and DataFrames. It helps display data patterns, trends, and comparisons using different types of charts and graphs.

2. What Is the Use of Pandas plot() Function?

The Pandas plot() function is used to create charts and graphs from DataFrame and Series data. It supports different plot types, including line, bar, histogram, scatter, and pie charts.

3. How to Create a Chart Using Pandas plot()?

You can create a chart using the Pandas plot() function by selecting a DataFrame column and specifying the chart type.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "Month": ["Jan", "Feb", "Mar"],
    "Sales": [12000, 15000, 18000]
})

df.plot(x="Month", y="Sales", kind="bar")

plt.show()

4. What Are the Different Types of Pandas Charts?

Pandas Charts include several types of visualizations, such as:

  • Line Chart
  • Bar Chart
  • Histogram
  • Scatter Plot
  • Pie Chart
  • Box Plot
  • Area Chart

These charts help users understand and compare datasets visually.

5. How to Perform Plotting in Pandas Using a DataFrame?

You can perform Plotting in Pandas by calling the plot() function on a DataFrame. You can specify columns, chart types, titles, labels, and other customization options to create meaningful visualizations.

6. Can We Create Pandas Graphs Without Using Matplotlib Directly?

Yes, you can create Pandas Graphs using the built-in plot() function without directly writing Matplotlib plotting commands. However, Pandas uses Matplotlib as its default plotting backend, so Matplotlib is required for standard plotting.

7. Which Library Is Required for Pandas Plotting?

Matplotlib is the default visualization library used by Pandas for Pandas Plotting. You can install it using the following command:

pip install matplotlib

8. Why Is Pandas Plotting Important in Data Analysis?

Pandas Plotting is important because it converts numerical and categorical data into visual charts. It helps data analysts identify trends, patterns, comparisons, and relationships that may be difficult to understand from raw data.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top