1.绘制正弦
代码语言:javascript复制from matplotlib.pyplot import plot, show
import math
T = range(100) # 0~99
# X周的范围2pi,分成100份
X = [(2 * math.pi) * t / len(T) for t in T]
# sin和cos
Y = [math.sin(value) for value in X]
print(X)
plot(X, Y)
# 绘制
show()
2.在同一个二维坐标系绘制出一元二次曲线和正弦、余弦曲线
代码语言:javascript复制import numpy
from matplotlib.pyplot import plot, show
# 在同一个二维坐标系绘制出一元二次曲线和正弦、余弦曲线
# 一元二次方程
X = numpy.linspace(-3, 3, 200)
Y = X ** 2 - 2 * X 1
plot(X, Y)
# sin
X = numpy.linspace(0, 2 * numpy.pi, 100)
Y = numpy.sin(X)
plot(X, Y)
# cos
X = numpy.linspace(0, 2 * numpy.pi, 100)
Y = numpy.cos(X)
plot(X, Y)
show()
3.绘制随机点
代码语言:javascript复制import random
import matplotlib.pyplot as plt
# 绘制随机点
count = 1024
X = [random.random() for i in range(count)]
Y = [random.random() for i in range(count)]
# 绘制连续的
# plt.plot(X, Y)
# 绘制随机的
plt.scatter(X, Y)
plt.show()
4.绘制垂直柱状图
代码语言:javascript复制from matplotlib.pyplot import plot, show, bar, barh
# 绘制垂直柱状图
# x坐标
X = [0, 1, 2, 3]
# y轴坐标
Y = [22, 11, 44, 15]
bar(X, Y)
show()
5.绘制多组垂直柱状图
代码语言:javascript复制import matplotlib.pyplot as plt
# 绘制多组垂直柱状图
Y = [
[11, 22, 44, 66],
[55, 66, 77, 22],
[44, 55, 66, 77]
]
plt.bar(range(4), Y[0], width=0.25)
plt.bar([x 0.25 for x in range(4)], Y[1], width=0.25)
plt.bar([x 0.5 for x in range(4)], Y[2], width=0.25)
plt.show()
6.在同一个窗口绘制直方图和盒状图
代码语言:javascript复制import numpy
import matplotlib.pyplot as plot
# hist:直方图
# boxplot:盒状图
# randn函数返回一个或一组样本,具有标准正态分布
data = numpy.random.randn(100)
# print(data)
print("平均值==", numpy.average(data))
# 把显示分为两个区域
fig, (ax1, ax2) = plot.subplots(1, 2, figsize=(8, 4))
print(fig) # Figure(800x400)
# 直方图,分为100份
ax1.hist(data, 100)
# 盒状图
ax2.boxplot(data)
# 显示
plot.show()
7.绘制有百分比和标签的饼状图
代码语言:javascript复制import matplotlib.pyplot as plt
X = [22, 33, 11, 66]
labels = ["张三", "李四", "王二", "麻子"]
plt.pie(X, autopct="%.2f%%", labels=labels)
plt.legend(labels)
plt.axis("equal")
plt.show()