折线图
#折线图,曲线图import numpy as npimport matplotlib.pyplot as pltx = np.linspace(-10, 10, 1000)# y = np.sin(x)#y = 2 * x * x * x + 3* x * x + 2*x +5y = np.sin(2*x)+2*np.cos(1/x)plt.figure()plt.plot(x, y)plt.show()
import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['KaiTi'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号plt.figure()fig, (axes1, axes2) = plt.subplots(nrows=1, ncols=2)axes1.plot([1, 2, 3, 4, 5, 6], color="r", linestyle="-.", label="红线")axes1.set_title("图1")# 设置当前x轴以及y轴的labelaxes1.set_xlabel(xlabel="x轴")axes1.set_ylabel(ylabel="y轴")# 设置显示昂前的legendaxes1.legend()# 设置当前的网格axes1.grid(True, linestyle='-.', alpha=0.5)axes2.plot([2, 4, 6, 8], color="y", linestyle="--", label="黄线")axes2.set_title("图2")# 设置当前第二张图的刻度axes2.set_xticks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])axes2.set_yticks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])axes2.legend()# 开启刻度axes2.minorticks_on()plt.show()
子图
import matplotlibimport matplotlib.pyplot as pltplt.figure()plt.subplot(2,1,1)plt.plot(x,mean_loss,'r.-',label='mean_loss')plt.legend()plt.subplot(2,3,4)plt.plot(x,NLL_loss,'bo-',label='NLL_loss')plt.legend()plt.subplot(235)plt.plot(x,label_loss,'bo-',label='label_loss')plt.legend()plt.subplot(236)plt.plot(x,KL_loss,'bo-',label='KL_loss')plt.legend()plt.savefig(save_model_path + '/'+'loss.png')plt.show() # 展示
直方图
# 直方图与当前的柱状图不一样,一个是有间隔并且x轴的是一个准确的值,直方图的值为区间import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['KaiTi'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号plt.figure()x_date = [22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27]bins = [0, 20, 40, 60, 80, 100]plt.hist(x_date, bins, density=True)# plt.yticks(range(min(x_date), max(x_date), 10))plt.xticks(range(min(bins), max(bins) + 5, 5))plt.show()
柱状图
import matplotlib.pyplot as pltimport randomplt.rcParams['font.sans-serif'] = ['KaiTi'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号plt.figure()month_days = 31x = [i for i in range(1, month_days)]y = [random.randrange(20, 41) for i in range(1, month_days)]plt.bar(x, y, color="r", label="金额")plt.minorticks_on()plt.title("一个月的消费情况")plt.xlabel("一个月(天)")plt.ylabel("消费金额(元)")plt.legend()# plt.xticks(x)# plt.yticks([i for i in range(0, 41)])plt.show()
import matplotlib.pyplot as pltimport randomplt.rcParams['font.sans-serif'] = ['KaiTi'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号plt.figure()month_days = 5x = [i + 1 for i in range(1, month_days + 1)]y = [random.randrange(20, 41) for i in range(1, month_days + 1)]plt.bar(x, y, label="金额", color=["r", "y", "b", "g", "c"])# plt.minorticks_on()plt.title("一周的消费情况")plt.xlabel("一周(天)")plt.ylabel("消费金额(元)")plt.legend()plt.xticks(x, ["星期{0}".format(i + 1) for i in range(0, month_days + 1)])plt.grid( linestyle="-.", alpha=0.5)plt.show()
import matplotlib.pyplot as pltimport randomplt.rcParams['font.sans-serif'] = ['KaiTi'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号plt.figure()month_days = 5x = [i for i in range(1, month_days + 1)]y = [random.randrange(20, 41) for i in range(1, month_days + 1)]plt.bar(x, y, label="本周", width=0.3, color="r")plt.bar([i + 0.2 for i in x], [i + random.randrange(1, 10) for i in y], label="上周", width=0.3, color="g")# plt.minorticks_on()plt.title("本周和上周的消费情况")plt.xlabel("同比")plt.ylabel("消费金额(元)")plt.legend()plt.xticks([i + 0.05 for i in x], ["星期{0}".format(i + 1) for i in range(0, month_days + 1)])plt.grid(linestyle="-.", alpha=0.5)plt.show()
# -*- coding: utf-8 -*-import timeimport matplotlib.pyplot as pltdef showResult(xList, yList, title, xLabel, yLabel):plt.bar(xList, yList, width=0.5,color="b")plt.title(title)plt.xlabel(xLabel)plt.ylabel(yLabel)plt.xticks(xList)for x, y in zip(xList, yList):plt.text(x, y+0.3, str(y), ha='center', va='bottom', fontsize=7.5)plt.savefig('fig'+str(int(time.time()))+'.jpg')plt.show()x_arr = [1, 2, 3, 4, 5, 6,7,8,9,10]y_arr = [95.88897746,92.99818646,84.0831402,87.035405,90.48605803,83.32441838,82.4323623,94.95956628,86.27340434,90.85186676]showResult(x_arr, y_arr, 'Changan Soh Estimation', 'vehicle number', 'SOH')
饼图
import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['KaiTi'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号plt.figure()dataList = [10, 12, 15, 18, 9, 25]dataLabel = ["水", "零食", "水果", "生活用品", "外卖", "电影"]plt.pie(dataList, labels=dataLabel, colors=["r", "y", "g", "b", "c", "m"], autopct="%1.2f%%")plt.legend()plt.title("一天的消费情况")# 将当前的图形变成圆形,默认为椭圆plt.axis("equal")plt.show()
散点图
import matplotlib.pyplot as pltimport randomplt.rcParams['font.sans-serif'] = ['KaiTi'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = Falseplt.figure()month_days = 31x = [i for i in range(1, month_days)]y = [random.randrange(20, 40) for i in range(1, month_days)]plt.scatter(x, y)plt.xlabel("一个月")plt.ylabel("消费金额")plt.title("一个月的中餐的消费情况")plt.show()
热力图
import numpy as npimport matplotlib.pyplot as pltx = np.random.rand(100).reshape(10,10)plt.imshow(x, cmap=plt.cm.hot, vmin=0, vmax=1)plt.colorbar()plt.show()
三维的线图和散点图
最基本的三维图是由(x, y, z)三维坐标点构成的线图与散点图,可以用ax.plot3D和ax.scatter3D函数来创建,默认情况下,散点会自动改变透明度,以在平面上呈现出立体感
#绘制三角螺旋线from mpl_toolkits import mplot3d%matplotlib inlineimport matplotlib.pyplot as pltimport numpy as npax = plt.axes(projection='3d')#三维线的数据zline = np.linspace(0, 15, 1000)xline = np.sin(zline)yline = np.cos(zline)ax.plot3D(xline, yline, zline, 'gray')# 三维散点的数据zdata = 15 * np.random.random(100)xdata = np.sin(zdata) + 0.1 * np.random.randn(100)ydata = np.cos(zdata) + 0.1 * np.random.randn(100)ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens')
三维等高线图
def f(x, y):return np.sin(np.sqrt(x ** 2 + y ** 2))x = np.linspace(-6,6,30)y = np.linspace(-6,6,30)X, Y = np.meshgrid(x, y)Z = f(X,Y)fig = plt.figure()ax = plt.axes(projection='3d')ax.contour3D(X, Y, Z, 50, cmap='binary')ax.set_xlabel('x')ax.set_ylabel('y')ax.set_zlabel('z')#调整观察角度和方位角。这里将俯仰角设为60度,把方位角调整为35度ax.view_init(60, 35)
线框图和全面图
全面图和线框图相似,只不过线框图的每一个面都是由多边形构成。只要增加唉一个配色方案来填充这些多边形,就可以感受到可视化图形表面的拓扑结构了。
#线框图fig =plt.figure()ax = plt.axes(projection='3d')ax.plot_wireframe(X, Y, Z, color='c')ax.set_title('wireframe')
曲面图
#曲面图ax = plt.axes(projection='3d')ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')ax.set_title('surface')
三维切片
#使用极坐标可以获得切片的效果r = np.linspace(0, 6, 20)theta = np.linspace(-0.9 * np.pi, 0.8 * np.pi, 40)r, theta = np.meshgrid(r, theta)X = r * np.sin(theta)Y = r * np.cos(theta)Z = f(X, Y)ax = plt.axes(projection='3d')ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
曲面三角剖分
在某些应用场景下,上述这些要求均匀采样的网格数据显得太过严格且不太容易实现。这时就可以使用三角剖分部分图形。
theta = 2 * np.pi * np.random.random(1000)r = 6 * np.random.random(1000)x = np.ravel(r * np.sin(theta))y = np.ravel(r * np.cos(theta))z = f(x, y)ax = plt.axes(projection='3d')ax.scatter(x, y, z, c=z, cmap='viridis', linewidth=0.5)
上图还有许多地方需要修补,这些工作可以由ax.plot_trisurf函数帮助我们完成。它首先找到一组所有点都连接起来的三角形,然后用这些三角形创建曲面
ax = plt.axes(projection='3d')ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none')
莫比乌斯带(应用曲面三角剖分)
#绘制莫比乌斯带#由于它是一条二维带,因此需要两个内在维度。theta维度取值范围是0~2pi,宽度维度w取值范围是-1~1theta = np.linspace(0, 2 * np.pi, 30)w = np.linspace(-0.25, 0.25, 8)w, theta = np.meshgrid(w, theta)phi = 0.5 * theta#x-y平面内的半径r = 1 + w * np.cos(phi)x = np.ravel(r * np.cos(theta))y = np.ravel(r * np.sin(theta))z = np.ravel(w * np.sin(phi))#要画出莫比乌斯带,还必须保证三角部分是正确的。最好的方法是首先用基本参数化方法定义三角部分,然后用Matplotlib将#这个三角剖分映射到莫比乌斯带的三维空间里from matplotlib.tri import Triangulationtri = Triangulation(np.ravel(w), np.ravel(theta))ax = plt.axes(projection='3d')ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap='viridis', linewidth=0.2)ax.set_xlim(-1, 1);ax.set_ylim(-1,1);ax.set_zlim(-1,1)
动态条形图
import matplotlib.pyplot as pltimport timedef insert_sort(lst):lsts = []for i in range(len(lst)):temp = lst[i]j = i-1while j>=0 and lst[j]>temp:lst[j+1] = lst[j]j -= 1lst[j+1] = templ = lst[:]lsts.append(l)return lstsif __name__ == "__main__":lst = [13,32,42,1,53,4,66,2,5,7,74,23]lsts = insert_sort(lst)plt.ion()#打开交互模式fig = plt.figure()#新建绘图窗口ax = plt.gca()#获取当前子图bars = ax.bar(range(len(lst)),height=lst)#绘制条形图for l in lsts:print(l)bars.remove()#删除条形图bars = ax.bar(range(len(lst)),height=l)#绘制条形图plt.pause(0.5)while True:#防止图片关闭plt.pause(1)
如果觉得《matplotlib绘图(折线图 直方图 柱状图 饼图 散点图 三维 动图)》对你有帮助,请点赞、收藏,并留下你的观点哦!