Open In App

pandas.plot() method

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

line

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:

Screenshot-2024-12-08-201107

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:

hist

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:

file

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:

area

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:

pie

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:

file

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.


Next Article

Similar Reads