How to rotate the dial in a gauge chart? Using python plotly

前端 未结 3 1074
天命终不由人
天命终不由人 2021-01-21 06:07

I am recently into using plotly package for a gauge chart in python.

After going through the tutorial and template here, I wonder if there is a way to

相关标签:
3条回答
  • 2021-01-21 07:06

    A bit late to this question. My solution to this problem, though it still needs work is:

    I was using the svg path for the dial given in the plotly tutorial, namely

    M 0.235 0.5 L 0.24 0.65 L 0.245 0.5 Z

    The center point (0.24,0.65) touches the arch of the circle on the inner part of the gauge. Thus, the arch is a circle with its center at (0.24,0.5) and a radius of 0.15.

    Given an angle theta in radians, a center (h,k), and expressing a circle in polar form, we can easily obtain cartesian coordinates for a point on the circle at that degree as follows:

    x = h +  r * cos(theta)
    y = k +  r * sin(theta)
    

    We can then simply map our input to the expected angle it is supposed to have on the gauge and calculate x and y from there. For my implementation in python, using the math library, this translates to the following:

    h = 0.24
    k = 0.5
    r = 0.15
    # Map my_raw_value to degrees. my_raw_value is between 0 and 300
    theta = my_raw_value * 180 / 300
    # and then into radians
    theta = theta * math.pi / 180
    x = h + r*math.cos(theta)
    y = k + r*math.sin(theta)
    path = 'M 0.235 0.5 L ' + str(x) + ' ' + str(y) + ' L 0.245 0.5 Z'
    

    This will dynamically generate the triangle path for your shape and roughly set the long edge of the dial where it is supposed to be. Ideally we would want to rotate the whole thing, since in this implementation the base of the triangle stays static, resulting in a straight line on the limits of the graph. You would need to multiply all three points on the path by a rotation matrix to get the exact coordinates.

    0 讨论(0)
  • 2021-01-21 07:08

    Not sure why but the above solution did not work for me. However, if you attempt a few values you will discover that the x and y axis are not on the same scale. You can find the constant by looking at the ratio between the radius in each scale. The result is simple, everything remains the same as @jvrsgsty answer, except you multiply the x cartesian coordinates by C = 0.25.

    So, literally just do the same as @jvrsgsty suggests but the x coordinate is now:

    x = h + r*math.cos(theta)*C
    
    0 讨论(0)
  • 2021-01-21 07:09

    In my case, the solution provided by @jvrsgsty needed a bit modification to work. That's how I finally fixed it:

    h = 0.24
    k = 0.5
    r = 0.15
    # Map my_raw_value to degrees. my_raw_value is between 0 and 300
    theta = (100 - my_raw_value) * 180 / 100
    # and then into radians
    theta = theta * math.pi / 180
    x = h + r*math.cos(theta)
    y = k + r*math.sin(theta)
    path = 'M 0.235 0.5 L ' + str(x) + ' ' + str(y) + ' L 0.245 0.5 Z'
    
    0 讨论(0)
提交回复
热议问题