十九、matplotlib 绘图基础案例
编辑日期: 2024-11-28 文章阅读: 次
十九、matplotlib 绘图基础案例
需要导入的模块:
import numpy as np
import matplotlib.pyplot as plt
案例1
基本折线图,绘制 \(y=x^2\)
X = range(100)
Y = [value ** 2 for value in X]
plt.plot(X, Y)
plt.show()
案例2
X = np.linspace(0, 2 * np.pi, 100)
Y = np.sin(X)
plt.plot(X, Y)
plt.show()
案例3
X = np.linspace(0, 2 * np.pi, 100)
Ya = np.sin(X)
Yb = np.cos(X)
plt.plot(X, Ya)
plt.plot(X, Yb)
plt.show()
案例4
def plot_slope(X, Y):
Xs = X[1:] - X[:-1]
Ys = Y[1:] - Y[:-1]
plt.plot(X[1:], Ys / Xs)
X = np.linspace(-3, 3, 100)
Y = np.exp(-X ** 2)
plt.plot(X, Y)
plot_slope(X, Y)
plt.show()
案例5
数据文件 my_data.txt 为:
X, Y = [], []
for line in open('my_data.txt', 'r'):
values = [float(s) for s in line.split()]
X.append(values[0])
Y.append(values[1])
plt.plot(X, Y)
plt.show()
案例6
data = np.random.rand(1024, 2)
plt.scatter(data[:, 0], data[:, 1])
plt.show()
案例7 柱状图
data = [5., 25., 50., 20.]
plt.bar(range(len(data)), data, width=0.5)
plt.show()
案例8 水平柱状图
data = [5., 25., 50., 20.]
plt.barh(range(len(data)), data)
plt.show()
案例9 系列柱状图
import numpy as np
import matplotlib.pyplot as plt
data = [[5., 25., 50., 20.],
[4., 23., 51., 17.],
[6., 22., 52., 19.]]
X = np.arange(4)
plt.bar(X + 0.00, data[0], color='b', width=0.25)
plt.bar(X + 0.25, data[1], color='g', width=0.25)
plt.bar(X + 0.50, data[2], color='r', width=0.25)
plt.show()
案例10 stacked 柱状图
A = [5., 30., 45., 22.]
B = [5., 25., 50., 20.]
X = range(4)
plt.bar(X, A, color='b')
plt.bar(X, B, color='r', bottom=A)
plt.show()
案例11 背靠背水平柱状图
women_pop = np.array([5., 30., 45., 22.])
men_pop = np.array([5., 25., 50., 20.])
X = np.arange(4)
plt.barh(X, women_pop, color = 'r')
plt.barh(X, -men_pop, color = 'b')
plt.show()
X = np.arange(4)
plt.barh(X, women_pop, color='r')
plt.barh(X, -men_pop, color='b')
plt.show()
案例12 饼状图
data = [5, 25, 50, 20]
plt.pie(data)
plt.show()
案例13 直方图
X = np.random.randn(1000)
plt.hist(X, bins=20)
plt.show()
案例14 箱形图
data = np.random.randn(100, 5)
plt.boxplot(data)
plt.show()
案例15 三角图
import matplotlib.tri as tri
data = np.random.rand(100, 2)
triangles = tri.Triangulation(data[:, 0], data[:, 1])
plt.triplot(triangles)
plt.show()
Python 20个专题完整目录: