Matplotlib中两条线之间的角度为正确的比例

时间:2017-10-03 21:20:09

标签: python matplotlib

我做同样的事情that answered here

def get_angle_plot(line1, line2, offset = 1, color = None, origin = [0,0], len_x_axis = 1, len_y_axis = 1):
    l1xy = line1.get_xydata()
    slope1 = (l1xy[1][1] - l1xy[0][1]) / float(l1xy[1][0] - l1xy[0][0])
    angle1 = abs(math.degrees(math.atan(slope1))) # Taking only the positive angle
    l2xy = line2.get_xydata()
    slope2 = (l2xy[1][1] - l2xy[0][1]) / float(l2xy[1][0] - l2xy[0][0])
    angle2 = abs(math.degrees(math.atan(slope2)))
    theta1 = min(angle1, angle2)
    theta2 = max(angle1, angle2)
    angle = theta2 - theta1
    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, theta1, theta2, color=color, label = str(angle)+u"\u00b0")

当Line2D-s与示例相同时。一切正常。

 fig = plt.figure()
 line_1 = Line2D([0,1], [0,4], linewidth=1, linestyle = "-", color="green")
 line_2 = Line2D([0,4.5], [0,3], linewidth=1, linestyle = "-", color="red")
 ax = fig.add_subplot(1,1,1)
 ax.add_line(line_1)
 ax.add_line(line_2)
 angle_plot = get_angle_plot(line_1, line_2, 1)
 ax.add_patch(angle_plot) # To display the angle arc
 plt.show()

但是当我略微改变这个

 line_1 = Line2D([10,30], [1,2], linewidth=1, linestyle = "-", color="green")
 line_2 = Line2D([10,30], [1,1], linewidth=1, linestyle = "-", color="red")

我得到1 * 1大小的白色空图。如果更精致,不是2 * 30

1 个答案:

答案 0 :(得分:0)

您需要将origin设置为两条线相交的点。在这种情况下origin = [10,1]。 然后您可能想要重新划分轴,因为要显示的行超出了范围[0,1]。您可以将ax.relim(); ax.autoscale_view()用于此目的。

line_1 = Line2D([10,30], [1,2], linewidth=1, linestyle = "-", color="green")
line_2 = Line2D([10,30], [1,1], linewidth=1, linestyle = "-", color="red")

ax = fig.add_subplot(1,1,1)
ax.add_line(line_1)
ax.add_line(line_2)
angle_plot = get_angle_plot(line_1, line_2, 1, origin = [10,1])
ax.add_patch(angle_plot) # To display the angle arc
ax.relim()
ax.autoscale_view()
plt.show()

请注意,更简单的选项肯定不是将行定义为Line2D,而是像往常一样plot。这使得无需重新划分轴。

ax = fig.add_subplot(1,1,1)
line_1, = ax.plot([10,30], [1,2], linewidth=1, linestyle = "-", color="green")
line_2, = ax.plot([10,30], [1,1], linewidth=1, linestyle = "-", color="red")
angle_plot = get_angle_plot(line_1, line_2, 5, origin = [10,1])
ax.add_patch(angle_plot) # To display the angle arc

plt.show()

因为x和y标度差异很大,结果看起来更像是一条直线。

enter image description here