A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python_pandas/python_pandas_bar_plots.htm below:

Python Pandas - Bar Plots

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 −

In Pandas, the plot.bar() and plot.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 called plot.bar() and plot.barh() for creating bar plots directly from Series or DataFrame objects. These methods internally use Matplotlib and return either a matplotlib.axes.Axes object or NumPy array np.ndarray of Axes when subplots parameter is set to True.

The plot.bar() method creates the vertical bar plots, while plot.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,

Creating a Vertical Bar Plot

You can use the DataFrame.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 the DataFrame.plot.bar() method.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7, 4]

# Create a DataFrame with sample data
df = pd.DataFrame({'Category': ['A', 'B', 'C'], 'Values': [10, 30, 20]})

# Vertical bar plot
ax = df.plot.bar(x='Category', y='Values')

plt.title("Vertical Bar Plot")
plt.show()

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

Create a Horizontal Bar plot

To create a horizontal bar chart, we can use plot.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 the DataFrame.plot.barh() method.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7, 4]

# Create a DataFrame with sample data
df = pd.DataFrame({'Category': ['A', 'B', 'C'], 'Values': [10, 30, 20]})

# Horizontal bar plot
ax = df.plot.barh(x='Category', y='Values')

plt.title("Horizontal Bar Plot")
plt.show()

Following is the output of the above code −

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 the Stacked parameter to True.

Example: Plotting a Stacked Vertical Bar plot

This example creates a stacked bar plot by setting the stacked parameter to True.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7, 4]

# Sample DataFrame
data = {'Category': ['Col1', 'Col2', 'Col3'], 'Value1': [10, 15, 20], 'Value2': [5, 10, 15]}
df = pd.DataFrame(data)

# Stacked bar plot
ax = 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 −

Example: Plotting a Stacked Horizontal Bar plot

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

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7, 4]

# Sample DataFrame
data = {'Category': ['Col1', 'Col2', 'Col3'], 'Value1': [10, 15, 20], 'Value2': [5, 10, 15]}
df = pd.DataFrame(data)

# Stacked horizontal bar plot
ax = 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 −

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 pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7, 4]

# Sample DataFrame
data = {'Category': ['Col1', 'Col2', 'Col3'], 'Value1': [10, 15, 20], 'Value2': [5, 10, 15]}
df = pd.DataFrame(data)

# Assign specific colors to columns
ax = df.plot.bar(color={'Value1': 'green', 'Value2': 'black'})

plt.title("Customizing Bar Colors")
plt.show()

Following is the output of the above code −

Example: Splitting Bar Plot into Subplots

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

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7, 4]

# Sample DataFrame
data = {'Category': ['Col1', 'Col2', 'Col3'], 'Value1': [10, 15, 20], 'Value2': [5, 10, 15]}
df = pd.DataFrame(data)

# Subplots for each column
axes = df.plot.bar(subplots=True, color=['cyan', 'magenta'])
plt.show()

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4