Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas - Bar Plots



A bar plot is a graphical representation of categorical data using rectangular bars, where the length of each bar is proportional to the value it represents. Bar plots are commonly used to compare discrete categories. The bars can be displayed either vertically or horizontally −

  • Vertical bar plot: Categories are displayed along the x-axis, and the values are represented on the y-axis.

  • Horizontal bar plot: Categories are along the y-axis, and the values are represented on the x-axis.

In Pandas, theplot.bar() andplot.barh() methods allow you to create vertical and horizontal bar plots, respectively. In this tutorial, we will learn about how to use these Pandas methods for creating various types of bar plots, including stacked, grouped, bar plot customization, and more.

Bar Plots in Pandas

The Pandas library provides two efficient methods calledplot.bar() andplot.barh() for creating bar plots directly from Series or DataFrame objects. These methods internally use Matplotlib and return either amatplotlib.axes.Axes object or NumPy arraynp.ndarray of Axes whensubplots parameter is set toTrue.

Theplot.bar() method creates the vertical bar plots, whileplot.barh() creates horizontal bar plots.

Syntax

Following is the syntax of the plot.bar() Method −

DataFrame.plot.bar(x=None, y=None, **kwargs)

Following is the syntax of the plot.barh() Method −

DataFrame.plot.barh(x=None, y=None, **kwargs)

Where,

  • x: Specifies the column for the categorical values. If not specified, then the DataFrame index is used.

  • y: Specifies the column or index label for the y-axis. If not specified, all numerical columns are used.

  • color: Sets colors for bars. Accepts a single color, a sequence of colors, or a dictionary mapping columns to colors.

  • **kwargs: Additional arguments to customize the plot.

Creating a Vertical Bar Plot

You can use theDataFrame.plot.bar() method for creating the basic vertical bar plot. In this categories are displayed along the x-axis, while the heights of these bars along the y-axis represents the values.

Example

This example creates a simple vertical bar plot using theDataFrame.plot.bar() method.

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.rcParams["figure.figsize"] = [7, 4]# Create a DataFrame with sample datadf = pd.DataFrame({'Category': ['A', 'B', 'C'], 'Values': [10, 30, 20]})# Vertical bar plotax = df.plot.bar(x='Category', y='Values')plt.title("Vertical Bar Plot")plt.show()

After executing the above code, we get the following output −

Vertical Bar Plot

Create a Horizontal Bar plot

To create a horizontal bar chart, we can useplot.barh() method. A horizontal bar plot flips the orientation of the bars, where y-axis displays the categories, and the heights of these bars along the x-axis represents the values.

Example

The following example demonstrates how to create a horizontal bar plot using theDataFrame.plot.barh() method.

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.rcParams["figure.figsize"] = [7, 4]# Create a DataFrame with sample datadf = pd.DataFrame({'Category': ['A', 'B', 'C'], 'Values': [10, 30, 20]})# Horizontal bar plotax = df.plot.barh(x='Category', y='Values')plt.title("Horizontal Bar Plot")plt.show()

Following is the output of the above code −

Horizontal Bar Plot Example

Plotting a Stacked Bar plot

Stacked bar plots display multiple numerical columns in a single bar, showing cumulative values for each category. To create stacked bars, set theStacked parameter toTrue.

Example: Plotting a Stacked Vertical Bar plot

This example creates a stacked bar plot by setting thestacked parameter toTrue.

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.rcParams["figure.figsize"] = [7, 4]# Sample DataFramedata = {'Category': ['Col1', 'Col2', 'Col3'], 'Value1': [10, 15, 20], 'Value2': [5, 10, 15]}df = pd.DataFrame(data)# Stacked bar plotax = df.plot.bar(x='Category', stacked=True)plt.title("Stacked Bar Plot")plt.show()

On executing the above code we will get the following output −

Stacked Bar Plot Example

Example: Plotting a Stacked Horizontal Bar plot

This example creates a stacked horizontal bar plot by adjusting thestacked parameter value of theplot.barh() method.

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.rcParams["figure.figsize"] = [7, 4]# Sample DataFramedata = {'Category': ['Col1', 'Col2', 'Col3'], 'Value1': [10, 15, 20], 'Value2': [5, 10, 15]}df = pd.DataFrame(data)# Stacked horizontal bar plotax = df.plot.barh(x='Category', stacked=True)plt.title("Stacked Horizontal Bar Plot")plt.show()

After executing the above code, we get the following output −

Stacked Horizontal Bar Plot

Customizing Bar Plots

You can customize bar plots using the various parameters available in Matplotlib, such as colors, colormaps, labels, gridlines, and more.

Example: Customizing Bar Colors

This example demonstrates using the Python dictionary object for mapping column names to colors customization.

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.rcParams["figure.figsize"] = [7, 4]# Sample DataFramedata = {'Category': ['Col1', 'Col2', 'Col3'], 'Value1': [10, 15, 20], 'Value2': [5, 10, 15]}df = pd.DataFrame(data)# Assign specific colors to columnsax = df.plot.bar(color={'Value1': 'green', 'Value2': 'black'})plt.title("Customizing Bar Colors")plt.show()

Following is the output of the above code −

Customizing Bar Colors

Example: Splitting Bar Plot into Subplots

You can split multiple columns of a DataFrame into separate plots using thesubplots=True parameter. The following example demonstrates the same.

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.rcParams["figure.figsize"] = [7, 4]# Sample DataFramedata = {'Category': ['Col1', 'Col2', 'Col3'], 'Value1': [10, 15, 20], 'Value2': [5, 10, 15]}df = pd.DataFrame(data)# Subplots for each columnaxes = df.plot.bar(subplots=True, color=['cyan', 'magenta'])plt.show()

On executing the above code we will get the following output −

Splitting Bar Plot into Subplots
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp