更新时间:2022-11-03 来源:黑马程序员 浏览量:
在Python中,我们通过运用numpy可视化库,可以构建特效代码来绘制流星雨的效果图,具体实现代码如下:
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) # 参数 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()
运行程序,效果如图1-1所示。
图1-1 用Python绘制的流星雨效果图
如果想绘制很多流星雨的效果图,实现代码如下。
from numpy.random import rand, randint from matplotlib.collections import LineCollection import numpy as np import matplotlib.pyplot as plt N, L = 20, 100 # 流星个数和线段数 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() # 取消坐标轴 plt.show()
运行程序,效果如图1-2所示。
图1-2 用Python绘制多条流星雨的效果图
【AI设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19【AI大模型开发-Python】毕业33个工作日,就业率已达到94.55%,班均薪资20763元
2025-09-19【AI智能应用开发-Java】毕业5个工作日就业率98.18%,最高薪资 17.5k*13薪,全班平均薪资9244元
2025-09-19