![](/img/trans.png)
[英]Plotly: How to display the total sum of the values at top of a stacked bar chart along with the individual bar values?
[英]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.