python中怎么输⼊⾓度_python–在Matplotlib中绘制两⾏之间
的⾓度的最佳⽅式
您可以使⽤
matplotlib.patches.Arc绘制相应⾓度测量的弧.
绘制⾓弧:
定义⼀个可以使⽤2个matplotlib.lines.Line2D对象的函数,计算⾓度并返回⼀个matplotlib.patches.Arc对象,您可以将其添加到绘图中. def get_angle_plot(line1,line2,offset = 1,color = None,origin = [0,0],len_x_axis = 1,len_y_axis = 1):
l1xy = _xydata()
# Angle between line1 and x-axis
slope1 = (l1xy[1][1] - l1xy[0][2]) / float(l1xy[1][0] - l1xy[0][0])
angle1 = abs(math.degrees(math.atan(slope1))) # Taking only the positive angle
l2xy = _xydata()
# Angle between line2 and x-axis
slope2 = (l2xy[1][3] - l2xy[0][4]) / 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 = _color() # Uses the color of line 1 if color parameter is not passed.
return Arc(origin,len_x_axis*offset,len_y_axis*offset,theta1,theta2,color=color,label = str(angle)+u"\u00b0")
打印⾓度值:
您想要将⾓度值显⽰为内联,请参阅this SO如何在matplotlib中打印内联标签的问题.请注意,您必须打印弧的标签.
我做了⼀个⼩函数,它提取圆弧的顶点,并尝试计算⾓度⽂本的坐标.
这可能不是最佳的,并且可能不适⽤于所有⾓度值.
def get_angle_text(angle_plot):
angle = _label()[:-1] # Excluding the degree symbol
angle = "%0.2f"%float(angle)+u"\u00b0" # Display angle upto 2 decimal places
# Get the vertices of the angle arc
vertices = _verts()
# Get the midpoint of the arc extremes
x_width = (vertices[0][0] + vertices[-1][0]) / 2.0
y_width = (vertices[0][5] + vertices[-1][6]) / 2.0
#print x_width,y_width
separation_radius = max(x_width/2.0,y_width/2.0)
return [ x_width + separation_radius,y_width + separation_radius,angle]
或者您可以随时⼿动计算标签点,并使⽤text显⽰⾓度值.您可以使⽤get_label()⽅法从Arc对象的标签获取⾓度值(因为我们将标签设置为⾓度值为unicode度符号).
上述功能的使⽤⽰例:
matplotlib中subplotfig = plt.figure()
line_1 = Line2D([0,1],[0,4],linewidth=1,linestyle = "-",color="green")
line_2 = Line2D([0,4.5],3],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)
angle_text = get_angle_text(angle_plot)
# Gets the arguments to be passed as a list to display the angle value besides the arc
ax.add_patch(angle_plot) # To display the angle arc
<(*angle_text) # To display the angle value
ax.set_xlim(0,7)
ax.set_ylim(0,5)
如果您不在意⾓度⽂本的内联放置.您可以使⽤plt.legend()打印⾓度值.
最后:
plt.legend()
plt.show()
函数get_angle_plot中的offset参数⽤于指定弧的psudo-radius值.
当⾓弧彼此重叠时,这将是有⽤的.
(在这个图中,就像我说的那样,我的get_angle_text函数在放置⽂本值⽅⾯并不是很好,但是应该给出⼀个如何计算点的想法)
添加第三⾏:
line_3 = Line2D([0,7],color="brown")
ax.add_line(line_3)
angle_plot = get_angle_plot(line_1,line_3,2,color="red") # Second angle arc will be red in color
angle_text = get_angle_text(angle_plot)
ax.add_patch(angle_plot) # To display the 2nd angle arc
<(*angle_text) # To display the 2nd angle value

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。