Home >Backend Development >Python Tutorial >How to Plot a Stacked Bar Chart with Pandas When Data is Separated into Multiple Columns?

How to Plot a Stacked Bar Chart with Pandas When Data is Separated into Multiple Columns?

Susan Sarandon
Susan SarandonOriginal
2024-10-21 19:40:031049browse

How to Plot a Stacked Bar Chart with Pandas When Data is Separated into Multiple Columns?

Plotting a Stacked Bar Chart with Pandas

In Python, we can use Pandas and Matplotlib to create stacked bar charts. A common challenge is structuring the data for the chart.

For instance, consider the task of creating a stacked bar graph with data separated into multiple columns. The given example shows a spreadsheet with site names and abuse/NFF counts. To plot this data:

  1. Import Libraries: Begin by importing Pandas and Matplotlib.
  2. Create Data Frame: Create a Pandas DataFrame from your CSV data.
  3. Restructure Data: Use the groupby() and unstack() functions to restructure the data into a format suitable for the bar chart. In the example, the data is grouped by Site Name and Abuse/NFF, and then the counts are unstacked.
  4. Create Bar Chart: Use the plot() function with the kind='bar' and stacked=True arguments to create the stacked bar chart.
  5. Label Axes: Remember to label the x and y axes.

Example Code:

import pandas as pd
import matplotlib.pyplot as plt

# Create DataFrame from CSV data
df = pd.read_csv('data.csv')

# Restructure data
df2 = df.groupby(['Site Name', 'Abuse/NFF'])['Site Name'].count().unstack('Abuse/NFF').fillna(0)

# Create bar chart
df2[['abuse', 'nff']].plot(kind='bar', stacked=True)
plt.xlabel('Site Name')
plt.ylabel('Count')
plt.title('Stacked Bar Chart of Abuse and NFF')
plt.show()

The above is the detailed content of How to Plot a Stacked Bar Chart with Pandas When Data is Separated into Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn