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