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

Plotly组合图表问题:柱状图异常合并Time与Volume值显示

Plotly K线+柱状图组合图:柱状图异常合并Time与Volume值的解决方案

问题本质

你的柱状图之所以显示(10:30, 100,000)这类格式,核心原因是Bar图的x轴参数误传入了包含Time和Volume的复合数据(比如元组或多列DataFrame),而非单独的时间序列数据,导致Plotly将两个值组合后显示。


具体解决步骤

1. 修正Bar图的x轴参数配置

检查你的代码中go.Bar的x参数,确保它只绑定单独的时间列(比如df['Time'])或DataFrame的时间索引,而非多列数据。

  • 错误示例(导致合并显示):
    fig.add_trace(go.Bar(x=df[['Time', 'Volume']], y=df['Volume']))
    
  • 正确示例:
    # 直接使用Time列作为x轴
    fig.add_trace(go.Bar(x=df['Time'], y=df['Volume'], name='成交量'))
    # 或使用DataFrame的时间索引(如果已将Time设为索引)
    fig.add_trace(go.Bar(x=df.index, y=df['Volume'], name='成交量'))
    

2. 确保Volume列是纯数值类型

如果Volume列包含千分位逗号或字符串格式,会导致数据解析异常,先做类型转换:

# 移除千分位逗号并转为整数
df['Volume'] = df['Volume'].replace(',', '', regex=True).astype(int)
# 检查数据类型,确认是int/float
print(df['Volume'].dtype)

3. 统一组合图的x轴对齐

为避免K线图和柱状图的x轴错位,显式配置x轴类型:

fig.update_layout(
    xaxis=dict(
        type='category'  # 适用于字符串格式的时间(如"10:30")
        # 若Time是datetime类型,改用type='date'
    )
)

完整可运行示例代码

import plotly.graph_objects as go
import pandas as pd

# 模拟你的数据集结构
df = pd.DataFrame({
    'Time': ['10:30', '10:35', '10:40', '10:45'],
    'Open': [150.2, 152.5, 151.8, 153.1],
    'High': [153.0, 154.2, 152.5, 153.8],
    'Low': [149.5, 151.3, 150.7, 152.0],
    'Close': [152.3, 153.1, 151.5, 153.5],
    'Volume': ['100,000', '120,000', '95,000', '110,000']
})

# 预处理Volume列
df['Volume'] = df['Volume'].replace(',', '', regex=True).astype(int)

# 创建K线图
fig = go.Figure(data=[go.Candlestick(
    x=df['Time'],
    open=df['Open'],
    high=df['High'],
    low=df['Low'],
    close=df['Close'],
    name='K线'
)])

# 添加成交量柱状图(双Y轴布局)
fig.add_trace(go.Bar(
    x=df['Time'],
    y=df['Volume'],
    name='成交量',
    yaxis='y2'
))

# 配置布局
fig.update_layout(
    title='K线+成交量组合图',
    xaxis_title='时间',
    yaxis_title='价格',
    yaxis2=dict(
        overlaying='y',
        side='right',
        title='成交量'
    ),
    xaxis=dict(type='category')
)

fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:10:14