Skip to main content
 首页 » 编程设计

python之使用 matplotlib 寻找角度

2025年05月04日9haluo1

我对使用 matplotlib 还很陌生,找不到任何示例来说明如何标记点的角度。我需要在所有四个象限中找到角度,即如果点是 (1,1) 角度 = 45 度,(-1,1) 角度 = 135 度,(-1,-1) 角度 = 225 度和 ( 1,-1)应该是315度。

这是我需要将其添加到的函数:

def visualize(val,ar): 
   plt.figure() 
   ax = plt.gca() 
   ax.plot([val-5],[ar-5], marker='o', color='r') 
   ax.set_xlim([-5,5]) 
   ax.set_ylim([-5,5]) 
   plt.draw() 
   plt.grid() 
   plt.show()  

请您参考如下方法:

我认为您需要自己对自己的点进行数学运算,然后使用 annotate() 在图上注释这些点.从您的示例中很难判断 val 和 ar 是单值还是向量 - 我认为根据您使用的语法是单值。这是一个带有计算函数的示例和使用 annotate 的示例 - 我试图使绘图位与您的代码相同,只是添加位来计算度数,然后将它们放入在轴上

import math 
import matplotlib.pyplot as plt 
 
#This function does the maths - turns co-ordinates into angles 
#with 0 on +ve x axis, increasing anti-clockwise 
def get_theta(x,y): 
    theta = math.atan(y*1.0/x) / (2*math.pi) * 360 
    if x < 0: 
        theta += 180 
    if theta < 0: 
        theta += 360 
    return theta  
 
def visualize(val,ar): 
    ax = plt.gca() 
    ax.plot([val-5],[ar-5], marker='o', color='r') 
    ax.set_xlim([-5,5]) 
    ax.set_ylim([-5,5]) 
   #insert the following to calculate the angles and 
   #then annotate them on the plot 
    x,y = val-5,ar-5 
    label = get_theta(x, y) 
    ax.annotate(str(label)+' degrees', xy = (x, y), xytext = (-20, 20),textcoords = 'offset points') 
     
if __name__ == '__main__': 
    plt.figure() 
    x = [6,4,4,6] 
    y = [6,6,4,4] 
    for (val, ar) in zip(x,y): 
        visualize(val,ar)     
 
    plt.draw() 
    plt.grid() 
    plt.show()  

关于您可以使用注释做什么的更多变体是 in the docs .


输出