首頁技術(shù)文章正文

Python培訓(xùn):python流星雨特效代碼

更新時(shí)間:2022-11-03 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

  在Python中,我們通過運(yùn)用numpy可視化庫,可以構(gòu)建特效代碼來繪制流星雨的效果圖,具體實(shí)現(xiàn)代碼如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x0, y0 = 1, 1  # 此為流星位置
ts = np.arange(0, 1, 0.01)  # 參數(shù)
xs, ys = x0 + ts, y0 + ts  # 繪圖線條

points = np.array([xs, ys]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

ax = plt.subplot()
lc = LineCollection(segments, cmap='viridis')

lc.set_array(ts)
lc.set_linewidth(ts[::-1])
line = ax.add_collection(lc)

ax.set_xlim(0, 3)
ax.set_ylim(0, 3)
plt.show()

  運(yùn)行程序,效果如圖1-1所示。

1667457366888_用python繪制流星雨效果圖.jpg

  圖1-1 用Python繪制的流星雨效果圖

  如果想繪制很多流星雨的效果圖,實(shí)現(xiàn)代碼如下。

from numpy.random import rand, randint
from matplotlib.collections import LineCollection

import numpy as np
import matplotlib.pyplot as plt

N, L = 20, 100  # 流星個(gè)數(shù)和線段數(shù)
ts = np.array([
    np.linspace(0, rand(), L) for _ in range(N)]).T
x0, y0 = rand(2 * N).reshape(2, 1, N)
x0 *= 5
xs, ys = x0 + ts, y0 + ts  # 繪圖線條1

points = np.array([xs, ys]).T.reshape(N, L, -1, 2)

ax = plt.subplot()
for i in range(N):
    segs = np.concatenate([points[i][:-1], points[i][1:]], axis=1)
    lc = LineCollection(segs, cmap='viridis')
    lc.set_array(ts[:, i])
    lc.set_linewidth(ts[::-1, i])
    ax.add_collection(lc)

ax.set_xlim(0, 6)
ax.set_ylim(-2, 3)
ax.set_axis_off()  # 取消坐標(biāo)軸
plt.show()

  運(yùn)行程序,效果如圖1-2所示。

1667457484669_用python繪制多條流星雨的效果圖.jpg

  圖1-2 用Python繪制多條流星雨的效果圖

分享到:
在線咨詢 我要報(bào)名
和我們在線交談!