0

I have a dataframe created from a csv file. I created calculations to convert column values to percentages.

Then I converted the columns to lists and now I want to create a stacked bar chart using the lists, but I can't.

What is the best way forward?

def funcaoStackedBar(data,valor, colX, colStacked):

data[f'perc_{valor}'] = data.apply(lambda x: (x[f'{valor}'] / x[f'{valor}']/ data[f'{valor}'].sum())*100, axis = 1)
tps = data.pivot_table(values=f'perc_{valor}', index=colX, columns=colStacked, aggfunc='sum')

tps = tps.div(tps.sum(1), axis=0)
tps.plot(kind='bar', stacked=True, figsize=(20,10), title='Gráfico de Barras Empilhadas')
  • 1
    Can you show some of your code to see how far you got? I would reccomend `pandas` package for reading csvs and plotting. – erncyp Oct 14 '19 at 11:47
  • 1
    Possible duplicate of [How to plot a very simple bar chart (Python, Matplotlib) using input \*.txt file?](https://stackoverflow.com/questions/11617719/how-to-plot-a-very-simple-bar-chart-python-matplotlib-using-input-txt-file) – erncyp Oct 14 '19 at 11:49
  • Here is an [example](https://stackoverflow.com/a/58134775/8366805). – meTchaikovsky Oct 16 '19 at 02:13

1 Answers1

0

I'm not sure how your list looks like, but here's another solution for you to create a normalized/percentage stacked barchart from your dataframe, assuming you're calculating the percentage of each column, for each row.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Dummy dataframe
df = pd.DataFrame(data=[[50, 39, 30],
                        [100, 84, 300],
                        [23, 65, 13]],
                  columns=['A', 'B', 'C'])


# Compute the percentage
df = df.div(df.sum(axis=1), axis=0) * 100

# Plot a stacked barchart
ax = df.plot.bar(stacked=True)

# Place the legend
ax.legend(bbox_to_anchor=(1.1, 1.05))
plt.xticks(rotation=60)
plt.ylim(0, 100)
plt.title('Stacked Barchart')
plt.xlabel('Type')
plt.ylabel('Percentage of Type (%)')
plt.show()

Normalized stacked barchart

Alex Ramses
  • 538
  • 3
  • 19