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 li
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 Plot Value Counts in Pandas
In this article, we'll learn how to plot value counts using provide, which can help us quickly understand the frequency distribution of values in a dataset. Table of Content Concepts Related to Plotting Value CountsSteps to Plot Value Counts in Pandas1. Install Required Libraries2. Import Required L
3 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 a powerful and open-source Python library. The Pandas library is used for data manipulation and analysis. Pandas consist of data structures and functions to perform efficient operations on data. Pandas is well-suited for working with tabular data, such as spreadsheets or SQL tables. To lea
3 min read
Data Processing with Pandas
Data Processing is an important part of any task that includes data-driven work. It helps us to provide meaningful insights from the data. As we know Python is a widely used programming language, and there are various libraries and tools available for data processing. In this article, we are going t
10 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
Python | Pandas Series.axes
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be un
2 min read
Pandas Step-by-Step Guide
Pandas is a powerful data manipulation and analysis library for Python. It provides data structures like series and dataframes to effectively easily clean, transform, and analyze large datasets and integrates seamlessly with other python libraries, such as numPy and matplotlib. It offers powerful fu
15 min read
Python | Pandas Series.data
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be un
2 min read