Skip to main content
 首页 » 编程设计

python matplotlib不可见点

2025年05月04日35zdz8207

我正在学习 matplolib。我尝试在表面上显示特定点,我得到以下结果:

两张截图来自同一张图。在第一个上,我们几乎看不到我要显示的点,在第二个上看不到。我想让它出现在每个人身上。这是我的代码:

import numpy as np 
from matplotlib import cm 
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
 
hours, pauses, results = [], [], [] 
 
with open('./data.txt', 'r') as f: 
    for line in f: 
        value = line.split() 
        for i, l in enumerate([hours, pauses, results]): 
            l.append(int(value[i])) 
 
for l in [hours, pauses, results]: 
    l = np.asarray(l, dtype=float) 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
m = len(hours) 
 
WP_init = 5 * np.random.rand() 
WH_init = 5 * np.random.rand() 
Z_init = 0 
for i in range(m): 
    Z_init += 1. / (2 * m) * (WH_init * hours[i] + WP_init * pauses[i] - results[i])**2 
ax.scatter(WH_init, WP_init, Z_init, s=40, c='r', marker='o') 
 
 
WH = np.arange(-5, 5, 0.25) 
WP = np.arange(-5, 5, 0.25) 
WH, WP = np.meshgrid(WH, WP) 
Z = np.zeros(np.shape(WP)) 
for i in range(m): 
    Z += 1. / (2 * m) * (WH * hours[i] + WP * pauses[i] - results[i])**2 
 
ax.plot_surface(WH, WP, Z, rstride=4, cstride=4, cmap=cm.coolwarm) 
 
plt.show() 

你知道我该如何解决这些问题吗?

谢谢

编辑:这里是data.txt的内容:
12 0 13
12 8 18
10 0 14
10 4 16
8 0 14
8 2 15
8 8 8
6 0 13
6 3 11
4 0 8
4 4 4
2 2 2
0 0 0

请您参考如下方法:

您可以将表面的 alpha 设置为小于 1 的值,这样它的不透明度就不会完全遮住红点:

ax.plot_surface(WH, WP, Z, rstride=4, cstride=4, cmap=cm.coolwarm, alpha=0.5)