Matplotlib之基本操作
程序员文章站
2024-03-26 12:33:05
...
下面完整代码在github仓库:传送门
一、画散点图
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['figure.figsize'] = (10, 6) # 图像显示大小
plt.rcParams['font.sans-serif'] = ['SimHei'] # 防止中文标签乱码,还有通过导入字体文件的方法
plt.rcParams['lines.linewidth'] = 0.5 # 设置曲线线条宽度
# plt.scatter(x=[2, 5, 6], y=[4, 8, 3], marker="*", alpha=0.5)
# plt.show()
# num = np.array([[2, 5], [3, 6], [4, 5], [3, 7], [5, 9]])
# # plt.scatter(x=num, y=num, marker="*", alpha=0.5)
# plt.scatter(x=num[:, 0], y=num[:, 1], marker="*", alpha=0.5)
# plt.show()
x = np.random.rand(20)
y = np.random.rand(20)
x1 = np.random.rand(20)
y1 = np.random.rand(20)
# 绘制点
plt.scatter(x, y, c="r", marker="p", s=20, label="girl")
plt.scatter(x1, y1, c="b", marker="v", s=18, label="boy")
plt.legend() # 显示图例
plt.title("标题")
plt.text(0.5, 0.4, "哈哈")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
二、画3D图
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.random.normal(0, 1, 100)
y = np.random.normal(0, 1, 100)
z = np.random.normal(0, 10, 100)
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c="green", marker="v", label="boy")
plt.legend()
plt.show()
三、画各种直方图
from matplotlib import pyplot as plt
import numpy as np
x = [5, 8, 10]
y = [12, 16, 6]
x2 = [6, 9, 11]
y2 = [6, 15, 7]
plt.bar(x, y)
plt.bar(x2, y2)
plt.title("Bar")
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
from matplotlib import pyplot as plt
import numpy as np
u = 100 # 均值
sigma = 20 # 方差
# 2000个数据
x = u + sigma*np.random.randn(2000)
# x = np.random.randn(2000)
# 画图 bins:条形的个数, normed:是否标准化
plt.hist(x=x, bins=10, normed=True)
plt.show()
from matplotlib import pyplot as plt
import numpy as np
u = 100 # 均值
sigma = 20 # 方差
# 2000个数据
x = u + sigma*np.random.randn(2000)
# x = np.random.randn(2000)
# 画图 bins:条形的个数, normed:是否标准化
plt.hist(x=x, bins=10, normed=True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(10000)
y = np.random.rand(10000)
plt.hist2d(x=x, y=y, bins=100)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
labels = ['娱乐', '育儿', '饮食', '房贷', '交通', '其它']
sizes = [2, 4, 12, 70, 2, 9]
explode = (0, 0, 0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=False, startangle=150)
plt.title("饼图实例-8月份家庭支出")
plt.show()
四、画动态图
import matplotlib.pyplot as plt
import numpy as np
ax = []
ay = []
plt.ion()
for i in range(100):
random = np.random.rand()
ax.append(i)
# ay.append(i**2)
# ay.append(np.log(i**2))
# ay.append(-np.log(i**2))
ay.append(-np.log(i**2)*random)
# plt.clf()
plt.plot(ax, ay) # 画折线图
plt.scatter(ax,ay, c="r", marker="v")
plt.pause(0.1)
plt.ioff()
plt.show()