这次我们将通过几个小项目,更深入地掌握 Numpy 和 Matplotlib 的使用方法,边玩边学,轻松有趣!
一、项目一:水果商店的数据分析
小朋友们想象一下,我们现在经营一家水果店,每天都要记录不同水果的销售数量。我们可以用Numpy和Matplotlib来帮我们分析哦!
1. 构造数据
import numpy as np
import matplotlib.pyplot as plt
fruits = ['苹果', '香蕉', '橘子', '草莓']
sales = np.array([100, 80, 90, 120])2. 分析并画图
plt.bar(fruits, sales, color='orange')
plt.title("水果销量统计")
plt.xlabel("水果")
plt.ylabel("销量")
plt.show()是不是很直观呢?马上就知道哪个水果卖得最好啦!
二、项目二:画出漂亮的彩虹波浪
我们来画一条像彩虹一样的波浪线,用到了正弦函数 sin 和 cos。
x = np.linspace(0, 10, 200)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label="sin(x)", color="red")
plt.plot(x, y2, label="cos(x)", color="blue")
plt.title("彩虹波浪线")
plt.xlabel("X轴")
plt.ylabel("函数值")
plt.legend()
plt.grid(True)
plt.show()你可以改变颜色、线条样式,来创造自己的“彩虹”!
三、项目三:天气分析器
假设我们记录了一整个月的天气温度,来分析一下吧!
1. 生成模拟数据
days = np.arange(1, 31)
temperature = np.random.randint(20, 35, size=30)2. 绘图分析
plt.plot(days, temperature, marker='o')
plt.title("一个月的天气变化")
plt.xlabel("日期")
plt.ylabel("温度(℃)")
plt.grid(True)
avg_temp = temperature.mean()
plt.axhline(y=avg_temp, color='red', linestyle='--', label='平均温度')
plt.legend()
plt.show()现在你就是一个“天气小分析师”啦!
四、项目四:自己的星空图
我们用散点图来画一幅属于自己的“星空”。
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)
sizes = np.random.randint(10, 200, size=100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.6)
plt.title("我的星空")
plt.show()这是不是像一幅艺术作品?Python也能让你当小画家!
五、项目五:成绩雷达图(进阶版)
想把语文、数学、英语、科学、美术这些成绩画在一个圆圈里?试试雷达图!
import matplotlib.pyplot as plt
import numpy as np
labels = ['语文', '数学', '英语', '科学', '美术']
scores = [85, 90, 78, 88, 92]
angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False).tolist()
scores += scores[:1]
angles += angles[:1]
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
ax.plot(angles, scores, 'o-', linewidth=2)
ax.fill(angles, scores, alpha=0.25)
ax.set_thetagrids(np.degrees(angles[:-1]), labels)
plt.title("我的成绩雷达图")
plt.show()酷不酷?像游戏中的属性图一样!
六、小任务:动手试试你能做什么?
1. 改变图的颜色和样式
2. 把数据换成你自己的成绩或温度
3. 画一个“我的一天时间安排”饼图
饼图示例:
labels = ['学习', '运动', '吃饭', '玩耍', '睡觉']
sizes = [6, 1, 2, 3, 12]
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title("我的一天")
plt.axis('equal')
plt.show()七、总结与延伸
通过今天的内容,我们进一步掌握了:
• 怎么用 Numpy 创建和操作数据
• 怎么用 Matplotlib 画各种图
• 如何将编程与日常生活结合起来
这不仅仅是学编程,更是学会用编程思维解决问题!
更多相关技术内容咨询欢迎前往并持续关注好学星城论坛了解详情。
想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!