Top 5 values in plotly bar chart

Question:

How to show only the top 5 values in bar chart using Plotly

import plotly.graph_objects as go

fig = go.Figure([go.Bar(x=col, y=res, text=res)])
fig.update_layout(plot_bgcolor = "white",
                    font = dict(color = "#909497"),
                    title = dict(text = "Ratio of Buyers vs Non Buyers (Master Data(MIN))"),
                    xaxis = dict(title = "Features", linecolor = "#909497"), #tick prefix is the html code for Rupee
                    yaxis = dict(title = "Ratio", tickformat = ",", linecolor = "#909497",)) #apply our custom category order
fig.update_layout(barmode='stack', xaxis={'categoryorder':'total descending'})
fig.show()
Asked By: Siddarth G

||

Answers:

There’s no buillt-in way to do this, so you’ll have to handle sorting and subsetting through pandas for example. Taking sample data from px.data.gapminder, an example of such sorting and subsetting could be:

dfg = df.groupby(['name']).size().to_frame().sort_values([0], ascending = False).head(5).reset_index()

Which will turn this:

enter image description here

Into this:

enter image description here

Complete code:

imports

import pandas as pd
import plotly.express as px
import random

# data sample
gapminder = list(set(px.data.gapminder()['country']))[1:20]
names = random.choices(gapminder, k=100)

# data munging
df = pd.DataFrame({'name':names})
# dfg = df.groupby(['name']).size().to_frame().sort_values([0], ascending = False).reset_index()

dfg = df.groupby(['name']).size().to_frame().sort_values([0], ascending = False).head(5).reset_index()
dfg.columns = ['name', 'count']

# plotly
fig = px.bar(dfg, x='name', y = 'count')
fig.layout.yaxis.title.text = 'count'
fig.show()

If you’re willing to share a sample of your data, we can take a closer look at the details.

Answered By: vestland
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.