pandas.plot() is built on the top of Matplotlib engine. From the Dataframe or the Series we can create plots directly. The main feature of using this method is that it handles the indexing accordingly.
Syntax: DataFrame.plot(kind=<plot_type>, x=<x_column>, y=<y_column>, **kwargs)
Parameters:
- kind: Specifies the type of plot (e.g., 'line', 'bar', 'hist').
- x: (optional) The column to be plotted on the x-axis.
- y: (optional) The column to be plotted on the y-axis.
- **kwargs: Other parameters to customize the plot (e.g., title, labels, etc.).
Plotting Line Plots using pandas.plot()
We can create line plots using plot method by defining the category as line. Let us consider a sample dataframe. Here we will pass one column in the X-axis and two columns in the Y-axis.
Python
import pandas as pd
# Create a sample dataset
data = {
"Month": ["Jan", "Feb", "Mar", "Apr"],
"Sales": [2500, 3000, 4000, 3500],
}
df = pd.DataFrame(data)
# Plot a line graph
df.plot(x="Month", y="Sales", kind="line", title="Monthly Sales", legend=True,color='red')
Output:
Using plot method and specifying the category in the kind parameter, we can create any type of graph.
In addition to line plots, the pandas.plot() method can also be used to visualize the following types of charts:
Creating Bar Plot with pandas.plot()
We can also create bar plot by just passing the categorical variable in the X-axis and numerical value in the Y-axis. Here we have a dataframe. Now we will create a vertical bar plot and a horizontal bar plot using kind as bar and also use the subplots.
Python
import pandas as pd
# Sample data
data = {
"Category": ["A", "B", "C", "D"],
"Values": [4, 7, 1, 8]
}
df = pd.DataFrame(data)
# Create subplots for vertical and horizontal bar plots
df.plot(x="Category", y="Values", kind="bar", subplots=True, layout=(2, 1), figsize=(12, 6), title="Vertical and Horizontal Bar Plots")
# Horizontal bar plot using kind='barh'
df.plot(x="Category", y="Values", kind="barh", subplots=True)
Output:
Visualizing Data Density with Histograms Using pandas.plot()
Histograms are basically used to visualize one- dimensional data. Using plot method we can create histograms as well. Let us illustrate the use of histogram using pandas.plot method.
Python
import pandas as pd
import numpy as np
# Sample data
data = {
"Scores": [65, 70, 85, 90, 95, 80]
}
df = pd.DataFrame(data)
# Plot a histogram
df.plot(y="Scores", kind="hist", bins=5, title="Histogram of Scores", legend=False, figsize=(8, 6))
Output:
Creating Box Plots for Data Visualization with pandas.plot()
We can create box plots to have a clear visualization and interpretation including outlier detection, interquartile ranges etc for each column in Pandas. By changing the kind to box, we can create box plots in just one line of code.
Python
import pandas as pd
# Sample data
data = {
"Category A": [7, 8, 5, 6, 9],
"Category B": [4, 3, 5, 7, 8]
}
df = pd.DataFrame(data)
# Box plot
df.plot(kind="box", title="Box Plot Example", figsize=(7, 6))
Output:
Creating Area Plots to Visualize Trends with pandas.plot()
Area plots can be used to highlight the trends or the patterns of the data over a certain timeline. In plot method, we can create area plots and stack one plot over the other. Let us consider an example.
Python
# Sample data
data = {
"Year": [2015, 2016, 2017, 2018, 2019],
"Sales": [200, 300, 400, 350, 500],
"Profit": [50, 80, 120, 100, 150]
}
df = pd.DataFrame(data)
# Area plot
df.plot(x="Year", kind="area", stacked=True, title="Area Plot Example", figsize=(8, 6))
Output:
Creating Pie charts to Visualize the Categories using pandas.plot()
Here, we can create pie charts using combination of plot method and set_index method. First we set the column as index and later on pass that index to the plot method and specify the category as pie.
Python
# Sample data
data = {
"Category": ["A", "B", "C", "D"],
"Values": [40, 35, 15, 10]
}
df = pd.DataFrame(data)
# Pie chart
df.set_index("Category").plot(kind="pie", y="Values", autopct="%1.1f%%", title="Pie Chart Example", figsize=(8, 6))
Output:
Can we integrate pandas.plot with Matplotlib?
Yes, we can integrate pandas.plot method with Matplotlib so that we can perform advanced customization. For instance, suppose we want to create subplots. By default, using plot method we can paste plots one below the other. But with the help of Matplotlib, we can insert the plots sideways so that we can do the analysis better.
Let us consider one sample example.
Here we have 3 columns. Now we want to create bar plot and scatter plot. With the help of Matplotlib we can specify the layout and use the pandas.plot method to create plots.
Python
import pandas as pd
import matplotlib.pyplot as plt
# Sample data
data = {
"Category": ["A", "B", "C", "D"],
"Values_1": [4, 7, 1, 8],
"Values_2": [5, 6, 2, 9]
}
df = pd.DataFrame(data)
# Create subplots: 1 row, 2 columns
fig, axes = plt.subplots(1, 2, figsize=(12, 6)) # 1 row, 2 columns
# First plot: Vertical bar plot
df.plot(x="Category", y="Values_1", kind="bar", ax=axes[0], title="Vertical Bar Plot")
axes[0].set_ylabel("Values")
# Second plot: Horizontal bar plot
df.plot(x="Values_1", y="Values_2", kind="scatter", ax=axes[1], title="Scatter Plot", color='black',s=200)
axes[1].set_xlabel("Values")
# Adjust layout and display
plt.tight_layout()
plt.show()
Output:
pandas.plot is a useful method as we can create customizable visualizations with less lines of code. As it is built on the top of Matplotlib, we can also combine this method with other libraries like Seaborn etc to get advanced visualizations.
Similar Reads
How to Use Python Pandas
to manipulate and analyze data efficientlyPandas is a Python toolbox for working with data collections. It includes functions for analyzing, cleaning, examining, and modifying data. In this article, we will see how we can use Python Pandas with the help of examples.What is Python Pandas?A Python lib
5 min read
How to Plot a Dataframe using Pandas
Pandas plotting is an interface to Matplotlib, that allows to generate high-quality plots directly from a DataFrame or Series. The .plot() method is the core function for plotting data in Pandas. Depending on the kind of plot we want to create, we can specify various parameters such as plot type (ki
8 min read
How to Learn Pandas ?
Pandas simplify complex data operations, allowing you to handle large datasets with ease, transform raw data into meaningful insights, and perform a wide range of data analysis tasks with minimal code. Whether you're new to programming or an experienced developer looking to enhance your data analysi
8 min read
Customizing Plot Labels in Pandas
Customizing plot labels in Pandas is an essential skill for data scientists and analysts who need to create clear and informative visualizations. Pandas, a powerful data manipulation library in Python, provides a convenient interface for creating plots with Matplotlib, a comprehensive plotting libra
5 min read
Pandas Introduction
Pandas is open-source Python library which is used for data manipulation and analysis. It consist of data structures and functions to perform efficient operations on data. It is well-suited for working with tabular data such as spreadsheets or SQL tables. It is used in data science because it works
3 min read
How to Install Pandas in Python?
Pandas in Python is a package that is written for data analysis and manipulation. Pandas offer various operations and data structures to perform numerical data manipulations and time series. Pandas is an open-source library that is built over Numpy libraries. Pandas library is known for its high pro
5 min read
Matplotlib Pyplot
Pyplot is a submodule of the Matplotlib library in python and beginner-friendly tool for creating visualizations providing a MATLAB-like interface, to generate plots with minimal code. How to Use Pyplot for Plotting?To use Pyplot we must first download the Matplotlib module. For this write the follo
2 min read
How to plot a Pandas Dataframe with Matplotlib?
We have a Pandas DataFrame and now we want to visualize it using Matplotlib for data visualization to understand trends, patterns and relationships in the data. In this article we will explore different ways to plot a Pandas DataFrame using Matplotlib's various charts. Before we start, ensure you ha
2 min read
Data Visualization with Pandas
Pandas allows to create various graphs directly from your data using built-in functions. This tutorial covers Pandas capabilities for visualizing data with line plots, area charts, bar plots, and more.Introducing Pandas for Data VisualizationPandas is a powerful open-source data analysis and manipul
5 min read
Area Line Plot
Area line plots are an effective tool in the data visualization toolbox for illustrating relationships and trends across time. They provide a comprehensive and visually captivating method of presenting numerical data by expertly combining the readability of line charts with the eye-catching attracti
6 min read