Python可视化图表生成-Matplotlib

发布于 2021-04-29 07:40

Matplotlib 是Python中类似 MATLAB 的绘图工具,熟悉 MATLAB 也可以很快的上手 Matplotlib

安装

pip install matplotlib


折线图

import numpy as npimport matplotlib.pyplot as pltimport matplotlib
# 指定默认字体matplotlib.rcParams['font.sans-serif'] = ['SimHei']matplotlib.rcParams['font.family'] = 'sans-serif'# 解决负号'-'显示为方块的问题matplotlib.rcParams['axes.unicode_minus'] = False
x = np.linspace(0, 2, 100) # 创建等差数列 0-2之间100个
plt.plot(x, x, label="line1") # 第一个参数为横坐标 第二个为纵坐标 第三个为曲线名字plt.plot(x, x ** 2, label="line2")plt.plot(x, x ** 3, label="line3")plt.xlabel("x label") # x轴名字plt.ylabel("y label")  # y轴名字plt.title("折线图")  # 图标名字plt.legend()  # 显示图例plt.show()  # 生成图表

散点图


import numpy as npimport matplotlib.pyplot as pltimport matplotlib
# 指定默认字体matplotlib.rcParams['font.sans-serif'] = ['SimHei']matplotlib.rcParams['font.family'] = 'sans-serif'# 解决负号'-'显示为方块的问题matplotlib.rcParams['axes.unicode_minus'] = False
x = np.arange(0., 5., 0.2) # 从0-5之间,产生等差数列,公差为0.2plt.plot(x, x, "r--", x, x ** 2, "bs", x, x ** 3, "g^") #plt.xlabel("x label") # x轴名字plt.ylabel("y label") # y轴名字plt.title("折线图") # 图标名字plt.legend() # 显示图例
plt.show() # 生成图表

三维散点图

import numpy as npimport matplotlib.pyplot as pltimport matplotlib
# 指定默认字体matplotlib.rcParams['font.sans-serif'] = ['SimHei']matplotlib.rcParams['font.family'] = 'sans-serif'# 解决负号'-'显示为方块的问题matplotlib.rcParams['axes.unicode_minus'] = False
data = np.random.randint(0, 255, size=[40, 40, 40]) # 产生随机数
x, y, z = data[0], data[1], data[2] #ax = plt.subplot(111, projection="3d") # 创建三维绘图
ax.scatter(x[:10], y[:10], z[:10], c="y") # 绘制散点ax.scatter(x[10:20], y[10:20], z[10:20], c="r")ax.scatter(x[30:40], y[30:40], z[30:40], c="g")
ax.set_xlabel("X") # x轴名字ax.set_ylabel("Y") # y轴名字ax.set_zlabel("Z") # z轴名字
plt.title("三维散点图") # 图标名字plt.legend() # 显示图例plt.show() # 生成图表


三维平面图

import numpy as npimport matplotlib.pyplot as pltimport matplotlibfrom mpl_toolkits.mplot3d import Axes3D
# 指定默认字体matplotlib.rcParams['font.sans-serif'] = ['SimHei']matplotlib.rcParams['font.family'] = 'sans-serif'# 解决负号'-'显示为方块的问题matplotlib.rcParams['axes.unicode_minus'] = False
fig = plt.figure()ax = Axes3D(fig)X = np.arange(-4, 4, 0.25)Y = np.arange(-4, 4, 0.25)X, Y = np.meshgrid(X, Y) #R = np.sqrt(X ** 2 + Y ** 2)Z = np.sin(R)ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="rainbow") #
plt.show() # 生成图表