更新時(shí)間:2022-05-09 來(lái)源:黑馬程序員 瀏覽量:
“一閃一閃亮晶晶,滿天都是小星星......”
相信很多人都聽(tīng)過(guò)這首《小星星》。Python大數(shù)據(jù)學(xué)習(xí)中,經(jīng)常會(huì)碰到用3D散點(diǎn)圖實(shí)現(xiàn)數(shù)據(jù)的情況,下面就繪制包含若干個(gè)五角星的3D散點(diǎn)圖,并在不同的坐標(biāo)范圍內(nèi)顯示不同顏色的五角星,具體代碼如下。
# 01_stars_in_3d import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D plt.rcParams["font.sans-serif"] = ["SimHei"] plt.rcParams["axes.unicode_minus"] = False # 生成測(cè)試數(shù)據(jù) x = np.random.randint(0, 40, 30) y = np.random.randint(0, 40, 30) z = np.random.randint(0, 40, 30) # 創(chuàng)建三維坐標(biāo)系的繪圖區(qū)域,并在該區(qū)域中繪制3D散點(diǎn)圖 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for xx, yy, zz in zip(x, y, z): color = 'y' if 10 < zz <20: color = '#C71585' elif zz >=20: color = '#C71585' ax.scatter(xx, yy, zz, c=color, marker='*', s=160, linewidth=1, edgecolor='black') ax.set_xlabel('X軸') ax.set_ylabel('y軸') ax.set_zlabel('z軸') ax.set_title('3D散點(diǎn)圖', fontproperties='simhei', fontsize=14) plt.tight_layout() plt.show()
運(yùn)行程序,效果如圖7-3所示。
圖7-3 3D散點(diǎn)圖