Plotly 中的仪表图给出超过 180 度/超过一个圆

Gauge Chart in Plotly to give more than 180 degree / more than a circle

我目前正在制作仪表图,因为它们也在 documentation 中。

然而,我所看到的一切都带有半个圆 (180°) 的图表。对于“圆”,我需要 300° 之类的东西。有办法改变吗?

我一直在自己阅读文档和测试,但不幸的是答案是“不,没有办法显示 180° 以上的任何东西”

仪表图不支持显示大于 180˚ 的角度

但是,您可以通过绘制每个组件(例如条形图本身)以及周围的刻度线来手动创建圆形仪表图。我将对我回答的问题使用类似的方法 here

这是一个允许您通过指定开始和结束度数、注释文本和您想要的刻度线来构建此类图表的函数。我在函数中硬编码了刻度线,因为我真的不知道你想如何控制刻度线,但这部分函数可以根据需要修改。

import numpy as np
from numpy import sin, cos, pi
import plotly.graph_objects as go

def degree_to_radian(degrees):
    return degrees*pi/180

def draw_circular_gauge(degree_start, degree_end, annotation_text, r=1.0, padding=0.2, tick_length=0.02):
    radian_start, radian_end =  degree_to_radian(degree_start), degree_to_radian(degree_end)
    theta = np.linspace(radian_start,radian_end,5000)
    x = r * cos(theta)
    y = r * sin(theta)
    fig = go.Figure()

    # draw the bar
    fig.add_trace(go.Scatter(
        x=x, y=y, mode='markers', marker_symbol='circle', marker_size=15, hoverinfo='skip'
    ))
    
    # draw the outer border
    for r_outer in [r-padding,r+padding]:
        fig.add_shape(type="circle",
            xref="x", yref="y",
            x0=-r_outer, y0=-r_outer, x1=r_outer, y1=r_outer,
            line_color="black",
        )

    tick_theta = np.linspace(pi,-pi,13)
    tick_labels = np.linspace(0,330,12)
    tick_start_x, tick_end_x = (r+padding)*cos(tick_theta), (r+padding+tick_length)*cos(tick_theta)
    tick_start_y, tick_end_y = (r+padding)*sin(tick_theta), (r+padding+tick_length)*sin(tick_theta)
    tick_label_x, tick_label_y = (r+padding+0.04+tick_length)*cos(tick_theta), (r+padding+0.04+tick_length)*sin(tick_theta)

    # add ticks
    for i in range(len(tick_theta)):
        fig.add_trace(go.Scatter(
            x=[tick_start_x[i], tick_end_x[i]],
            y=[tick_start_y[i], tick_end_y[i]],
            mode='text+lines',
            marker=dict(color="black"),
            hoverinfo='skip'
        ))
    
    # add ticklabels
    fig.add_trace(go.Scatter(
        x=tick_label_x,
        y=tick_label_y,
        text=tick_labels,
        mode='text',
        hoverinfo='skip'
    ))

    ## add text in the center of the plot
    fig.add_trace(go.Scatter(
        x=[0], y=[0],
        mode="text",
        text=[annotation_text],
        textfont=dict(size=30),
        textposition="middle center",
        hoverinfo='skip'
    ))

    ## get rid of axes, ticks, background
    fig.update_layout(
        showlegend=False,
        xaxis_range=[-1.5,1.5], yaxis_range=[-1.5,1.5], 
        xaxis_visible=False, xaxis_showticklabels=False, 
        yaxis_visible=False, yaxis_showticklabels=False, 
        template="plotly_white",
        width=800, height=800
    )
    return fig  

fig = draw_circular_gauge(180,-120,"300")
fig.show()