Python evenly scatter coordinates around fixed center based on distance - python

I want to scatter a lot of datapoints around a centre one (2.5,2.5) based on a given distance for each datapoint to the centre.
How do I do that and also evade duplicates/scatter them evenly around the centre?
Thanks in advance

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(6, 6))
N = 120
angles = np.linspace(0, 2 * np.pi, N)
c_x, c_y = (2.5, 2.5)
x_s, y_s = [], []
distances = list(np.arange(0, 5.5, 0.5))
for distance in distances:
for angle in angles:
x_s.append(c_x + distance * np.cos(angle))
y_s.append(c_y + distance * np.sin(angle))
plt.scatter(x_s, y_s, c="b", s=4)
plt.show()

To clarify, I wanted one point for each distance, and then the next one offset by 180 or 90 degrees. But I managed to complete it based on the code provided by Gustav Rasmussen:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(6, 6))
#default
N = 50
angles = np.linspace(0, 2 * np.pi, N)
c_x, c_y = (2.5, 2.5)
x_s, y_s = [], []
distances = list(np.arange(0, 5.5, 0.01))
i = angles.size/4
for distance in distances:
x_s.append(c_x + distance * np.cos(i))
y_s.append(c_y + distance * np.sin(i))
i += i
plt.scatter(x_s, y_s, c="b", s=4)
plt.show()
Here we can see 550 distances, displayed with the next one being displayed offset by approximately 90 degrees.
Last mention: When dealing with a dataset of bigger deviations it is better to do i = angles.size/2 as to keep the output somewhat circled

import cmath
import numpy as np
from matplotlib import pyplot as plt
from itertools import starmap
c = np.array(list(starmap(cmath.rect, [(v//40+1, v*np.pi/20) for v in range(120)])))
x = c.real+2.5
y = c.imag+2.5
plt.scatter(x, y)

Related

plotting triangle inside circle

I am creating a circle and want to then develop a right-angle triangle, or any isometric form of a triangle. Whereby, I can take any line distance between two edges of the circle and draw arrows toward the peak point.
For example:
import numpy as np
import matplotlib.pyplot as plt
import math
theta = np.linspace(0, 2*np.pi, 100)
x1 = np.cos(theta)
y1 = np.sin(theta)
plt.plot(x1, y1)
for i in [min(y1), max(y1)]:
plt.plot(0, i, '-ok', mfc='C1', mec='C1')
plt.arrow(0,min(y1),0,2*max(y1),width=0.001,color='red',head_starts_at_zero=False)
plt.arrow(min(x1), (1/2)*min(y1), 2*max(x1), (1/2)*max(y1),width=0.001,color='red',head_starts_at_zero=False)
However, I cannot accurately get the distance between two points correct when i aim for any form of a triangle.
However, I can easily achieve it when setting y to 0 in the second arrow. Perhaps there is a general equation to do this?
Like this:
import numpy as np
import matplotlib.pyplot as plt
import math
theta = np.linspace(0, 2*np.pi, 100)
x1 = np.cos(theta)
y1 = np.sin(theta)
plt.plot(x1, y1)
x = np.array([0,120,240,0])
y = np.array([0,120,240,0])
x = np.cos( x * np.pi / 180 )
y = np.sin( y * np.pi / 180 )
plt.plot( x, y, color='red' )
plt.show()
Output:
In fact, if you choose ANY three angles, you'll get an inscribed triangle.

How to rotate a function by a desired angle?

How to rotate a function by the desired angle (for instance, 30 degrees)?
import matplotlib.pyplot as plt
import numpy as np
from numpy import exp, sin
def g(y):
return exp(-y)*sin(4*y)
y = np.linspace(0, 1.8, 501)
values = g(y)
fig, ax = plt.subplots(figsize=(5,5))
plt.plot(y, values)
plt.show()
Using the cosine and sine of the angle, you can create a rotation matrix. Multiplying each point (y, g(y)) with that matrix create a rotation around 0,0.
Here is some Python/numpy code to illustrate how everything could work together:
import matplotlib.pyplot as plt
import numpy as np
def g(y):
return np.exp(-y) * np.sin(4 * y)
y = np.linspace(0, 1.8, 501)
values = g(y)
theta = np.radians(30)
c, s = np.cos(theta), np.sin(theta)
rot_matrix = np.array(((c, s), (-s, c)))
xy = np.array([y, values]).T # rot_matrix
fig, ax = plt.subplots(figsize=(5, 5))
plt.plot(y, values)
plt.plot(xy[:, 0], xy[:, 1])
plt.axis('equal') # so angles on the screen look like the real angles
plt.show()
PS: To rotate around another point, first subtract the rotation center, do the rotation and then add it again:
center = np.array([0.9, 0])
xy = (np.array([y, values]).T - center) # rot_matrix + center

How to draw circles on the perimeter of a circle?

I'm trying to plot something like this:
I don't know how to find the center of smaller circles in for loops. First, I've tried to plot it with smaller number of circles(for example 2) but I don't know why the smaller circles are semi-circles??
My try:
import numpy as np
import matplotlib.pyplot as plt
r = 2, h = 1, k = 1
axlim = r + np.max((abs(h),np.max(abs(k))))
x = np.linspace(-axlim, axlim, 100)
X,Y = np.meshgrid(x,x)
F = (X-h)**2 + (Y-k)**2 - r**2
plt.contour(X,Y,F,0)
F1 = (X-(h+r))**2 + (Y-k)**2 - (r/3)**2
plt.contour(X,Y,F1,0)
F2 = (X-h)**2 + (Y-(k+r))**2 - (r/3)**2
plt.contour(X,Y,F2,0)
plt.gca().set_aspect('equal')
plt.axis([-4*r, 4*r, -4*r,4*r])
# plt.axis('off')
plt.show()
The output:
Sine, cosine and an angle evenly divided over the range 0, 2picould be used:
import numpy as np
import matplotlib.pyplot as plt
num_circ = 7
rad_large = 7
rad_small = 6
thetas = np.linspace(0, 2 * np.pi, num_circ, endpoint=False)
fig, ax = plt.subplots()
ax.add_patch(plt.Circle((0, 0), rad_large, fc='none', ec='navy'))
for theta in thetas:
ax.add_patch(plt.Circle((rad_large * np.cos(theta), rad_large * np.sin(theta),), rad_small, fc='none', ec='crimson'))
ax.autoscale_view() # calculate the limits for the x and y axis
ax.set_aspect('equal') # show circles as circles
plt.show()

How to Obtain Coordinates for a Hemisphere in Python

Currently, I have some Python code to obtain equidistant points on the surface of a sphere. Now, I want to edit this code to obtain equidistant points on the surface of a hemisphere. I assume that there is some simple parameter I need to change, but I am still a Python novice.
My code:
from numpy import pi, cos, sin, arccos, arange
import mpl_toolkits.mplot3d
import matplotlib.pyplot as plt
num_pts = 10000
indices = arange(0, num_pts, dtype=float) + 0.5
phi = arccos(1 - 2*indices/num_pts)
theta = pi * (1 + 5**0.5) * indices
x, y, z = cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi);
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 75
fig_size[1] = 75
plt.rcParams["figure.figsize"] = fig_size
plt.figure().add_subplot(111, projection='3d').scatter(x, y, z, s=1);
plt.show()
#saves the coordinates
import numpy as np
import sys
points = np.transpose(np.array([x,y,z]))
#np.savetxt(sys.stdout, points, fmt="%.6f")
np.savetxt('data.txt', points, fmt="%.6f")
Thank you for your help!
Simplest way from what you have:
X = np.stack((x,y,z)) # stack up all coordinates
mask = X[-1]>=0 # mask of elements where z coordinate larger than 0
x,y,z = X.T[mask].T # mask out the elements where z coordinate < 0
Then plot those points. you'll get a hemisphere I figure

Plot equation showing a circle

The following formula is used to classify points from a 2-dimensional space:
f(x1,x2) = np.sign(x1^2+x2^2-.6)
All points are in space X = [-1,1] x [-1,1] with a uniform probability of picking each x.
Now I would like to visualize the circle that equals:
0 = x1^2+x2^2-.6
The values of x1 should be on the x-axis and values of x2 on the y-axis.
It must be possible but I have difficulty transforming the equation to a plot.
You can use a contour plot, as follows (based on the examples at http://matplotlib.org/examples/pylab_examples/contour_demo.html):
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1.0, 1.0, 100)
y = np.linspace(-1.0, 1.0, 100)
X, Y = np.meshgrid(x,y)
F = X**2 + Y**2 - 0.6
plt.contour(X,Y,F,[0])
plt.show()
This yields the following graph
Lastly, some general statements:
x^2 does not mean what you think it does in python, you have to use x**2.
x1 and x2 are terribly misleading (to me), especially if you state that x2 has to be on the y-axis.
(Thanks to Dux) You can add plt.gca().set_aspect('equal') to make the figure actually look circular, by making the axis equal.
The solution of #BasJansen certainly gets you there, it's either very inefficient (if you use many grid points) or inaccurate (if you use only few grid points).
You can easily draw the circle directly. Given 0 = x1**2 + x**2 - 0.6 it follows that x2 = sqrt(0.6 - x1**2) (as Dux stated).
But what you really want to do is to transform your cartesian coordinates to polar ones.
x1 = r*cos(theta)
x2 = r*sin(theta)
if you use these substitions in the circle equation you will see that r=sqrt(0.6).
So now you can use that for your plot:
import numpy as np
import matplotlib.pyplot as plt
# theta goes from 0 to 2pi
theta = np.linspace(0, 2*np.pi, 100)
# the radius of the circle
r = np.sqrt(0.6)
# compute x1 and x2
x1 = r*np.cos(theta)
x2 = r*np.sin(theta)
# create the figure
fig, ax = plt.subplots(1)
ax.plot(x1, x2)
ax.set_aspect(1)
plt.show()
Result:
How about drawing x-values and calculating the corresponding y-values?
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 100, endpoint=True)
y = np.sqrt(-x**2. + 0.6)
plt.plot(x, y)
plt.plot(x, -y)
produces
This can obviously be made much nicer, but this is only for demonstration...
# x**2 + y**2 = r**2
r = 6
x = np.linspace(-r,r,1000)
y = np.sqrt(-x**2+r**2)
plt.plot(x, y,'b')
plt.plot(x,-y,'b')
plt.gca().set_aspect('equal')
plt.show()
produces:
Plotting a circle using complex numbers
The idea: multiplying a point by complex exponential () rotates the point on a circle
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
num_pts=20 # number of points on the circle
ps = np.arange(num_pts+1)
# j = np.sqrt(-1)
pts = np.exp(2j*np.pi/num_pts *(ps))
fig, ax = plt.subplots(1)
ax.plot(pts.real, pts.imag , '-o')
ax.set_aspect(1)
plt.show()

Categories

Resources