如何在python中显示与x轴成角的圆弧

2024-06-25 06:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在xy平面的图形上画线的代码。我想为每一条线显示一条弧,并在其上表示角度。在

sim_score =[0.993832,0.543218,0.234745 ,0.873513,0.234565,0.789212]

plt.figure()
for i in sim_score:
    for j in sim_label:
        a= math.acos(i)
        b = a * 180 / math.pi
        point=(0,0)
        x,y = point
        length=10
        # find the end point
        endy = length * math.sin(math.radians(b))
        endx = length * math.cos(math.radians(b))        
        # plot the points
        ax = plt.subplot(111)
        # set the bounds to be 10, 10
        ax.set_ylim([0, 10])
        ax.set_xlim([0, 10])
        ax.plot([x, endx], [y,endy] )

我想做一个带角度的弧作为标签。在


Tags: theinforpltmathsimaxlength
1条回答
网友
1楼 · 发布于 2024-06-25 06:42:01

this post之后,我对代码源进行了调整,使其具有良好的基础:

import matplotlib.pyplot as plt
from matplotlib.patches import Arc
from matplotlib.lines import Line2D
import math

def get_angle_text(angle_plot):
    angle = angle_plot.get_label()[:-1]  # Excluding the degree symbol
    angle = "%0.2f" % float(angle) + u"\u00b0"  # Display angle upto 2 decimal places

    # Set the label position
    x_width = angle_plot.width / 2
    y_width = math.sin(math.radians(angle_plot.theta2))

    return [x_width, y_width, angle]

def get_angle_plot(line1, offset=1, color=None, origin=[0, 0], len_x_axis=1, len_y_axis=1):

    l1xy = line1.get_xydata()

    # Angle between line1 and x-axis
    slope = (l1xy[1][1] - l1xy[0][1]) / float(l1xy[1][0] - l1xy[0][0])
    angle = abs(math.degrees(math.atan(slope)))  # Taking only the positive angle

    if color is None:
        color = line1.get_color()  # Uses the color of line 1 if color parameter is not passed.

    return Arc(origin, len_x_axis * offset, len_y_axis * offset, 0, 0, angle, color=color,
               label=str(angle) + u"\u00b0")

    sim_score = [0.993832, 0.543218, 0.234745, 0.873513]

fig = plt.figure()
ax = fig.add_subplot(111)
offset = 0
for i in sim_score:
    offset += 2  # you play with this value to draw arc spaced from the previous
    a = math.acos(i)
    b = a * 180 / math.pi
    point = (0, 0)
    x, y = point
    length = 10
    # find the end point
    endy = length * math.sin(math.radians(b))
    endx = length * math.cos(math.radians(b))

    line = Line2D([x, endx], [y, endy], linewidth=1, linestyle="-", color="blue")
    angle_plot = get_angle_plot(line, offset)
    angle_text = get_angle_text(angle_plot)
    ax.add_line(line )
    ax.add_patch(angle_plot)
    ax.text(*angle_text)  # To display the angle value

ax.set_ylim([0, 10])
ax.set_xlim([0, 10])
plt.show()

你应该调整程序来放置标签,我刚刚做了一个快速的位置演算

结果图:

enter image description here

相关问题 更多 >