You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Plotly直方图x轴标签为区间范围并添加趋势线

实现方案

你要的两个需求可以通过预分箱生成自定义标签 + 叠加折线轨迹实现,完整可运行代码如下:

import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import pandas as pd

df = px.data.tips()
# 替换为你自己的数据源列
target_data = df['total_bill']
# 自定义区间步长,可根据需求修改
bin_step = 10

# 生成自定义区间及对应标签
bin_min = int(np.floor(target_data.min()))
bin_max = int(np.ceil(target_data.max()))
bins = list(range(bin_min, bin_max + bin_step, bin_step))
bin_labels = [f"[{bins[i]}-{bins[i+1]-1}]" for i in range(len(bins)-1)]

# 对数据做分箱映射,统计每个区间的频数
df['value_bin'] = pd.cut(target_data, bins=bins, labels=bin_labels, include_lowest=True)
bin_count = df['value_bin'].value_counts().sort_index()

# 绘制直方图
fig = px.histogram(df, x='value_bin', color_discrete_sequence=['purple'])
# 叠加趋势线
fig.add_trace(go.Scatter(
    x = bin_count.index,
    y = bin_count.values,
    mode = 'lines+markers',
    line = dict(color='red', width=2),
    name = '频数趋势'
))

# 样式调整
fig.update_layout(
    bargap = 0.01,
    xaxis_title = '数值区间',
    yaxis_title = '频数'
)
fig.show()

关键说明:

  • 你可以修改bin_step的数值调整区间大小,比如设为5就会生成[0-4]、[5-9]这类区间
  • 趋势线的颜色、粗细可以通过line参数的配置自定义
  • 预分箱的方式兼容性更强,同时适配整数、非整数类型的数据源

内容的提问来源于stack exchange,提问作者illhahb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:09:03