python - 无法使用 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 函数,这是它显示的图形:
蒂姆·罗伯茨(TIM ROBERTS)没看错,这只是一个错字。谢谢蒂姆
解决方案
我删除 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()
推荐阅读
- r - R中的Kolmogorov-Smirnov检验 - For-loop
- dialogflow-es - 错误:getaddrinfo EAI_AGAIN api.dialogflow.com:443
- arrays - 如何使用蓝色棱镜将文本中的 fieldinfo 参数用于列代码
- google-sheets - 如何创建引用来自多个工作表的数据的数据透视表?
- c++ - 更改调用者传递的结构?(从前序构造二叉搜索树)
- c++ - 为什么嵌套类时不能从内部类访问外部类的私有成员?
- c# - 将一个类列表中的数据分配给另一个类列表
- android - 设备启动时不发送 FCM 消息且有密码
- c++ - 如何在 CLion 项目中使用共享的 .clang 格式
- java - collectors.tomap 和 HeaderEelement 的 getValue 和 getNmae 存在问题