Issue
i'm trying to graphic two functions of cosine, which both have different amplitude. I want to mark the max, min and where both touch zero, in the graphic. First im trying to mark the max, but this doesn't seems to work. I have search many codes in stackoverflow and for some reason, when I compile the code it starts getting errors. Can anyone help me, finding max and min of my graphic please.
Here is my code:
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()
Without the def annot_max function this is the graphic it shows:
TIM ROBERTS GOT IT RIGHT, IT WAS JUST A TYPO. THANKS TIM
Solution
I remove xytext - you must stay within the range of the graph. Adding .5 causes the annotate to behave incorrectly.
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()
Answered By - Golden Lion
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.