首页 > 解决方案 > 无法使用 matplotlib 在我的图形的 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 函数,这是它显示的图形:

我的代码中没有 def annot_max 的图形

蒂姆·罗伯茨(TIM ROBERTS)没看错,这只是一个错字。谢谢蒂姆

标签: pythonpython-3.xmatplotlib

解决方案


我删除 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() 

推荐阅读