簡體   English   中英

plotly 條形圖中的前 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()

如果您願意分享您的數據樣本,我們可以仔細查看詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM