how can i get this graph by python? - python

i have written this code
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
r=np.arange(1,2)
theta=np.linspace(0,np.pi/2)
x=r*np.cos(theta)
y=r*np.sin(theta)
plt.plot(x,y)
plt.show()
and get this graph.
but i want to get the graph below.
i'm confused about how to set a proper range of r.
i want to set r's range 1<=r<=2, but don't know how to do that.
how can i modify my code?

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
theta = np.linspace(0,np.pi/2)
for i in range(1,3):
x = []
y = []
for t in theta:
if t == 0:
y.append(0)
x.append(3-1)
elif t == np.pi/2:
y.append(3-1)
x.append(0)
else:
x.append(i*np.cos(t))
y.append(i*np.sin(t))
plt.plot(x,y)
plt.show()

Related

How to solve Axes3D error when plotting a function?

I have a code to graph mi function f(x,y)=(x^4 + y^4). I already imported all the necessary libraries, but when i run it, the "MatplotlibDeprecationWarning: Axes3D(fig) adding itself to the figure is deprecated since 3.4. Pass the keyword argument auto_add_to_figure=False and use fig.add_axes(ax) to suppress this warning. The default value of auto_add_to_figure will change to False in mpl3.5 and True values will no longer work in 3.6. This is consistent with other Axes classes." error shows.
This is my code:
`
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
figura = plt.figure()
ejes = Axes3D(figura)
plt.show()
def f(x,y):
return ((x**4)+(y**4))
x = np.linspace(-2,2,40)
y = np.linspace(-2,2,40)
x,y = np.meshgrid(x,y)
z= f(x,y)
ejes.plot_wireframe(x,y,z)
`
On my environment it actually works. Anyway you can obtain the same plot using the "3d" projection of pyplot:
import numpy as np
import matplotlib.pyplot as plt
figura = plt.figure(figsize=(7,7))
ejes = plt.subplot(111, projection="3d")
def f(x,y):
return ((x**4)+(y**4))
x = np.linspace(-2,2,40)
y = np.linspace(-2,2,40)
x,y = np.meshgrid(x,y)
z= f(x,y)
ejes.plot_wireframe(x,y,z)
plt.show()

How to avoid plotting for a zero without deleting the zero entry in the line plot Matplotlib?

I have tried a sample code where I used my figure to plot:
import matplotlib.pyplot as plt
import numpy as np
l = [1.10867,1.10894,1.10914,1.10926,1.10930,0.00000,0.00000,0.00000,0.00000,0.00000,1.10867,1.10894,1.10914,1.10926,1.10930]
x = np.arange(len(l))
y = np.array(l)
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma
fig.canvas.draw()
fig.canvas.flush_events()
The figure comes out to be the following:
But I am expecting to have a figure this:
The expected figure is obtained when I removed the zeroes from the list. But I want to if there is a way to plot without removing zeroes from the list and still the figure looks like the expected one.
Please share any thoughts.
You can interpolate the points where y's are equal to 0 and plot:
import matplotlib.pyplot as plt
import numpy as np
l = [1.10867,1.10894,1.10914,1.10926,1.10930,0.00000,0.00000,0.00000,0.00000,0.00000,1.10867,1.10894,1.10914,1.10926,1.10930]
x = np.arange(len(l))
y = np.array(l)
y_interp = np.interp(x, x[np.where(y != 0)], y[np.where(y != 0)])
plt.plot(x, y_interp)

how to join line among the points

Hii experts i need to join the line between the points obtained using for loop .But only scatter plot(plt.scatter) is working not the plt.plot option in matplotlib
my prograamme is
import numpy as np
import matplotlib.pyplot as plt
f=np.arange(1,5,1)
for i in f:
sum = 0
for m in np.arange(1,6,1):
x=((4.6)*(m*2)*(5)**2)*(i)/62
print(x)
sum += x
print(i,sum)
plt.scatter(i,sum)
plt.show()
Try this :
import numpy as np
import matplotlib.pyplot as plt
f=np.arange(1,5,1)
x_values = []
y_values = []
for i in f:
sum = 0
for m in np.arange(1,6,1):
x=((4.6)*(m*2)*(5)**2)*(i)/62
sum += x
#plt.scatter(i,sum)
x_values.append(i)
y_values.append(sum)
plt.plot(x_values, y_values, marker='o')
plt.show()

Matplotlib 3d scatter _facecolors3d not working

I am trying to save a 3d scatter plot animation where points appear one at a time. I made the animation work, but when I set the face colors of the points they do not take effect and all points appear blue. When I use the same color array but on static image, colors work well.
Animation Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation
import random
import seaborn as sns
import pandas as pd
import json
import os
from matplotlib.animation import FuncAnimation
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib import rc
from IPython.display import HTML
from itertools import product
x=[]
y=[]
for i in range(-80, 80, 10):
x.append(i)
y.append(i)
combs = list(product(x,y))
def obj(x, y):
global HISTORY
e = 2.718
res = 7*x*y/(e**(0.001*x**2 + 0.001*y**2))
return res
z = [obj(x,y) for x, y in combs]
x = [obj[0] for obj in combs]
y = [obj[1] for obj in combs]
data = [[x[i],y[i],z[i]] for i in range(len(x))]
cmap = sns.cubehelix_palette(as_cmap=True)
m = max(z) # Get the worst score so we can use it as the darkest area of the plot.
face_colors = np.array([cmap(i/m) for i in z]) # Map all of the values with cmap colors.
df = pd.DataFrame(data, columns=["x","y","z"])
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
sc = ax.scatter([],[],[], alpha=0.5)
def update(i):
sc._offsets3d = (df.x.values[:i], df.y.values[:i], df.z.values[:i])
sc._facecolors3d = face_colors[:i]
sc._facecolors2d=sc._facecolors3d
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim(min(x),max(x))
ax.set_ylim(min(y),max(y))
ax.set_zlim(min(z),max(z))
ani = matplotlib.animation.FuncAnimation(fig, update, frames=len(df), interval=70)
HTML(ani.to_html5_video())
When I do not use the animation and just call plt.scatter like this:
sc = ax.scatter(df.x.values,df.y.values,df.z.values, facecolors=face_colors)
My image works well:
How can I keep these colors in my animation as well?
Code for static image:
x=[]
y=[]
for i in range(-80, 80, 10):
x.append(i)
y.append(i)
combs = list(product(x,y))
def obj(x, y):
global HISTORY
e = 2.718
res = 7*x*y/(e**(0.001*x**2 + 0.001*y**2))
return res
z = [obj(x,y) for x, y in combs]
x = [obj[0] for obj in combs]
y = [obj[1] for obj in combs]
data = [[x[i],y[i],z[i]] for i in range(len(x))]
cmap = sns.cubehelix_palette(as_cmap=True)
m = max(z) # Get the worst score so we can use it as the darkest area of the plot.
face_colors = [cmap(i/m) for i in z] # Map all of the values with cmap colors.
df = pd.DataFrame(data, columns=["x","y","z"])
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
sc = ax.scatter(df.x.values,df.y.values,df.z.values, facecolors=face_colors)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim(min(x),max(x))
ax.set_ylim(min(y),max(y))
ax.set_zlim(min(z),max(z))
plt.show()
Might just be a typo. _facecolor3d instead of _facecolors3d try this:
def update(i):
sc._offsets3d = (df.x.values[:i], df.y.values[:i], df.z.values[:i])
sc._facecolor3d = face_colors[:i]
sc._edgecolor3d = face_colors[:i]

Plot a poisson distribution graph in python

I would like to plot the Poisson function in Python using Matplotlib. The function is (exp(-5)*5^x)/factorial(x)
import numpy as np
import math
import matplotlib.pyplot as plt
t = np.arange(0, 20, 0.1)
d = []
for i in t:
p = pow(5,i)
q = p/math.factorial(i)
d.append(q)
plt.plot( t, np.exp(-5)*d, 'bs')
plt.show()
But I get this error."Only size^1 arrays can be converted to Python scalars". How can I plot this graph? Thanks in advance
i think your function is not right: it's exp(-5)
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import factorial
t = np.arange(0, 20, 0.1)
d = np.exp(-5)*np.power(5, t)/factorial(t)
plt.plot(t, d, 'bs')
plt.show()
The immediate problem is probably that you are using 't' instead of 'i' in your loop. However, you may want to avoid mixing python lists with numpy arrays. You could do it like,
import numpy as np
import scipy.misc
import math
import matplotlib.pyplot as plt
t = np.arange(0, 20, 0.1)
x = np.power(t, 5)
y = scipy.misc.factorial(t)
plt.plot( t, x / y, 'bs')
plt.show()

Categories