条形图中的前 5 个值

Top 5 values in plotly bar chart

如何使用 Plotly 在条形图中仅显示前 5 个值

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()

没有内置的方法来执行此操作,因此您必须通过 pandas 来处理排序和子集化。从 px.data.gapminder 中获取示例数据,此类排序和子集化的示例可以是:

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

哪个会变成这个:

进入这个:

完整代码:

进口

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()

如果你愿意分享一个,我们可以仔细看看细节。