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

如何用Plotly等库在K线图顶部/底部显示标注列数值?

实现带自定义标注的K线图方案

推荐使用Plotly来实现,它的视觉效果和交互性远优于mplfinance,且标注配置灵活。以下是完整的实现步骤和代码:

核心思路

  1. 用Plotly的Candlestick组件绘制基础K线图
  2. 遍历数据中的annotation列,根据标注内容(或自定义规则)决定放置在K线顶部(high上方)还是底部(low下方)
  3. 将所有标注添加到图表布局中,调整样式保证可读性

完整代码示例

import pandas as pd
import plotly.graph_objects as go

# 替换成你的实际数据
data = pd.DataFrame({
    'open': [100, 102, 99, 101, 105],
    'high': [103, 105, 102, 104, 108],
    'low': [98, 100, 97, 99, 103],
    'close': [102, 103, 101, 103, 106],
    'annotation': ['+5', '-2', '+3', '', '+4']
}, index=pd.date_range('2024-01-01', periods=5))

# 创建K线图主体
fig = go.Figure(data=[go.Candlestick(
    x=data.index,
    open=data['open'],
    high=data['high'],
    low=data['low'],
    close=data['close'],
    increasing_line_color='#ef5350',  # 自定义上涨K线颜色
    decreasing_line_color='#26a69a',  # 自定义下跌K线颜色
    showlegend=False
)])

# 批量添加标注
annotations = []
price_offset = 0.6  # 标注与K线的距离,可根据数据量级调整
for date, row in data.iterrows():
    ann_text = row['annotation']
    if not ann_text:
        continue
    
    # 自定义标注位置规则:正数放K线顶部,负数放底部
    if ann_text.startswith('+'):
        y_position = row['high'] + price_offset
        text_anchor = 'bottom'
    else:
        y_position = row['low'] - price_offset
        text_anchor = 'top'
    
    annotations.append({
        'x': date,
        'y': y_position,
        'xanchor': 'center',
        'yanchor': text_anchor,
        'text': ann_text,
        'showarrow': False,
        'font': {'size': 11, 'color': '#2d3436'}
    })

# 调整图表布局
fig.update_layout(
    annotations=annotations,
    xaxis_title='日期',
    yaxis_title='价格',
    xaxis_rangeslider_visible=False,  # 隐藏底部的时间滑块(可选)
    title='带标注的K线图',
    template='plotly_white',  # 清爽的白色模板
    yaxis={'fixedrange': False}  # 允许鼠标滚轮缩放Y轴
)

# 显示图表
fig.show()

可自定义项

  • 修改increasing_line_color和decreasing_line_color调整K线颜色
  • 调整price_offset控制标注与K线的距离
  • 修改标注位置规则(比如根据close和open的大小判断,而不是annotation的正负)
  • 调整font参数修改标注的字体大小、颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:00:58