Python中用于画图的库主要有两个:`turtle` 和 `matplotlib`。下面分别介绍如何使用这两个库进行画图:
使用 `turtle` 库
`turtle` 是Python内置的一个绘图库,适合初学者。
导入库
import turtle
设置画布
设置画布大小
turtle.screensize(width=800, height=600, bg="white")
创建画布
screen = turtle.Screen()
设置画笔
创建画笔
pen = turtle.Turtle()
设置画笔属性
pen.color("blue")
pen.pensize(3)
绘制图形
向前移动100个单位
pen.forward(100)
向右旋转90度
pen.right(90)
绘制正方形
for _ in range(4):
pen.forward(100)
pen.right(90)
结束绘图
turtle.done()
使用 `matplotlib` 库
`matplotlib` 是一个功能强大的绘图库,适合绘制复杂的图形。
导入库
import matplotlib.pyplot as plt
绘制图形
绘制直线
x = [10, 20, 30]
y = [10, 40, 20]
plt.plot(x, y)
添加标签
plt.xlabel('times')
plt.ylabel('numbers')
显示图形
plt.show()
绘制饼图
数据
labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
fracs = [15, 30, 45, 10]
绘制饼图
plt.pie(fracs, explode=(0, 0.1, 0, 0), labels=labels, autopct='%1.1f%%', shadow=True)
添加标题
plt.title('Raining Hogs and Dogs')
显示图形
plt.show()
以上是使用 `turtle` 和 `matplotlib` 库进行画图的基本方法。你可以根据需要选择合适的库和命令来绘制你想要的图形