如何使用Plotly在条形图中仅展示排名前5的数值
Plotly 条形图仅展示数值最高前5个类别的实现方法
核心实现逻辑很简单:先对类别和对应的数值做排序,仅截取前5组数据传入绘图对象即可,数据预处理阶段完成过滤比依赖Plotly参数做截断更灵活可控。
基于你提供的参考代码修改后的完整实现
import plotly.graph_objects as go # --------------------------新增的预处理逻辑开始-------------------------- # 将类别col和对应数值res配对,按数值降序排序后取前5 sorted_pairs = sorted(zip(res, col), key=lambda item: item[0], reverse=True)[:5] # 解包得到前5的类别和对应数值 top5_res = [pair[0] for pair in sorted_pairs] top5_col = [pair[1] for pair in sorted_pairs] # --------------------------新增的预处理逻辑结束-------------------------- # 绘图时仅传入前5的数据即可 fig = go.Figure([go.Bar(x=top5_col, y=top5_res, text=top5_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"), yaxis = dict(title = "Ratio", tickformat = ",", linecolor = "#909497")) # 这里的categoryorder参数可以保留也可以删除,预处理阶段已经做好排序 fig.update_layout(barmode='stack', xaxis={'categoryorder':'total descending'}) fig.show()
其他说明
- 如果你的原始数据存储在Pandas DataFrame中,可以直接用
nlargest方法更便捷的取前5数据,示例如下:# 假设df是你的原始数据表,feature列存类别,ratio列存对应数值 top5_df = df.nlargest(5, 'ratio') # 绘图时x、y分别传入top5_df['feature']、top5_df['ratio']即可 - 若需要调整展示的条目数量,直接修改切片参数
[:5]即可,比如要展示前10个就改为[:10]
内容的提问来源于stack exchange,提问作者Siddarth G
相关产品推荐
相关产品推荐

