Python 中的球形颜色曲面图

问题描述 投票:0回答:1

我正在尝试重新创建这样的情节: enter image description here 但球体表面的颜色与此类似: enter image description here

因此球体的顶部和底部(Z 轴)应为蓝色,前后(X 轴)应为红色,左侧和右侧(Y 轴)应为绿色。

我的想法是使用球体表面上点的XYZ坐标作为RGB值,例如如果坐标为1,0,0(球体背面的尖端),则1,0,0的RGB值=红色。

但是,当我尝试绘制此图时,表面没有所需的 RGB 颜色,而是具有未知的标量值: enter image description here

我做错了什么?

这是生成上图的我的代码:

import plotly.graph_objects as go
import numpy as np
from matplotlib import cm

# Create a grid of theta and phi values
theta = np.linspace(0, 2 * np.pi, 100)
phi = np.linspace(0, np.pi, 100)

# Create the meshgrid
theta, phi = np.meshgrid(theta, phi)

# Define the radius of the sphere
r = 1

# Convert spherical coordinates to Cartesian coordinates
x = r * np.sin(phi) * np.cos(theta)
y = r * np.sin(phi) * np.sin(theta)
z = r * np.cos(phi)

# Combine absolute values of X, Y, and Z to get final color
color = np.stack([np.abs(x), np.abs(y), np.abs(z)], axis=1)

# Create the plotly figure
fig = go.Figure(data=[go.Surface(x=x, y=y, z=z, surfacecolor=color)])

# Update layout
fig.update_layout(scene=dict(aspectmode="data"))

# Show the interactive plot
fig.show()
python colors plotly spherical-coordinate
1个回答
0
投票

感谢 Iburakov 的评论,我能够通过从顶点构造一个球体,然后为每个顶点单独分配一个 RGB 值来解决问题:

import numpy as np
import plotly.graph_objects as go

N = 100  # Sphere resolution (both rings and segments, can be separated to different constants)
theta, z = np.meshgrid(np.linspace(-np.pi, np.pi, N), np.linspace(-1, 1, N))
r = np.sqrt(1 - z ** 2)
x = r * np.cos(theta)
y = r * np.sin(theta)
x = x.ravel()
y = y.ravel()
z = z.ravel()

# Triangle indices
indices = np.arange(N * (N - 1) - 1)
i1 = np.concatenate([indices, (indices // N + 1) * N + (indices + 1) % N])
i2 = np.concatenate([indices + N, indices // N * N + (indices + 1) % N])
i3 = np.concatenate([(indices // N + 1) * N + (indices + 1) % N, indices])

# Calculate individual RGB values for each vertex based on x, y, z coordinates
rgb_values = np.stack([np.abs(x), np.abs(y), np.abs(z)], axis=-1)

# Create the Plotly figure
fig = go.Figure(data=[
    go.Mesh3d(
        x=x,
        y=y,
        z=z,
        vertexcolor=rgb_values,  # Specify RGB values for each vertex
        i=i1,
        j=i2,
        k=i3
    )
])

这会产生我想要的输出: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.