移动 前端 Python Android Java数据分析

大师兄的Python机器学习笔记:Numpy库、Scipy库和M

2020-04-03  本文已影响0人  superkmi

大师兄的Python机器学习笔记:Numpy库、Scipy库和Matplotlib库(二)
大师兄的Python机器学习笔记:数据预处理

四、Matplotlib库

1. Matplotlib库的功能
2. 实现简单的视图
2.1 matplotlib.pyplot
2.2 plt.plot(x,y,format_string, **kwargs)
字符串 案例
颜色字符 'b' : 蓝色
'#008000' : RGB颜色
0.8 : 灰度值字符串
风格字符 '-' : 实线
'--' : 破折线
'-.' : 点划线
':' : 虚线
'' : 无线条
标记字符 '.' : 点标记
'o' : 实心圈
'v' : 倒三角
'^' : 上三角
2.3 plt.show()
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>plt.plot(x,y,":")
>>>plt.show()
2.4 plt.subplots()
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>plt.plot(x,y,":")

>>>fig,ax = plt.subplots()
>>>print("Figure:",fig)
>>>print("Axes:",ax)
Figure: Figure(432x288)
Axes: AxesSubplot(0.125,0.125;0.775x0.755)
3. 环境配置
3.1 图标
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>plt.plot(x,y,":",label="label sample")
>>>plt.legend() # 生成图例
>>>plt.show()
3.2 标题
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>plt.plot(x,y,":",label="label sample")
>>>plt.title('sample title')
>>>plt.legend()
>>>plt.show()
3.3 标签
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>plt.plot(x,y,":",label="label sample")
>>>plt.title('sample title')
>>>plt.xlabel('xsample')
>>>plt.ylabel('ysample')
>>>plt.legend()
>>>plt.show()
3.4 网格线
参数 意义
b 是否显示网格线 True / False
which 模式 'major' / 'minor' / 'both'
axis 绘制哪个方向的网格线 'both' / 'x' / 'y'
color/c 颜色 各种颜色的首字母
linestyle/ls 网格线风格 '-' / '--' / '-. / ':' / 'None' / ' '
linewidth 网格线宽度 数字
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>plt.plot(x,y,":",label="label sample")
>>>plt.title('sample title')
>>>plt.xlabel('xsample')
>>>plt.ylabel('ysample')
>>>plt.grid(b=True,which='major',linewidth=0.5)
>>>plt.legend()
>>>plt.show()
3.5 中文显示
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>plt.plot(x,y,":",label="label样式")

>>>plt.rcParams['font.sans-serif']=['SimHei']  # 配置字体
>>>plt.rcParams['axes.unicode_minus']=False  # 正常显示符号

>>>plt.title('中文标题')
>>>plt.xlabel('x轴')
>>>plt.ylabel('y轴')
>>>plt.grid(b=True,which='major',linewidth=0.5)
>>>plt.legend()
>>>plt.show()
4. 图标类型
4.1 条形图
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>plt.bar(x,y,label= 'sample1')
>>>plt.bar(y,x,label= 'sample2',color='g')

>>>plt.xlabel('xsample')
>>>plt.ylabel('ysample')
>>>plt.legend()
>>>plt.show()
4.2 直方图
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>data = np.random.random_integers(100,size=(100))
>>>bins=np.array(range(0,100,10))
>>>plt.hist(data,bins,histtype='bar',rwidth=0.8)

>>>plt.xlabel('xsample')
>>>plt.ylabel('ysample')
>>>plt.legend()
>>>plt.show()
4.3 散点图
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>plt.scatter(x,y,label='sample',color='b',s=20,marker="o")
>>>plt.xlabel('xsample')
>>>plt.ylabel('ysample')
>>>plt.legend()
>>>plt.show()
4.4 堆叠图
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>data1 = np.array([1,3,5,7,9])
>>>data2 = np.array([2,4,6,8,10])
>>>data3 = np.array([1,2,3,4,5])
>>>data4 = np.array([6,7,8,9,10])

>>>plt.stackplot(data1,data2,data3,data4,colors=['b','r','m','k'])
>>>plt.xlabel('xsample')
>>>plt.ylabel('ysample')
>>>plt.legend()
>>>plt.show()
4.5 饼图
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>data = np.random.random_integers(100,size=(5))
>>>title=["A","B","C","D","E"]
>>>colours = ['b','r','m','k','c']
>>>plt.pie(data,labels=title,colors=colours,startangle=90,shadow=True,autopct='%1.1f%%',explode=(0.1,0,0,0,0))

>>>plt.legend()
>>>plt.show()
5. 时间戳的使用
>>>from datetime import datetime,date,timedelta
>>>import time
>>>import matplotlib.dates as mdates
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>data = np.arange(0,7)
>>>ts_start = datetime(2018,3,30,0,0,0)
>>>ts_now = datetime(2019,3,30,0,0,0)
>>>formatter = mdates.DateFormatter("%Y-%m-%d")
>>>delta = timedelta(5*10^10)
>>>dates = mdates.drange(ts_start,ts_now,delta)

>>>fig,ax = plt.subplots()
>>>plt.plot_date(dates,data)
>>>ax.xaxis.set_major_formatter(formatter)
>>>ax.xaxis.set_tick_params(rotation=30,labelsize=10)

>>>plt.show()
6. 颜色和样式
6.1 改变标签颜色
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>fig,ax = plt.subplots()

>>>plt.plot(x,y,":",label="label sample")
>>>plt.xlabel('xsample')
>>>plt.ylabel('ysample')
>>>ax.xaxis.label.set_color('b') # 改变x轴label颜色
>>>ax.yaxis.label.set_color('c') # 改变y轴label颜色
>>>plt.title('sample title')
>>>plt.legend()
>>>plt.show()
6.2 填充颜色
参数 含义
x 表示覆盖的区域
y1 表示覆盖的下限
y2 表示覆盖的上限
where 制定覆盖区域,默认为None
interpolate 是否有重叠区域
step 步长
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>plt.plot(x,y,":")

>>>fig,ax = plt.subplots()
>>>ax.fill_between(x,0,y,facecolor='b',alpha=0.5)
>>>plt.show()
6.3 自定义边框
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>fig,ax = plt.subplots()
>>>ax.spines['top'].set_color('b') # 改变顶部边框的颜色
>>>ax.spines['bottom'].set_visible(False) # 隐藏底部边框
>>>ax.spines['left'].set_linewidth(10) # 改变左侧边框宽度
6.4 自定义刻度
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>fig,ax = plt.subplots()
>>>ax.tick_params(axis='x', colors='b')
>>>ax.tick_params(axis='y',colors='r')
6.5 添加水平线和垂直线
>>>import matplotlib.pyplot as plt
>>>import numpy as np

[图片上传中...(下载.png-df23ca-1585644395419-0)]
>>>fig,ax = plt.subplots()
>>>ax.axhline(5, c='b',ls='--', lw=1,)
>>>ax.axvline(5, c='r',ls='-', lw=1,)
6.6 风格美化
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>plt.style.use('dark_background')
>>>plt.plot(x,y,label="label sample")
>>>plt.show()
7.文本注解
7.1 简单的文本注解
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>plt.style.use('ggplot')
>>>plt.text(5,7,'text sample',color='b')
>>>plt.plot(x,y,label="label sample")
>>>plt.show()
7.2 带箭头的文本注解
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>plt.style.use('ggplot')
>>>plt.annotate('text sample',(5,7),
>>>             xytext=(0.6, 0.7), textcoords='axes fraction',
>>>             arrowprops = dict(facecolor='red',color='red'),
>>>             color='b')
>>>plt.plot(x,y,label="label sample")
>>>plt.show()
7.3 使用框+文本的注解
参数 含义
boxstyle 边框的类型
fc 背景颜色
ec 边框线的透明度
alpha 字体的透明度
lw 线的粗细
rotation 角度
名称 基础属性
Circle circle pad=0.3
DArrow darrow pad=0.3
LArrow larrow pad=0.3
RArrow rarrow pad=0.3
Round round pad=0.3,rounding_size=None
Round4 round4 pad=0.3,rounding_size=None
Roundtooth roundtooth pad=0.3,tooth_size=None
Sawtooth sawtooth pad=0.3,tooth_size=None
Square square pad=0.3
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>bbox = dict(boxstyle="larrow",fc='w',ec="r",lw=1)
>>>t = plt.text(7,6,"sample",ha="center",va="center",size=10,bbox=bbox)
>>>plt.plot(x,y,label="label sample")
>>>plt.show()
8. 多图表
8.1 子图
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>#子图1
>>>plt.subplot(2,2,1)
>>>plt.plot(x,y,label="sample1",c='b')
>>>plt.legend()

>>>#子图2
>>>plt.subplot(2,2,2)
>>>plt.plot(x,y,label="sample2",c='r')
>>>plt.legend()

>>>#子图3
>>>plt.subplot(2,2,3)
>>>plt.plot(x,y,label="sample3",c='m')
>>>plt.legend()

>>>#子图4
>>>plt.subplot(2,2,4)
>>>plt.plot(x,y,label="sample4",c='y')
>>>plt.legend()

>>>plt.show()
8.2 跨越网格的子图
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>#子图1
>>>plt.subplot2grid((4,4),(0,0),colspan=2)
>>>plt.plot(x,y,label="sample1",c='b')
>>>plt.legend()

>>>#子图2
>>>plt.subplot2grid((4,4),(0,3),rowspan=2)
>>>plt.plot(x,y,label="sample2",c='r')
>>>plt.legend()

>>>#子图3
>>>plt.subplot2grid((4,4),(2,1),rowspan=2,colspan=2)
>>>plt.plot(x,y,label="sample3",c='m')
>>>plt.legend()

>>>plt.show()
8.3 共享X轴
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>x1 = np.array(range(1,20))
>>>y1 = np.array(range(20,1,-1))

>>>x2 = np.array(range(1,30))
>>>y2 = np.array(range(30,1,-1))

>>>plt.subplots_adjust(wspace =0, hspace =0)#调整子图间距

>>>#子图1
>>>ax=plt.subplot2grid((3,1),(0,0))
>>>ax.get_xaxis().set_visible(False) # 隐藏x轴
>>>ax.spines['bottom'].set_visible(False) # 隐藏下边框
>>>plt.plot(x,y,label="sample1",c='b')
>>>plt.legend()

>>>#子图2
>>>ax1=plt.subplot2grid((3,1),(1,0),sharex=ax)
>>>ax1.get_xaxis().set_visible(False)# 隐藏x轴
>>>ax1.spines['bottom'].set_visible(False) # 隐藏下边框
>>>ax1.spines['top'].set_visible(False) # 隐藏上边框
>>>plt.plot(x1,y1,label="sample2",c='r')
>>>plt.legend()

>>>#子图3
>>>ax2=plt.subplot2grid((3,1),(2,0),sharex=ax)
>>>ax2.spines['top'].set_visible(False) # 隐藏上边框
>>>plt.plot(x2,y2,label="sample3",c='m')
>>>plt.legend()

>>>plt.show()
8.4 共享y轴
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>x1 = np.array(range(1,20))
>>>y1 = np.array(range(20,1,-1))

>>>x2 = np.array(range(1,30))
>>>y2 = np.array(range(30,1,-1))

>>>plt.subplots_adjust(wspace =0, hspace =0)#调整子图间距

>>>#子图1
>>>ax=plt.subplot2grid((1,3),(0,0))
>>>plt.plot(x,y,label="sample1",c='b')
>>>plt.legend()

>>>#子图2
>>>ax1=plt.subplot2grid((1,3),(0,1),sharey=ax)
>>>ax1.get_yaxis().set_visible(False)# 隐藏x轴
>>>ax1.spines['left'].set_visible(False) # 隐藏左边框
>>>plt.plot(x1,y1,label="sample2",c='r')
>>>plt.legend()

>>>#子图3
>>>ax2=plt.subplot2grid((1,3),(0,2),sharey=ax)
>>>ax2.get_yaxis().set_visible(False) # 隐藏x轴
>>>ax2.spines['left'].set_visible(False) # 隐藏左边框
>>>plt.plot(x2,y2,label="sample3",c='m')
>>>plt.legend()
>>>plt.show()
9. 自定义图标
9.1 自定义图标基础属性
参数 含义
loc 自定义位置 string/int
nco 自定义列数 int
fontsize 自定义字体大小 string/int
frameon 边框 bool
facecolor 背景颜色 string
edgecolor 边框颜色 string
title 标题 string
prop 属性 dict
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>for i in range(1,4):
>>>    plt.plot(x+i,y+i,label="label sample{}".format(i))

>>>leg = plt.legend(loc='upper center',ncol=2,title='sample',facecolor='b',prop={'size':12})
>>>leg.get_frame().set_alpha(0.4) # 改变透明度
>>>plt.show()
9.1 更精准的定位
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))

>>>for i in range(1,4):
>>>    plt.plot(x+i,y+i,label="label sample{}".format(i))

>>>leg = plt.legend(title='sample',bbox_to_anchor=(1.5,1))
>>>plt.show()
10. 3D 绘图
10.1 实现简单的3D绘图
>>>from mpl_toolkits.mplot3d import Axes3D
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>z = np.array([np.sin(x)])

>>>fig = plt.figure()
>>>ax = Axes3D(fig)

>>>ax.plot_wireframe(x,y,z)
>>>ax.set_xlabel('sample x')
>>>ax.set_ylabel('sample y')
>>>ax.set_zlabel('sample z')

>>>plt.show()
10.2 3D散点图
>>>from mpl_toolkits.mplot3d import Axes3D
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>z = np.array([np.sin(x)])

>>>fig = plt.figure()
>>>ax = Axes3D(fig)

>>>ax.scatter(x,y,z,c='b',marker='o')
>>>ax.set_xlabel('sample x')
>>>ax.set_ylabel('sample y')
>>>ax.set_zlabel('sample z')

>>>plt.show()
10.3 3D条形图
>>>from mpl_toolkits.mplot3d import Axes3D
>>>import matplotlib.pyplot as plt
>>>import numpy as np

>>>x = np.array(range(1,10))
>>>y = np.array(range(10,1,-1))
>>>z = np.array(np.cos(x))

>>>dx=dy= np.ones(9)
>>>dz= np.array(range(1,10))
>>>fig = plt.figure()
>>>ax = Axes3D(fig)

>>>ax.bar3d(x,y,z,dx,dy,dz)
>>>ax.set_xlabel('sample x')
>>>ax.set_ylabel('sample y')
>>>ax.set_zlabel('sample z')

>>>plt.show()

参考资料


上一篇 下一篇

猜你喜欢

热点阅读