Home  >  Article  >  Backend Development  >  How to Create a Stacked Bar Chart with Pandas Using Grouped Data

How to Create a Stacked Bar Chart with Pandas Using Grouped Data

Patricia Arquette
Patricia ArquetteOriginal
2024-10-21 19:35:29651browse

How to Create a Stacked Bar Chart with Pandas Using Grouped Data

Creating a Stacked Bar Chart with Pandas

To create a stacked bar chart with pandas, you need to have your data in a DataFrame with one column for the x-axis labels and one column for each series in the bar chart. In this case, the x-axis labels are the 'Site Name' and the series are 'Abuse' and 'NFF'.

One way to create this DataFrame is to use the pandas' groupby() and unstack() methods. The 'groupby() method groups the data by the 'Site Name' and the Abuse/NFF' columns, and the unstack()` method converts the grouped data into a DataFrame with the 'Site Name' as the index and the 'Abuse' and 'NFF' columns as the columns.

<code class="python">test5 = faultdf.groupby(['Site Name', 'Abuse/NFF'])['Site Name'].count().unstack('Abuse/NFF').fillna(0)</code>

Once you have the DataFrame, you can create the stacked bar chart using the plot() method with the kind='bar' and stacked parameters set to True.

<code class="python">test5.plot(kind='bar', stacked=True)</code>

The resulting plot will be a stacked bar chart with the 'Site Name' on the x-axis and the 'Abuse' and 'NFF' columns as the stacks.

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

df2 = df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF').fillna(0)
df2[['abuse','nff']].plot(kind='bar', stacked=True)</code>

The above is the detailed content of How to Create a Stacked Bar Chart with Pandas Using Grouped 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