无法使用matplotlib将最大值和最小值放入图形的python代码中

2024-10-01 07:46:28 发布

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

我试着画两个余弦函数,它们都有不同的振幅。我想在图形中标记最大值、最小值以及两者均触零的位置。首先,我试图标记最大值,但这似乎不起作用。我在stackoverflow中搜索了很多代码,由于某种原因,当我编译代码时,它开始出错。有人能帮我找到我的图形的最大值和最小值吗

这是我的密码:

import matplotlib
import numpy as np 
import matplotlib.pyplot as plt

def h(X):
        return (10*(np.cos(((120*(np.pi))*x)+((np.pi/6)))))

def g(x):
        return (5*(np.cos(((120*(np.pi))*x)-((np.pi/6)))))

x = np.linspace(0, 0.05, 1000)


plt.ylabel("Voltaje (V)")
plt.xlabel("Tiempo (s)")


plt.grid(True)

def annot_max(x,y, ax=None):
    xmax = x[np.argmax(y)]
    ymax = y.max()
    text= "x={:.3f}, y={:.3f}".format(xmax, ymax)
    if not ax:
        ax=plt.gca()
    bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
    arrowprops=dict(arrowstyle="->",connectionstyle="angle,angleA=0,angleB=60")
    kw = dict(xycoords='data',textcoords="data",
              arrowprops=arrowprops, bbox=bbox_props, ha="left", va="top")
    ax.annotate(text, xy=(xmax, ymax), xytext=(xmax+.5,ymax+5), **kw)

#plt.annotate("maximo de grafica 1", xy=(2,1), xytext=(3,1.5) , arrowprops=dict(facecolor="black", shrink=0.05),) #i also tried this, and didn't work too.


plt.plot(x,h(x), label="grafica 1")  
plt.plot(x,g(x), label="grafica 2")


plt.legend(loc=1)

annot_max(x,h(x))
annot_max(x,(g(x))

plt.show() 

在没有def annot_max功能的情况下,这是它显示的图形:

graphic without the def annot_max in my code

蒂姆·罗伯茨答对了,只是打错了。谢谢你,蒂姆


Tags: import图形defnppipltaxdict
1条回答
网友
1楼 · 发布于 2024-10-01 07:46:28

我删除xytext-您必须保持在图形范围内。添加.5会导致注释行为不正确

 def h(X):
         return (10*(np.cos(((120*(np.pi))*x)+((np.pi/6)))))

 def g(x):
         return (5*(np.cos(((120*(np.pi))*x)-((np.pi/6)))))

 x = np.linspace(0, 0.05, 1000)

 plt.ylabel("Voltaje (V)")
 plt.xlabel("Tiempo (s)")
 plt.grid(True)

 def annot_max(x,y, ax=None):
     xmax = x.max()
     ymax = y.max()
     text= "x={:.3f}, y={:.3f}".format(xmax, ymax)
     print(text)
     if not ax:
         ax=plt.gca()
     bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
     arrowprops=dict(arrowstyle="-     >",connectionstyle="angle,angleA=0,angleB=60")
     kw = dict(xycoords='data',textcoords="data",
          arrowprops=arrowprops, bbox=bbox_props, ha="left", va="top")
     ax.annotate(text,xy=(xmax,ymax),**kw)

 plt.plot(x,h(x), label="grafica 1")  
 plt.plot(x,g(x), label="grafica 2")
 plt.legend(loc=0)
 annot_max(x,h(x))
 annot_max(x,g(x))
 plt.show() 

相关问题 更多 >