You need to enable JavaScript to run this app. Plotly烛台图标注perDel列值时出现ValueError如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Plotly烛台图标注perDel列值时出现ValueError如何解决?

错误原因

报错的核心原因是annotations参数要求接收单个标注配置组成的列表,不能直接传入pandas Series类型的整列数据。你当前的写法直接把整列Date、High Price、perDel传给了单个annotation的配置,不符合Plotly的参数规范。
同时你原本写的yref='paper'是相对画布的比例坐标,改成y才能和价格轴绑定,让标注显示在对应K线的高点位置。

可行解决方案

直接修改display_candlestick函数里的fig.update_layout部分,用循环逐行生成标注即可,修改后的完整代码如下:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go

import pandas as pd
from datetime import datetime

df = pd.read_csv(r'..\CandlesPlotPython\APOLLOALLN.csv')

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Checklist(
        id='toggle-rangeslider',
        options=[{'label': 'Include Rangeslider', 
                  'value': 'slider'}],
        value=['slider']
    ),
    dcc.Graph(id="graph"),
])

@app.callback(
    Output("graph", "figure"), 
    [Input("toggle-rangeslider", "value")])
def display_candlestick(value):
    fig = go.Figure(go.Candlestick(
        x=df['Date'],
        open=df['Open Price'],
        high=df['High Price'],
        low=df['Low Price'],
        close=df['Close Price']
    ))
    
    # 逐行生成标注,替代原来的单annotation写法
    annotations = []
    for idx, row in df.iterrows():
        annotations.append(dict(
            x=row['Date'], 
            y=row['High Price'], 
            xref='x', 
            yref='y', # 改为绑定y轴,显示在实际高点位置
            showarrow=False, 
            xanchor='center',
            yanchor='bottom', # 让文字底部对齐高点,不会挡住K线
            text=str(row['perDel']),
            font=dict(size=10) # 可选调整字体大小避免拥挤
        ))
    
    fig.update_layout(
        xaxis_rangeslider_visible='slider' in value,
        annotations=annotations
    )

    return fig

app.run_server(debug=True)

可选优化

如果K线数量较多标注太拥挤,可以添加条件过滤,只标注perDel超过指定阈值的数值,比如:

for idx, row in df.iterrows():
    # 只标注perDel超过50的数值
    if row['perDel'] > 50:
        annotations.append(dict(...))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 02:06:05