How to Create a Stacked Bar Chart in Pandas with Grouped Data?

Mary-Kate Olsen
Release: 2024-10-21 19:37:03
Original
129 people have browsed it

How to Create a Stacked Bar Chart in Pandas with Grouped Data?

Plotting a Stacked Bar Chart Using Pandas

Question:

How can I create a stacked bar chart with pandas, similar to the image provided? My current dataframe consists of separate columns for "Site Name" and "Abuse/NFF" counts, and I'm unable to arrange the data or generate the stacked bar chart.

Solution:

1. Data Preparation:

Create a new dataframe by grouping the data by both "Site Name" and "Abuse/NFF" and counting the occurrences of each combination.

2. Stacking the Data:

Use the .unstack() method to create a stacked dataframe, with "Site Name" as the index and "Abuse/NFF" as the columns.

3. Filling Missing Values:

Handle any missing values by filling them with zeros using the .fillna(0) method.

4. Plotting the Bar Chart:

Use the .plot() method with the kind parameter set to 'bar' and the stacked parameter set to True to generate a stacked bar chart.

Python Code:

<code class="python">import pandas as pd
import matplotlib.pyplot as plt

# Create a dataframe from the CSV file
df = pd.read_csv("data.csv")

# Group by "Site Name" and "Abuse/NFF" and count occurrences
df2 = df.groupby(['Site Name', 'Abuse/NFF'])['Site Name'].count().unstack('Abuse/NFF').fillna(0)

# Plot the stacked bar chart
df2[['abuse','nff']].plot(kind='bar', stacked=True)
plt.show()</code>
Copy after login

Output:

The resulting plot will resemble the image provided in the original question, displaying the stacked counts of "Abuse" and "NFF" for each "Site Name."

The above is the detailed content of How to Create a Stacked Bar Chart in Pandas with Grouped Data?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!