Matplotlib sorting using index as bar denominator

Asked

Viewed 69 times

3

I am at an impasse and cannot find a solution. I wish to generate a Bar Plot from a dataframe that is reordered in descending order. I would like the bar name to be the index (0 to 5) When I plot my Plot, it does not appear in descending order. How can I change the order of the bars?

Operations I’ve already tried:

import pandas as pd
import matplotlib.pyplot as plt 
plt.style.use('seaborn')
des = ['0. item A', '1. item B', '2. item C', '3. item D','4. item E','5. item F']
total = [100,75,5,30,3,5]

df = pd.DataFrame({'des': des,
                   'total':total}) 
df = df.sort_values(by=['total'], ascending=False)

df

inserir a descrição da imagem aqui

# Solução 1
xs = df.index
ys = df['total']

plt.bar(xs, ys, color='#DDA63A')

inserir a descrição da imagem aqui

# Solução 2:
plt.bar('index', 'total', color='#DDA63A', data=df)

inserir a descrição da imagem aqui

#Solução 3
plt.bar(df.index, df.total, color='#DDA63A', data=df)

inserir a descrição da imagem aqui

  • Hello, replacing only this line I have error 'Dataframe' Object has in attribute 'Sorted'

3 answers

1

  • I would like to use a solution with Matplotlib

1

One of the ways you can get the desired result is:

import matplotlib.pyplot as plt
plt.style.use('seaborn')
des = ['0. item A', '1. item B', '2. item C', '3. item D','4. item E','5. item F']
total = [100,75,5,30,3,5]

df = pd.DataFrame({'des': des,
                   'total':total})
df = df.sort_values(by=['total'], ascending=False)

xs = df.index
ys = df['total']

plt.bar(sorted(xs), ys, color='#DDA63A')
plt.show()

Note that the only change made was in the penultimate line reordering the variable Xs with the function Sorted().

inserir a descrição da imagem aqui

  • This answer worked with the example I created to post here but it didn’t work with my original graphic, it generates Typeerror: 'Dataframe' Object is not callable

0


Convert the index to a string list, it is a way to circumvent the captive matplotlib ordering.

`xs = df.index.map(str)
 ys = df['total']
 plt.bar(xs, ys, color='#DDA63A')`

inserir a descrição da imagem aqui

  • perfect! It was just what I needed! Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.