如何将Plotly中hrect的注释关联至次级Y轴?
问题:Plotly次级Y轴关联hrect的注释位置混乱
我用Plotly创建双Y轴图表,调用add_hrect并设置secondary_y=True时,水平矩形的位置显示正常,但绑定的注释没有关联到次级Y轴,导致位置混乱。当前代码如下:
fig.add_hrect(y0=current_quantile, y1=current_quantile, fillcolor="black", annotation_position="bottom right", annotation_text="Current performance", line_width=1, secondary_y=True)
手动修改HTML代码中注释的yref为y2后显示正常,但尝试annotate=dict(yref="y2")、annotation_yref="y2"等参数均无效,不确定add_hrect调用中是否支持修改注释的yref,求可行解决方法。
解决方法
目前Plotly的add_hrect方法未直接提供设置注释yref的参数,可通过以下两种方式解决:
- 拆分hrect与注释的创建步骤:先添加不带注释的hrect,再单独创建关联次级Y轴的注释
# 添加水平矩形,不附带注释 fig.add_hrect(y0=current_quantile, y1=current_quantile, fillcolor="black", line_width=1, secondary_y=True) # 单独添加绑定次级Y轴的注释 fig.add_annotation( text="Current performance", xref="paper", yref="y2", x=0.95, y=current_quantile, showarrow=False, align="right" )
其中xref="paper"让注释固定在X轴右侧相对位置,yref="y2"明确关联次级Y轴,y值与hrect的分位数保持一致。
- 直接修改图表的注释属性:调用
add_hrect后,遍历布局中的注释项,修改目标注释的yref
# 添加带注释的水平矩形 fig.add_hrect(y0=current_quantile, y1=current_quantile, fillcolor="black", annotation_position="bottom right", annotation_text="Current performance", line_width=1, secondary_y=True) # 修正注释的Y轴关联 for ann in fig.layout.annotations: if ann.text == "Current performance": ann.yref = "y2" break
这种方式无需拆分步骤,直接修正add_hrect自动生成的注释的轴关联属性。
内容的提问来源于stack exchange,提问作者Xaruman
相关产品推荐
相关产品推荐

