Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

python - Scatter Plot 3D with labels and spheres

I am trying to make a scatter plot with some data points (x,y,z,radius) and this is my result up to now:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

x = np.random.rand(20)
y = np.random.rand(20)
z = np.random.rand(20)
r = np.random.rand(20)


plt.rc('text', usetex=True)
plt.rcParams['text.latex.preamble']=[r"usepackage{amsmath}"]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(x, y, z, s=np.pi*r**2*100, c='blue', alpha=0.75)

ax.set_xlabel(r'$x$ $left[frac{ext{Mpc}}{h}
ight]$')
ax.set_ylabel(r'$y$ $left[frac{ext{Mpc}}{h}
ight]$')
ax.set_zlabel(r'$z$ $left[frac{ext{Mpc}}{h}
ight]$')

#plt.savefig('spheres.png')

plt.show()

http://www.file-upload.net/download-9033814/spheres.png.html

How can I improve this plot in order to have no overlap of the x- and y-labels with the tics?

And it there a possibility to make spheres instead of areas in this 3D-plot?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create a plot that uses spheres instead of circle markers by drawing one at each location as described here. Here's an example:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def drawSphere(xCenter, yCenter, zCenter, r):
    #draw sphere
    u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
    x=np.cos(u)*np.sin(v)
    y=np.sin(u)*np.sin(v)
    z=np.cos(v)
    # shift and scale sphere
    x = r*x + xCenter
    y = r*y + yCenter
    z = r*z + zCenter
    return (x,y,z)


x = 10*np.random.rand(20)
y = 10*np.random.rand(20)
z = 10*np.random.rand(20)
r = np.random.rand(20)


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# draw a sphere for each data point
for (xi,yi,zi,ri) in zip(x,y,z,r):
    (xs,ys,zs) = drawSphere(xi,yi,zi,ri)
    ax.plot_wireframe(xs, ys, zs, color="r")


plt.show()

spheres in 3D plot

To fix the label positioning problem try adding a second line as described here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...