How to turn off matplotlib plot default axis? - python

I'm plotting N plots in a grid without any decoration. The plots that have data are easily set to not show the axis by using axis('off'). But how can i do this for the "spillover" defaults from subplots()?
Here is a working example of the code in question:
import math
filenames = ['plot0', 'plot1', 'plot2', 'plot4', 'plot5', 'plot6', 'plot7', 'plot8', 'plot9', 'plotl0']
N = len(filenames)
Y = int(math.sqrt(N))
X = int(N / Y) + 1
fig, ax = plt.subplots(X, Y)
for i in range(N):
ax[divmod(i, Y)].text(0.5, 0.5, str('Test'))
ax[divmod(i, Y)].axis('off')
plt.show()

Use 'add_subplot()' to add 'subplot' to the 'fig' object with the required graph.
import matplotlib.pyplot as plt
import math
filenames = ['plot0', 'plot1', 'plot2', 'plot4', 'plot5', 'plot6', 'plot7', 'plot8', 'plot9', 'plotl0']
N = len(filenames)
Y = int(math.sqrt(N))
X = int(N / Y) + 1
fig = plt.figure()
for i in range(1,N+1):
axes.append(fig.add_subplot(X, Y, i))
axes[i-1].text(0.5, 0.5, str('Test'))
axes[i-1].axis('off')
plt.show()

Related

Simulate a rotating equal triangle by Python

can anyone help me, i stuck at the last step
[]
this is my code. then for the last step to rotate it, i didnt know what should i do to rotate the triangle
This is the perfect case for an animation:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
from matplotlib.animation import FuncAnimation
# Enter x and y coordinates of points and colors
a=(0,0.5);b=(0.43,-0.25);c=(-0.43,-0.25)
center=(0,0)
n = 3;r=1.0
theta = np.arange(0,360+(360/(n)),360/(n))
to=np.arange(0,2*np.pi,0.01)
x = r * np.cos(np.radians(theta))
y = r * np.sin(np.radians(theta))
xo = r * np.cos(to); yo = r * np.sin(to)
fig, ax = plt.subplots()
ax.plot(xo,yo)
# create artists: they will be used to update the position
# of the points being rendered
triangle, = ax.plot(x,y)
vertices = ax.scatter(x,y)
lim = r * 1.25
ax.set_xlim([-lim, lim]);ax.set_ylim([-lim, lim])
ax.set_aspect("equal")
w = 2
T = 2 * np.pi / w
# this defines the time steps of the animation
dt = np.linspace(0, 10 * T, num=500)
def animate(i):
x = r * np.cos(np.radians(theta) + w * dt[i])
y = r * np.sin(np.radians(theta) + w * dt[i])
# update the position of the points to be rendered
triangle.set_data(x, y)
vertices.set_offsets(np.stack([x, y]).T)
ax.set_title("Rotation #%s" % int(w * dt[i] / (2 * np.pi) + 1))
ani = FuncAnimation(fig, animate, frames=len(dt), repeat=False)
plt.show()
Check this out..
from IPython import display
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
# Enter x and y coordinates of points and colors
a=(0,0.5);b=(0.43,-0.25);c=(-0.43,-0.25)
center=(0,0)
n = 3;r=1.0
theta = np.arange(0,360+(360/(n)),360/(n))
w = 2
T = 2*np.pi/w
dt = np.linspace(0, 10*T, num=10) #increase num for more finely distributed rotations.
for d in dt:
to=np.arange(0,2*np.pi,0.01)
x = r*np.sin(np.radians(theta + d))
y=r*np.cos(np.radians(theta + d))
xo=r*np.sin(to);yo=r*np.cos(to)
plt.plot(xo,yo)
plt.plot(x,y)
plt.scatter(x,y)
plt.xlim([-1, 1]);plt.ylim([-1,1])

FuncAnimation how to update text after each iteration

I am trying to create an animation of a Monte-Carlo estimation of the number pi, for each iteration I would like the numerical estimation to be in text on the plot, but the previous text is not removed and makes the values unreadable. I tried Artist.remove(frame) with no success. The plot is done with Jupiter Notebook.
#Enable interactive plot
%matplotlib notebook
import math
from matplotlib.path import Path
from matplotlib.animation import FuncAnimation
from matplotlib.path import Path
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
from matplotlib.artist import Artist
N = 10000
#create necessary arrays
x = np.arange(0,N)
y = np.zeros(N)
#set initial points to zero
inHull = 0
def inCircle(point):
#the function is given a point in R^n
#returns a boolean stating if the norm of the point is smaller than 1.
if np.sum(np.square(point)) <= 1:
return True
else:
return False
#iterate over each point
for i in range(N):
random_point = np.random.rand(2)*2 - 1
#determine if the point is inside the hull
if inCircle(random_point):
inHull += 1
#we store areas in array y.
y[i] = (inHull*4)/(i+1)
fig = plt.figure()
ax = plt.subplot(1, 1, 1)
data_skip = 20
def init_func():
ax.clear()
plt.xlabel('n points')
plt.ylabel('Estimated area')
plt.xlim((x[0], x[-1]))
plt.ylim((min(y)- 1, max(y)+0.5))
def update_plot(i):
ax.plot(x[i:i+data_skip], y[i:i+data_skip], color='k')
ax.scatter(x[i], y[i], color='none')
Artist.remove(ax.text(N*0.6, max(y)+0.25, "Estimation: "+ str(round(y[i],5))))
ax.text(N*0.6, max(y)+0.25, "Estimation: "+ str(round(y[i],5)))
anim = FuncAnimation(fig,
update_plot,
frames=np.arange(0, len(x), data_skip),
init_func=init_func,
interval=20)
plt.show()
Thank you.
As you have already done in init_func, you should clear the plot in each iteration with ax.clear(). Then it is necessary to edit slighlty the plot function:
ax.plot(x[i:i+data_skip], y[i:i+data_skip], color='k')
And finally you have to fix x axis limits in each iteration with ax.set_xlim(0, N).
Complete Code
#Enable interactive plot
%matplotlib notebook
import math
from matplotlib.path import Path
from matplotlib.animation import FuncAnimation
from matplotlib.path import Path
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
from matplotlib.artist import Artist
N = 10000
# create necessary arrays
x = np.arange(0, N)
y = np.zeros(N)
# set initial points to zero
inHull = 0
def inCircle(point):
# the function is given a point in R^n
# returns a boolean stating if the norm of the point is smaller than 1.
if np.sum(np.square(point)) <= 1:
return True
else:
return False
# iterate over each point
for i in range(N):
random_point = np.random.rand(2)*2 - 1
# determine if the point is inside the hull
if inCircle(random_point):
inHull += 1
# we store areas in array y.
y[i] = (inHull*4)/(i + 1)
fig = plt.figure()
ax = plt.subplot(1, 1, 1)
data_skip = 20
txt = ax.text(N*0.6, max(y) + 0.25, "")
def init_func():
ax.clear()
plt.xlabel('n points')
plt.ylabel('Estimated area')
plt.xlim((x[0], x[-1]))
plt.ylim((min(y) - 1, max(y) + 0.5))
def update_plot(i):
ax.clear()
ax.plot(x[:i + data_skip], y[:i + data_skip], color = 'k')
ax.scatter(x[i], y[i], color = 'none')
ax.text(N*0.6, max(y) + 0.25, "Estimation: " + str(round(y[i], 5)))
ax.set_xlim(0, N)
anim = FuncAnimation(fig,
update_plot,
frames = np.arange(0, len(x), data_skip),
init_func = init_func,
interval = 20)
plt.show()
Animation

Monte Carlo simulation programming exercise [duplicate]

I can evaluate the value of pi using different data points by Python. But for each repeat I want to plot the scatter plot like this:
My python code for finding pi using monte carlo method is :
from random import *
from math import sqrt
inside=0
n=10**6
for i in range(0,n):
x=random()
y=random()
if sqrt(x*x+y*y)<=1:
inside+=1
pi=4*inside/n
print (pi)
If you get errors about the backend use this:
import matplotlib as mp
mp.use('Tkagg')
Which will set the backend to TkAgg, which uses the Tkinter user interface toolkit.
import numpy as np
import matplotlib.pyplot as plt
n=1e3
x = 1-2*np.random.random(int(n))
y = 1-2.*np.random.random(int(n))
insideX, insideY = x[(x*x+y*y)<=1],y[(x*x+y*y)<=1]
outsideX, outsideY = x[(x*x+y*y)>1],y[(x*x+y*y)>1]
fig, ax = plt.subplots(1)
ax.scatter(insideX, insideY, c='b', alpha=0.8, edgecolor=None)
ax.scatter(outsideX, outsideY, c='r', alpha=0.8, edgecolor=None)
ax.set_aspect('equal')
fig.show()
To further elaborate Robbie's code:
import numpy as np
import matplotlib.pyplot as plt
n = 1000
xy = np.random.uniform(-1, 1, 2 * n).reshape((2, n))
in_marker = xy[0]**2 + xy[1]**2 <= 1
pi = np.sum(in_marker) / n * 4
in_xy = xy[:, in_marker]
out_xy = xy[:, ~in_marker]
fig, ax = plt.subplots(1)
ax.scatter(*in_xy,c='b')
ax.scatter(*out_xy,c='r')
ax.set_aspect('equal')
fig.show()
building from your code, this may get you started:
import matplotlib.pyplot as plt
from random import random
inside = 0
n = 10**3
x_inside = []
y_inside = []
x_outside = []
y_outside = []
for _ in range(n):
x = random()
y = random()
if x**2+y**2 <= 1:
inside += 1
x_inside.append(x)
y_inside.append(y)
else:
x_outside.append(x)
y_outside.append(y)
pi = 4*inside/n
print(pi)
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(x_inside, y_inside, color='g', marker='s')
ax.scatter(x_outside, y_outside, color='r', marker='s')
fig.show()
although i prefer this answer that uses numpy from the start...
Here is a variation on hiro protagonist's code, using random.uniform() to allow for random numbers between -1.0 and 1.0, allowing all the points to be plotted, and not just 1/4 of it (not the most elegant code, but it is spelled-out to learn the basics of the Monte Carlo Simulation):
import matplotlib.pyplot as plt
import random
inside = 0
n = 10**3
x_inside = []
y_inside = []
x_outside = []
y_outside = []
for _ in range(n):
x = random.uniform(-1.0,1.0)
y = random.uniform(-1.0,1.0)
if x**2+y**2 <= 1:
inside += 1
x_inside.append(x)
y_inside.append(y)
else:
x_outside.append(x)
y_outside.append(y)
To estimate pi, the points in the circle correspond to the area of the circle enclosing it (pi*radius^2) and the total points correspond to the area of the square enclosing it (2*radius)^2. So this translates into:
(points in the circle)/(total points) = (pi*radius^2)/(2*radius)^2
Solving for pi, the equation becomes:
pi=4*(points in the circle)/(total points)
pi = 4*inside/n
print(pi)
Plot the points inside and outside the circle:
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(x_inside, y_inside, color='g', marker='s')
ax.scatter(x_outside, y_outside, color='r', marker='s')
fig.show()
Plot of points inside and outside the circle

Plotting Pi using Monte Carlo Method

I can evaluate the value of pi using different data points by Python. But for each repeat I want to plot the scatter plot like this:
My python code for finding pi using monte carlo method is :
from random import *
from math import sqrt
inside=0
n=10**6
for i in range(0,n):
x=random()
y=random()
if sqrt(x*x+y*y)<=1:
inside+=1
pi=4*inside/n
print (pi)
If you get errors about the backend use this:
import matplotlib as mp
mp.use('Tkagg')
Which will set the backend to TkAgg, which uses the Tkinter user interface toolkit.
import numpy as np
import matplotlib.pyplot as plt
n=1e3
x = 1-2*np.random.random(int(n))
y = 1-2.*np.random.random(int(n))
insideX, insideY = x[(x*x+y*y)<=1],y[(x*x+y*y)<=1]
outsideX, outsideY = x[(x*x+y*y)>1],y[(x*x+y*y)>1]
fig, ax = plt.subplots(1)
ax.scatter(insideX, insideY, c='b', alpha=0.8, edgecolor=None)
ax.scatter(outsideX, outsideY, c='r', alpha=0.8, edgecolor=None)
ax.set_aspect('equal')
fig.show()
To further elaborate Robbie's code:
import numpy as np
import matplotlib.pyplot as plt
n = 1000
xy = np.random.uniform(-1, 1, 2 * n).reshape((2, n))
in_marker = xy[0]**2 + xy[1]**2 <= 1
pi = np.sum(in_marker) / n * 4
in_xy = xy[:, in_marker]
out_xy = xy[:, ~in_marker]
fig, ax = plt.subplots(1)
ax.scatter(*in_xy,c='b')
ax.scatter(*out_xy,c='r')
ax.set_aspect('equal')
fig.show()
building from your code, this may get you started:
import matplotlib.pyplot as plt
from random import random
inside = 0
n = 10**3
x_inside = []
y_inside = []
x_outside = []
y_outside = []
for _ in range(n):
x = random()
y = random()
if x**2+y**2 <= 1:
inside += 1
x_inside.append(x)
y_inside.append(y)
else:
x_outside.append(x)
y_outside.append(y)
pi = 4*inside/n
print(pi)
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(x_inside, y_inside, color='g', marker='s')
ax.scatter(x_outside, y_outside, color='r', marker='s')
fig.show()
although i prefer this answer that uses numpy from the start...
Here is a variation on hiro protagonist's code, using random.uniform() to allow for random numbers between -1.0 and 1.0, allowing all the points to be plotted, and not just 1/4 of it (not the most elegant code, but it is spelled-out to learn the basics of the Monte Carlo Simulation):
import matplotlib.pyplot as plt
import random
inside = 0
n = 10**3
x_inside = []
y_inside = []
x_outside = []
y_outside = []
for _ in range(n):
x = random.uniform(-1.0,1.0)
y = random.uniform(-1.0,1.0)
if x**2+y**2 <= 1:
inside += 1
x_inside.append(x)
y_inside.append(y)
else:
x_outside.append(x)
y_outside.append(y)
To estimate pi, the points in the circle correspond to the area of the circle enclosing it (pi*radius^2) and the total points correspond to the area of the square enclosing it (2*radius)^2. So this translates into:
(points in the circle)/(total points) = (pi*radius^2)/(2*radius)^2
Solving for pi, the equation becomes:
pi=4*(points in the circle)/(total points)
pi = 4*inside/n
print(pi)
Plot the points inside and outside the circle:
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(x_inside, y_inside, color='g', marker='s')
ax.scatter(x_outside, y_outside, color='r', marker='s')
fig.show()
Plot of points inside and outside the circle

Plotting multiple 2d curves with matplotlib in 3d

I'm trying to plot a fourier series of a triangular wave with matplotlib.
I've managed to plot the elements on top of each other in 2d, but I'd like to plot them in 3d instead, as that makes it more easy to see.
Here's the plot my current code generates
triangular wave
Here's an image of what I'd like to plot, but for the triangular wave instead of a square wave.
square wave
Here's the current code
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
import scipy as sp
x1 = np.arange(0, L / 2.0, 0.01)
x2 = np.arange(L/2.0,L,0.01)
x = np.concatenate((x1,x2))
y1 = 2* x1
y2 = 2*(1 - x2)
triangle_y = np.concatenate((y1,y2))
L = 1;
def triangle_function(x, L):
'''given x, returns y as defined by the triangle function defined in the range 0 <= x <= L
'''
if x< 0:
print 'Error: the value of x should be between 0 and L'
y = None
elif x<L/2.0:
y = 2*x
elif x <= L:
y = 2*(1 - x)
else:
print 'Error: the value of x should be between 0 and L'
y = None
return y
def projection_integrand(x, n, L):
'''The inputs to the function are:
x ---> vector of x values.
n ---> the n-number associated to the sine functions
L --> L, upper limit of integration
'''
sine_function = np.sin(n * np.pi * x / np.double(L)) # this is the sine function sin(n*pi*x/L)
integrand = (2.0 / L) * sine_function * triangle_function(x, L) # this is the product of the two functions, with the 2/L factor
#return(sine_function*f_x)
return integrand
from scipy.integrate import quad
n_max = 5
x = np.arange(0, L, 0.01) # x vector
triangle_approx = np.zeros(len(x))
func_list = []
for n in range(1, n_max + 1):
c_n = quad(projection_integrand, 0, L, (n, L))
sin_arg = n* np.pi*x/np.double(L)
current = c_n[0]* np.sin(sin_arg)
triangle_approx += current
func_list.append(current)
from mpl_toolkits.mplot3d import Axes3D
plt.hold(True)
plt.plot(x, func_list[0])
plt.plot(x, func_list[1])
plt.plot(x, func_list[2])
plt.plot(x, func_list[3])
plt.plot(x, func_list[4])
plt.plot(x, triangle_approx)
plt.plot(x, triangle_y)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('approximating the triangle function as a sum of sines, n = 1 ...' + str(n_max))
plt.legend(['approximation', 'triangle function'])
plt.show()
I have found a way based on this matplotlib official example.
Add this code below your code and you will get something close to what you want:
fig = plt.figure()
ax = fig.gca(projection='3d')
z = np.array([1.0 for point in x])
for n, armonic in enumerate(func_list):
ax.plot(x, armonic, z*n, label='armonic{}'.format(n))
ax.legend()
plt.show()

Categories

Resources