Long story short, the highest upvoted answer to this question no longer works in Google Colab, although it used to work perfectly. What exactly has changed, and how does one fix it?
Made more explicit:
import numpy as np
import matplotlib.pyplot as plt
V = np.array([[1,1],[-2,2],[4,-7]])
origin = [0], [0] # origin point
plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21)
plt.show()
no longer works, since it seems the capability of using ":" has been taken out of plt.quiver. The following works, however:
import numpy as np
import matplotlib.pyplot as plt
V = np.array([[1,1],[-2,2],[4,-7]])
origin = [0], [0] # origin point
plt.quiver(*origin, V[0,0], V[0,1], color=['r'], scale=21)
plt.quiver(*origin, V[1,0], V[1,1], color=['g'], scale=21)
plt.quiver(*origin, V[2,0], V[2,1], color=['b'], scale=21)
plt.show()
will do what the old code did. How can I recover the use of ":"?
Evidently, the *origin part no longer works.
import numpy as np
import matplotlib.pyplot as plt
V = np.array([[1,1],[-2,2],[4,-7]])
O=np.array([[0],[0],[0]])
ax=plt.quiver(O[:],O[:],V[:,0],V[:,1], color=['r','g','b'], scale=21)
plt.show()
Related
I just tried to execute this code. but it shows always this error:'f() missing 1 required positional argument:'t'
please can you tell me what should I change?
import numpy as np
def f(y,z,t):
return np.array([2*y+z-t,z+y])
import matplotlib.pyplot as plt
from scipy.integrate import odeint
t=np.linspace(0,2,1000)
sol=odeint(f,[0,1],t)
y,z=sol[:,0],sol[:,1]
plt.plot(t,y,label='y')
plt.plot(t,z,label='z')
plt.show()
Depending on what you are trying to do, you can get around it two ways. To pass in additional arguments other than y and t you need to include them as a constant in the function parameter.
import numpy as np
def f(t,y,z):
return np.array([2*y+z-t,z+y])
import matplotlib.pyplot as plt
from scipy.integrate import odeint
t=np.linspace(0,2,1000)
z = 10.0
sol=odeint(f,[0,1],t, tfirst=True, args=(z, ))
y,z=sol[:,0],sol[:,1]
plt.plot(t,y,label='y')
plt.plot(t,z,label='z')
plt.show()
This will still cause an error. However, if you are also trying to obtain z as result then you should be able to run:
import numpy as np
def f(t,inp):
y, z = inp
return np.array([2*y+z-t,z+y])
import matplotlib.pyplot as plt
from scipy.integrate import odeint
t=np.linspace(0,2,1000)
sol=odeint(f,[0,1],t, tfirst=True)
y,z=sol[:,0],sol[:,1]
plt.plot(t,y,label='y')
plt.plot(t,z,label='z')
plt.show()
This should run without any errors but you may need to double check that this is the result you are expecting.
(The tfirst argument is just for clarity to make ensure the order of arguments provided is correct, you can remove and re-order if you want as well.)
Documentation for odeint function here: https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html
I am trying to create a factor plot but I am not able to change the kind of it from point to bar. How do we do that?
The codes used are
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.catplot('Sex',kind="bar",data=titanic_df)
The seaborn documentation has the exact example you are looking for. Following the documentation, if you run the below lines, it should generate the bar plot shown.
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
titanic = sns.load_dataset("titanic")
exercise = sns.load_dataset("exercise")
g = sns.catplot("alive", col="deck",
col_wrap=3, data=titanic[titanic.deck.notnull()],
kind="count", height=2.5, aspect=.8)
The important argument to note here is kind="count".
So I was trying to map out some math functions in 3d using matplotlib when I noticed something... The 3d plot suddenly changed (more like broke) when I tried to fix a previous issue wherein I was encountering some 'missing surface' - a gap in the plot. The main question is this -- Is the 3d plot not showing the two peaks on higher precision due to some inherent computing limitations of Axes3d or some other reason? Also a secondary question -- Why am I encountering 'missing surfaces' near +1.25 and -1.25 in lower precision plot?
I have tried googling for it and referred a few posts but nothing came ot except more questions.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
X=np.arange(-2,+2,0.025)
## Use np.arange(-5,+5,0.25) to experience the 'surface loss' I mention but otherwise correct 2 spike plot at each of (0,-1) and (0,+1) for both X and Y
Y=np.arange(-2,+2,0.025)
X,Y=np.meshgrid(X,Y)
R=1+X**2-Y**2
S=R**2+4*(X**2)*(Y**2)
Z=R/S
fig=plt.figure()
ax=Axes3D(fig)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.viridis,norm=mpl.colors.Normalize(vmin=-1.,vmax=1.))
##NORMALIZE Was essential to get the proper color range
plt.show()
plt.savefig('art3d.jpeg',bbox_inches='tight')
plt.savefig('art3d.svg',bbox_inches='tight')
The ideal result should be like this (shows the func and the plot)
https://i.stack.imgur.com/kVnYc.png
The two plots I'm getting could be seen when the code is run as I can't seem to add images presumably because of low reputation :(
Any and all help is appreciated.Thanks in advance.
First note that the function in use is different from the wolfram alpha output. So let's use the function shown in the screenshot. Then you can limit the data to the range you want to show.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
X = np.arange(-2,+2,0.025)
Y=np.arange(-2,+2,0.025)
X,Y=np.meshgrid(X,Y)
Z = -2*X*Y / ((2*X*Y)**2 + (X**2 - Y**2 + 1)**2)
Z[(Z < -1)] = -1
Z[(Z > 1)] = 1
fig=plt.figure()
ax=Axes3D(fig)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.viridis,norm=mpl.colors.Normalize(vmin=-1.,vmax=1.))
plt.show()
I am new using python and try to do some plots. I realized, that a plot of a bump function is incorrect. I have no idea how python came to this result.
This is my 'code'
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
class MainBody():
x = np.linspace(0.0001,99.9999,1000)
result = np.exp((-1.0)/(x*(100.0-x)))
plt.plot(x,result)
plt.show()
I got this result
but I should get this
I know that Python is powerful but I think such simple things should work without occuring such errors, where is my mistake?
Thank you
Matthias
Use plt.ylim to set the y-limits. Otherwise, by default, matplotlib will try to show the entire dataset, whose y-limits go roughly from 0 to 1:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.0001,99.9999,1000)
result = np.exp((-1.0)/(x*(100.0-x)))
plt.plot(x,result)
plt.ylim(0.9975, 0.9999)
plt.show()
I would like to do a subplot of two figures with matplotlib and add a horizontal line in both. This is probably basic, but I don't know how to specify that one of the lines should be drawn in the first figure, they both end up in the last one. e.g.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.rand(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0])
l1=plt.axhline(0.5,color='black',ls='--')
l1.set_label('l1')
f2= s1.plot(ax=axes[1])
l2=plt.axhline(0.7,color='red',ls='--')
l2.set_label('l2')
plt.legend()
axhline does not have "ax" as an argument, as the pandas plot function does. So this would work:
l1=plt.axhline(0.5,color='black',ls='--',ax=axes[0])
I read the examples in matplotlib and I tried with this other option that does not work either (probably for good reasons)
axes[0].plt.axhline(0.5,color='black',ls='--')
How should I do to draw lines in subplots? Ideally with a legend Thanks!
with the help of #Nick Becker I answered my own "syntax" question.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.randn(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0],label='s1')
l1=axes[0].axhline(0.5,color='black',ls='--')
l1.set_label('l1')
axes[0].legend(loc='best')
f2= s1.plot(ax=axes[1],label='s2')
l2=axes[1].axhline(0.5,color='black',ls='--')
l2.set_label('l2')
axes[1].legend(loc='best')