5 Best Ways to Create a Horizontal Bar Chart Using Python Pandas

πŸ’‘ Problem Formulation: You might have a dataset in Python Pandas and wish to visualize the frequency or occurrence of certain data categories. Specifically, you want to create a horizontal bar chart to represent the data clearly and aesthetically. Suppose your input is a Pandas DataFrame that consists of categories and their respective values. The desired output is a horizontal bar chart that precisely displays this information.

Method 1: Using DataFrame.plot.barh()

The DataFrame.plot.barh() method is a simple and quick way to create a horizontal bar chart from a Pandas DataFrame. This method is a wrapper around the matplotlib pyplot.barh() functions, providing convenience for users familiar with Pandas. It allows for customization of various aspects of the chart, such as color and size.

Here’s an example:

import pandas as pd
import matplotlib.pyplot as plt

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

# Set Categories as the index
df.set_index('Categories', inplace=True)

# Create the horizontal bar chart
df['Values'].plot.barh()

plt.show()

The output is a horizontal bar chart showing bars for category A, B, and C with the respective lengths according to their values in the DataFrame.

This code snippet imports Pandas and Matplotlib, creates a sample DataFrame, sets the ‘Categories’ column as the index, and calls plot.barh() on the ‘Values’ column to generate the horizontal bar chart. The chart is then displayed with plt.show().

Method 2: Using seaborn.barplot()

Seaborn is a statistical data visualization library in Python that simplifies creating many common visualizations, including horizontal bar charts. The seaborn.barplot() function provides greater style and color options out of the box and works well with DataFrames.

Here’s an example:

import pandas as pd
import seaborn as sns

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

# Create the horizontal bar chart
sns.barplot(x='Values', y='Categories', data=df)

sns.plt.show()

The output is a horizontal bar chart with categories on the y-axis and values on the x-axis, styled with Seaborn’s default theme.

This snippet sets up a DataFrame and passes it to Seaborn’s barplot() function, which automatically produces a horizontal bar chart (since the categories are assigned to the y-axis). The chart is then rendered using Seaborn’s enhanced visualization settings.

Method 3: Using matplotlib.pyplot.barh()

Matplotlib is a powerful plotting library for Python that provides a barh() function specifically for creating horizontal bar charts. This function gives finer control over the chart details and is suitable when custom visualizations are needed.

Here’s an example:

import pandas as pd
import matplotlib.pyplot as plt

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

# Create the horizontal bar chart
plt.barh(df['Categories'], df['Values'])

plt.show()

The output is a simple horizontal bar chart with categories as the y-axis and their respective values as the width of the bars.

This code creates a horizontal bar chart with the barh() function from Matplotlib, directly taking ‘Categories’ and ‘Values’ from the DataFrame and plotting them without additional customization.

Method 4: Using Plotly Express

Plotly Express provides an interactive chart creation experience with minimal code. It’s part of the Plotly library, which can create a wide range of interactive plots that are web-friendly. More complex than the other options, it is best when interactivity is needed.

Here’s an example:

import pandas as pd
import plotly.express as px

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

# Create the horizontal bar chart
fig = px.bar(df, x='Values', y='Categories', orientation='h')

fig.show()

The output is an interactive horizontal bar chart that can be hovered over for more detailed information on each bar segment.

This snippet utilizes Plotly Express to create an interactive horizontal bar chart. Here, orienting the bar chart horizontally is as simple as setting the orientation parameter to ‘h’. The resulting chart includes interactivity, such as tooltips on hover.

Bonus One-Liner Method 5: Direct Plotting with Pandas

For a quick and simple horizontal bar chart, Pandas integrates with Matplotlib to enable direct plotting from a Series or DataFrame with a single line of code.

Here’s an example:

pd.Series([10, 20, 30], index=['A', 'B', 'C']).plot.barh()

The output is a horizontal bar chart illustrating the three categories ‘A’, ‘B’, and ‘C’ with their corresponding values.

This one-liner takes advantage of Pandas’ built-in plotting capabilities where a Series is created with given values and index. The plot.barh() method is then immediately appended to generate the horizontal bar chart.

Summary/Discussion

  • Method 1: Pandas DataFrame.plot.barh(). Simple integration with Pandas. Limited customization compared to direct Matplotlib.
  • Method 2: Seaborn barplot(). Better default styles and integrated understanding of Pandas DataFrames. Requires additional library and understanding of Seaborn.
  • Method 3: Matplotlib.pyplot.barh(). Maximum flexibility and control. Potentially more complex and verbose code.
  • Method 4: Plotly Express. Provides interactivity and modern web-friendly charts. May include overhead due to interactivity features not always needed.
  • Bonus One-Liner Method 5: Direct plotting with Pandas Series.plot.barh(). Quick and concise for simple plots. Limited customization and not ideal for complex datasets.