Home >Backend Development >Python Tutorial >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:
<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!