X values out of bound in Axes3D - python-3.x

I'm plotting a 3D chart which looks like this
When I try to limit the axis, the values go out of bounds
What am I doing wrong?
the code:
fig = plt.figure(figsize=(10,10))
ax = Axes3D(fig)
ax.set_xlim3d(0,1000)
#ax.set_ylim3d(0,1000)
#ax.set_zlim3d(0,5000)
Y = 'allocated_time_on_page'
X = 'allocated_actions'
Z = 'avg_days_between_visits'
y = df_try[Y]
x = df_try[X]
z = df_try[Z]
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.set_zlabel(Z)
g = ax.scatter(x, y, z, marker='o',depthshade=True,c=df_try['logo_renewal'],alpha=.4)
#g = ax.scatter(x, y, z, marker='o',depthshade=True,c=df_try['proba'],cmap='RdYlGn',alpha=.4)
legend = ax.legend(*g.legend_elements(), loc="lower center", title="X Values", borderaxespad=-10, ncol=4)
ax.add_artist(legend)
plt.show()

Related

Uniformly distribute points in 4D

I am trying to distribute points onto a 4D surface. I have an implementation that evenly distributes data points onto a 3D surface octant.
n_samples = 100
N = int(np.floor(np.sqrt(0.25+2*n_samples) -0.5))
phis = np.linspace(start=0, stop=0.25*np.pi, num=N)
# points = np.empty((int(N*(N+1)/2), 3))
points = []
for n in range(1,N+1):
phi = phis[n-1]
for theta in np.linspace(start=0, stop=0.5*np.pi, num=n):
x = np.sin(phi)*np.cos(theta)
y = np.sin(phi)*np.sin(theta)
z = np.cos(phi)
points.append([x,y,z])
points = np.array(points)
df = pd.DataFrame(points, columns=['x', 'y', 'z'])
fig = px.scatter_3d(df, x='x', y='y', z='z')
fig.show()
I am having difficulties in extending this to a 4D surface and visualizing it. Am I thinking about this correct? I need all my points evenly distributed in an octant. For 3D, I am leveraging the quadratic equation to distribute the points, for 4D, I am leveraging the cubic equation for the same.
n_samples = 100
poly = [1, 1.5, 0.5, 3*n_samples]
N = int(np.floor(-np.real(np.roots(poly)[0])) - 1)
phi_1s = np.linspace(start=0, stop=0.25*np.pi, num=N)
# points = np.empty((int(N*(N+1)/2), 3))
points = []
for n in range(1,N+1):
phi_1 = phi_1s[n-1]
for phi_2 in np.linspace(start=0, stop=0.25*np.pi, num=n):
for phi_3 in np.linspace(start=0, stop=0.5*np.pi, num=n):
x1 = np.cos(phi_1)
x2 = np.sin(phi_1)*np.cos(phi_2)
x3 = np.sin(phi_1)*np.sin(phi_2)*np.cos(phi_3)
x4 = np.sin(phi_1)*np.sin(phi_2)*np.sin(phi_3)
points.append([x1, x2, x3, x4])
points = np.array(points)
df = pd.DataFrame(points, columns=['x', 'y', 'z', 'c'])
fig = px.scatter_3d(df, x='x', y='y', z='z', color='c')
Any thoughts on this is appreciated..

Rotating seaborn lineplot

I would like to rotate seaborn.lineplot, so height would be on the y axis and weighted PAVD would be on x.
sns.lineplot(data = df, y = "weightedPAVD", x = "# height", ci = 10, color = "darkgreen")
plt.show()
However, if I change x and y, the figure is messed up.
sns.lineplot(data = df, x = "weightedPAVD", y = "# height", ci = 10, color = "darkgreen")
plt.show()
How to fix this?
With seaborn v0.12+, add orient="y" to sort/aggregate/connect over the y variable instead of the x variable.

Using colormap in cycle (python)

How to edit the for cycles under #ax5 and #ax6 to plot graphs in the same fashion? Now, the lower figure has no colour transit, as opposed to the upper one. The colour transit appears in the lower figure after increasing of dpi, however, some unwanted stuff also appears. Is there a scalling problem? Thank you
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
import math
fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [8, 8]
# Function for plotting parallels to curves
def get_parallels(length=.1):
px, py = [], []
for idx in range(len(x)-1):
x0, y0, xa, ya = x[idx], y[idx], x[idx+1], y[idx+1]
dx, dy = xa-x0, ya-y0
norm = math.hypot(dx, dy) * 1/length
dx /= norm
dy /= norm
px.append(x0-dy)
py.append(y0+dx)
return px, py
def offset(x,y, o):
""" Offset coordinates given by array x,y by o """
X = np.c_[x,y].T
m = np.array([[0,-1],[1,0]])
R = np.zeros_like(X)
S = X[:,2:]-X[:,:-2]
R[:,1:-1] = np.dot(m, S)
R[:,0] = np.dot(m, X[:,1]-X[:,0])
R[:,-1] = np.dot(m, X[:,-1]-X[:,-2])
On = R/np.sqrt(R[0,:]**2+R[1,:]**2)*o
Out = On+X
return Out[0,:], Out[1,:]
dpi = 20
def offset_curve(ax, x,y, o):
""" Offset array x,y in data coordinates
by o in points """
trans = ax.transData.transform
inv = ax.transData.inverted().transform
X = np.c_[x,y]
Xt = trans(X)
xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72. )
Xto = np.c_[xto, yto]
Xo = inv(Xto)
return Xo[:,0], Xo[:,1]
fig = plt.figure(constrained_layout=True)
gs = GridSpec(3, 6, figure=fig)
ax5 = fig.add_subplot(gs[1, 3:6])
ax6 = fig.add_subplot(gs[2, :3])
ax7 = fig.add_subplot(gs[2, 3:6])
cmap = plt.get_cmap('Greys_r')
# ax5
x = np.linspace(-1, 1, 100)
y = -x**2
ax5.set_ylim(-1.02, 0.3)
width_l = ax5.get_ylim()[1] - ax5.get_ylim()[0]
for t in np.linspace(0, 1, 40):
length = -0.1*width_l*t
ax5.plot(*get_parallels(length=length), color=cmap(t/2 + 0.25))
# ax6
x = np.linspace(-3, 3, 100)
y = -(1/4*x**4 - 1.6*x**2)
ax6.plot(x, y)
ax6.set_xlim(ax6.get_xlim()[0]-0.5, ax6.get_xlim()[1]+0.5)
ax6.scatter(1/2*(ax6.get_xlim()[0] + ax6.get_xlim()[1]), 1.2, marker = 'o', s=900, facecolors='none')
lines = []
width_l = ax6.get_ylim()[1] - ax6.get_ylim()[0]
for t in np.linspace(0, 1, 40):
l, = ax6.plot(x, y - t * 0.1 * width_l, color=cmap(t/2 + 0.25))
lines.append(l)
def plot_rainbow(event=None):
x0 = x
y0 = y
for i in range(len(lines)):
xx, yy = offset_curve(ax, x0, y0, -width_l)
lines[i].set_data(xx, yy)
lines[i].set_linewidth(1.1*width_l)
x0 = xx
y0 = yy
plot_rainbow()
fig.canvas.mpl_connect("resize_event", plot_rainbow)
fig.canvas.mpl_connect("button_release_event", plot_rainbow)
plt.savefig('fig.pdf')

How to plot the figure in the desired fashion?

How to edit this code to have the same width and colour map as in the following figure? The script is based on this question.
import numpy as np
import matplotlib.pyplot as plt
dpi = 100
def offset(x,y, o):
""" Offset coordinates given by array x,y by o """
X = np.c_[x,y].T
m = np.array([[0,-1],[1,0]])
R = np.zeros_like(X)
S = X[:,2:]-X[:,:-2]
R[:,1:-1] = np.dot(m, S)
R[:,0] = np.dot(m, X[:,1]-X[:,0])
R[:,-1] = np.dot(m, X[:,-1]-X[:,-2])
On = R/np.sqrt(R[0,:]**2+R[1,:]**2)*o
Out = On+X
return Out[0,:], Out[1,:]
def offset_curve(ax, x,y, o):
""" Offset array x,y in data coordinates
by o in points """
trans = ax.transData.transform
inv = ax.transData.inverted().transform
X = np.c_[x,y]
Xt = trans(X)
xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72. )
Xto = np.c_[xto, yto]
Xo = inv(Xto)
return Xo[:,0], Xo[:,1]
x = np.linspace(-3, 3, 100)
y = -(1/4*x**4 - 1.6*x**2)
fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)
cmap = plt.get_cmap('Greys_r')
lw = 2.
lines = []
width_l = ax.get_ylim()[1] - ax.get_ylim()[0]
for t in np.linspace(0, 1, 40):
l, = ax.plot(x, y - t * 0.1 * width_l, color=cmap(t/2 + 0.25))
lines.append(l)
def plot_rainbow(event=None):
# initialization of lists
xr, yr = 6*[None], 6*[None]
xr[0],yr[0] = offset_curve(ax, x,y, lw/2.)
xr[1],yr[1] = offset_curve(ax, x,y, -lw/2.)
xr[2],yr[2] = offset_curve(ax, xr[0],yr[0], lw)
xr[3],yr[3] = offset_curve(ax, xr[1],yr[1], -lw)
xr[4],yr[4] = offset_curve(ax, xr[2],yr[2], lw)
xr[5],yr[5] = offset_curve(ax, xr[3],yr[3], -lw)
for i in range(6):
lines[i].set_data(xr[i], yr[i])
plot_rainbow()
fig.canvas.mpl_connect("resize_event", plot_rainbow)
fig.canvas.mpl_connect("button_release_event", plot_rainbow)
plt.show()
The figure above was created by the following script:
import numpy as np
import matplotlib.pyplot as plt
import math
dpi = 100
# Function for plotting parallels to curves
def get_parallels(length=.1):
px, py = [], []
for idx in range(len(x)-1):
x0, y0, xa, ya = x[idx], y[idx], x[idx+1], y[idx+1]
dx, dy = xa-x0, ya-y0
norm = math.hypot(dx, dy) * 1/length
dx /= norm
dy /= norm
px.append(x0-dy)
py.append(y0+dx)
return px, py
fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)
cmap = plt.get_cmap('Greys_r')
x = np.linspace(-1, 1, 100)
y = -x**2
ax.set_ylim(-1.02, 0.3)
ax.scatter(1/2*(ax.get_xlim()[0] + ax.get_xlim()[1]), 0.145, marker = 'o', s=900, facecolors='none')
width_l = ax.get_ylim()[1] - ax.get_ylim()[0]
for t in np.linspace(0, 1, 40):
length = -0.1*width_l*t
ax.plot(*get_parallels(length=length), color=cmap(t/2 + 0.25))
plt.tight_layout()
plt.show()
Several curves are plotted in camp and the length is set.
I would like to have the same "shadow" for the curve in the first scrip. How to do that, please?

How to convert the shape of x.numpy() into a matrix (n,m)

I have the following dataset,
for x,y in dataset:
print(f'x= {x.numpy()}, y = {y.numpy()}')
x= [0.1408765 0.09398889], y = 0.13090546429157257
x= [0.09398889 0.13090546], y = 0.1910403072834015
x= [0.13090546 0.1910403 ], y = 0.18664830923080444
x= [0.1910403 0.18664831], y = 0.14707279205322266
x= [0.18664831 0.14707279], y = 0.12366459518671036
x= [0.14707279 0.1236646 ], y = 0.29020464420318604
x= [0.1236646 0.29020464], y = 0.4495038092136383
x= [0.29020464 0.4495038 ], y = 0.599069356918335
x= [0.4495038 0.59906936], y = 0.5652390718460083
x= [0.59906936 0.5652391 ], y = 0.5409049987792969
x= [0.5652391 0.540905 ], y = 0.5281562805175781
x= [0.540905 0.5281563], y = 0.49817198514938354
x= [0.5281563 0.498172 ], y = 0.5296282172203064
When i call x.shape i get (2,) but i would like to get a shape of (len(x), 2). How can i convert x to get the desired shape please. Similarly, the desired shape of y is (len(y), 1).
Thank you
I suppose your dataset looks like
dataset = [[[0.1408765, 0.09398889], 0.13090546429157257],
[[0.09398889, 0.13090546], 0.1910403072834015],
[[0.13090546, 0.1910403], 0.18664830923080444],
[[0.1910403, 0.18664831], 0.14707279205322266],
[[0.18664831, 0.14707279], 0.12366459518671036],
[[0.14707279, 0.1236646], 0.29020464420318604],
[[0.1236646, 0.29020464], 0.4495038092136383],
[[0.29020464, 0.4495038], 0.599069356918335],
[[0.4495038, 0.59906936], 0.5652390718460083],
[[0.59906936, 0.5652391], 0.5409049987792969],
[[0.5652391, 0.540905], 0.5281562805175781],
[[0.540905, 0.5281563], 0.49817198514938354],
[[0.5281563, 0.498172], 0.5296282172203064]]
Then you can get x like:
x = [row[0] for row in dataset]
and y:
y = [row[1] for row in dataset]
Is this what you mean?
This answer worked for me:
x = [row[0] for row in dataset]
y= [row[1] for row in dataset]
print(np.asarray(x).shape)
print(np.asarray(y).shape)

Resources