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

如何在Python Plotly中为2022年4月的最后一根K线自定义颜色?

给指定K线单独设置颜色的方法

Plotly自带的蜡烛图组件没法直接修改单根K线的颜色,最简单的解决办法就是把数据拆成两部分:大部分正常配色的K线,加上你要改色的那根单独的K线,分别绘制到图表上即可。

具体修改步骤与完整代码

  1. 拆分原始数据集:将除2022年4月(最后一根)以外的所有数据作为主体K线数据,单独提取2022年4月的K线数据作为目标修改对象。
  2. 先绘制主体K线(保持原有红绿配色),再绘制目标K线(设置自定义颜色)。

修改后的完整代码如下:

fig = make_subplots(rows=1, cols=1, subplot_titles=[], \
                    specs=[[{"secondary_y": True}]], \
                    vertical_spacing=0, shared_xaxes=True, row_width=[1.0])
fig.add_trace(go.Scatter(x=df.index, y=df['Pivot'], marker=dict(color='black'), line=dict(width=2),
                         mode='lines', name='Pivot Point'), row=1, col=1)

fig.add_trace(go.Scatter(x=df.index, y=df['R1'], marker=dict(color='olive'), line=dict(width=1,dash='dot'),
                         mode='lines', name='Resistance 1'), row=1, col=1)

fig.add_trace(go.Scatter(x=df.index, y=df['S1'], marker=dict(color='turquoise'), line=dict(width=2,dash='dot'),
                         mode='lines', name='Support 1'), row=1, col=1)

# 拆分数据:主体K线和要改色的目标K线
df_main = df.iloc[:-1]  # 取除最后一行外的所有数据(对应除2022年4月外的K线)
df_last = df.iloc[-1:]  # 取最后一行(2022年4月的K线)

# 添加主体蜡烛图,保留原有红绿配色
fig.add_trace(go.Candlestick(x=df_main.index,
                             open=df_main['Open'],
                             close=df_main['Close'],
                             low=df_main['Low'],
                             high=df_main['High'],
                             increasing_line_color='green', decreasing_line_color='red', name='HRC Price'),row=1, col=1,)

# 添加目标蜡烛图,自定义颜色(示例用蓝色表示上涨、橙色表示下跌,可自行修改)
fig.add_trace(go.Candlestick(x=df_last.index,
                             open=df_last['Open'],
                             close=df_last['Close'],
                             low=df_last['Low'],
                             high=df_last['High'],
                             increasing_line_color='blue',
                             decreasing_line_color='orange',
                             showlegend=False),  # 隐藏重复图例,避免图表混乱
              row=1, col=1,)

fig.update_layout(
title='HRC Monthly Price',
yaxis_title='Price',
shapes = [dict(
    x0='2022-03-14', x1='2022-03-14', y0=0, y1=1, xref='x', yref='paper',
    line_width=2)],
annotations=[dict(
    x='2022-03-14', y=0.05, xref='x', yref='paper',
    showarrow=False, xanchor='left', text='Ukraine - Russia War Starts')]
)

return fig

额外实用提示

  • 如果不想靠位置定位最后一根K线,而是精准筛选2022年4月的数据,可以替换数据拆分的代码:
    # 假设DataFrame的索引是日期格式
    df_last = df[df.index.strftime('%Y-%m') == '2022-04']
    df_main = df[df.index.strftime('%Y-%m') != '2022-04']
    
  • 自定义颜色支持任意颜色名称(如'purple')或十六进制色码(如'#FF5733'),可根据需求调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:15:34