我的机器学习matplotlib篇

立flag啊 又要努力学习了!!分享学习机器学习上一些有趣的问题和实用的文章知识点!!

前言:
matplotlib是python最常用的绘图库,能帮你画出美丽的各种图

  • 导入

包含了中文显示,屏外显示

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
%matplotlib tk 
#解决中文不显示问题
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
  • 画出第一个图形

figure图形,画的每个图只有一个figure对象

x= np.arange(-3,3,0.1)
y1=np.sin(x)
#创建第一个figure
plt.figure()
#绘图
plt.plot(x,y1)
#表现出来
plt.show()

正弦图.png

有多条线

x= np.arange(-3,3,0.1)
y1=np.sin(x)
y2=np.cos(x)
plt.figure(num=3,figsize=(8,5))
plt.plot(x,y1,x,y2)
plt.show()

image.png

  • 颜色,标记,线型

主要是plt.plot的一些参数

plt.figure(num=3,figsize=(8,5))
plt.plot([1,2,3],[5,7,4],color="red",linestyle="dashed",marker="o",markersize="10",alpha=0.8)
plt.show()
# plt.plot([1,2,3],[5,7,4],'ro--')#为简写方式

image.png

  • 刻度、标题、标签和图例!

内容代码中已经注释

x1=[1,2,3]
y1=[5,7,4]
x2=[1,2,3]
y2=[10,14,12]
plt.figure(num=3,figsize=(8,5))
plt.plot(x1,y1,'ro-',label="进口")
plt.plot(x2,y2,'bo--',label="出口")#label设置线条标签
#设置标题,x,y轴标签
plt.xlabel('月份')
plt.ylabel("数额")
plt.title("进出口数据")
#设置x,y轴范围
plt.xlim(0,6)
plt.ylim(0,15)
# #设置x,y轴刻度
# plt.xticks(np.arange(0,6,1))
#按照上面设置不美观,推荐用np.linspace
plt.xticks(np.linspace(1,6,6),[str(i)+"月" for i in range(1,7)])
plt.yticks(np.arange(1,15,3),[200,300,400,500,600])
#设置边框,先获得坐标轴信息plt.gca()
ax=plt.gca()
ax.spines['top'].set_color('red')
# ax.spines['right'].set_color('none')
#生成默认图例
plt.legend()
plt.show()

image.png

  • 创建子图

在一个figure中显示多个图片

  • 面向过程的方法,一步一步创建
x1=[1,2,3]
y1=[5,7,4]
x2=[1,2,3]
y2=[10,14,12]
plt.figure()
plt.subplot(221)#第一个子图
plt.plot(x1,y1,'ro--')
plt.subplot(223)
plt.plot(x2,y2,'bo-')#第二个子图
plt.show
  • 面向对象创建子图
#创建图形
fig=plt.figure()
#创建子图
ax1=fig.add_subplot(221)
ax2=fig.add_subplot(222)
ax3=fig.add_subplot(212)

#在子图上画图
ax1.plot(np.random.randn(50).cumsum(),'r-')
ax2.plot(np.random.randn(50).cumsum(),'b-')
ax3.plot(np.random.randn(50).cumsum(),'g--')

plt.show

image.png

  • subplots创建多个子图
fig,axes=plt.subplots(nrows=4,ncols=1,sharex=True)
axes[0].plot(range(10),'ro--')
axes[1].plot(range(10),'bo--')
axes[2].plot(range(10),'yo--')
axes[3].plot(range(10),'go--')

image.png

  • 例子
fig,axes=plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2):
    for j in range(2):
        axes[i][j].hist(np.random.randn(100),5,color='g',alpha=0.75)
#调整子图之间的距离
fig.subplots_adjust(wspace=0.2,hspace=0.3)
fig.suptitle("text",fontsize=20)#设置标题和格式
#保存
# plt.savefig("aaa",dpi=200)
plt.show()

image.png

后记:
线图先到这,还有柱状图,散点图,3d图等待续……
我自己可能感冒的文章:
我的机器学习numpy篇
我的机器学习pandas篇
我的机器学习微积分篇

来自!!!
作者:飘涯
链接:https://www.jianshu.com/p/f2ebf312e323
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/u011516972/article/details/86700183