使用Plotly(Python)实现环形图注释相对位置不随分辨率变化
解决方案
问题核心是你当前使用的是相对于整个画布的全局固定坐标,画布宽高比例变化时坐标对应的实际像素位置就会偏移。正确做法是将注释绑定到对应子图本身的域坐标系,实现相对环形图的固定定位。
修改方法
在每个注释配置中新增xref和yref参数,指定为对应子图的域坐标系,坐标直接设为0.5即可永久保持在对应环形的正中心,不需要手动计算全局坐标值。
修改后的完整代码
import plotly.graph_objects as go from plotly.subplots import make_subplots lst_abc = [153, 256] lst_def = [1569, 724] lst_ghi = [75618, 28971] lst_long = [2, 5] # Create subplots, using 'domain' type for pie charts specs = [[{'type':'domain'}, {'type':'domain'}], [{'type':'domain'}, {'type':'domain'}]] fig = make_subplots(rows=2, cols=2, specs = specs) # Define pie charts fig.add_trace(go.Pie(labels=[1,2], values=lst_abc, name='ABC'), 1, 1) fig.add_trace(go.Pie(labels=[1,2], values=lst_def, name='DEF'), 1, 2) fig.add_trace(go.Pie(labels=[1,2], values=lst_ghi, name='GHI'), 2, 1) fig.add_trace(go.Pie(labels=[1,2], values=lst_long, name='Longer Title Here'), 2, 2) fig.update_traces(hole=.4, hoverinfo='percent', textinfo='value') fig.update_layout( showlegend=False, # Add annotations in the center of the donut pies. annotations=[ dict(text='ABC', x=0.5, y=0.5, xref='x domain', yref='y domain', font_size=15, showarrow=False), dict(text='DEF', x=0.5, y=0.5, xref='x2 domain', yref='y2 domain', font_size=15, showarrow=False), dict(text='GHI', x=0.5, y=0.5, xref='x3 domain', yref='y3 domain', font_size=15, showarrow=False), dict(text='Longer Title Here', x=0.5, y=0.5, xref='x4 domain', yref='y4 domain', font_size=15, showarrow=False) ]) fig.show() with open('Current Stats.html', 'a') as f: f.write(fig.to_html(full_html=False, include_plotlyjs='cdn'))
原理解释
xref='x{序号} domain'表示当前注释的x坐标是相对于对应子图x轴的范围计算的,取值0对应子图最左侧,1对应子图最右侧,0.5就是水平中心yref='y{序号} domain'同理,0对应子图最底部,1对应子图最顶部,0.5就是垂直中心- 子图序号按行优先顺序排列,2行2列的子图从左到右从上到下对应序号1/2/3/4
内容的提问来源于stack exchange,提问作者John Anderson
相关产品推荐
相关产品推荐

