Home  >  Article  >  Backend Development  >  How to Create a Stacked Bar Chart in Python with Differently Structured Data?

How to Create a Stacked Bar Chart in Python with Differently Structured Data?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-21 19:38:29861browse

How to Create a Stacked Bar Chart in Python with Differently Structured Data?

Plotting a Stacked Bar Chart in Python

Problem:

Creating a stacked bar chart with data structured differently from an example spreadsheet.

The DataFrame contains site names and counts of either "ABUSE" or "NFF" incidents. The goal is to create a bar chart with stacked bars representing the number of incidents by site name for both types of incidents. The data is given in a CSV file.

Solution:

To create a stacked bar chart, you can use the stacked=True option in the plot function. The key is to structure your data appropriately. Here's a solution:

  1. Group the data by both 'Site Name' and 'Abuse/NFF'.
  2. Use the count method to count the occurrences within each group.
  3. Use the unstack method to create a multi-index DataFrame with the site names as the index and the incident types as the columns.
  4. Use the fillna method to fill any missing values with 0.
  5. Finally, call the plot method with the stacked=True option to create the stacked bar chart.
<code class="python"># Import necessary libraries
import pandas as pd
import matplotlib.pyplot as plt

# Read CSV file
df = pd.read_csv('data.csv')

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

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

This should generate a stacked bar chart with the desired format.

The above is the detailed content of How to Create a Stacked Bar Chart in Python with Differently Structured Data?. 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