size = (m,n,3) 图片的通常形式就是这样的html
rgb 0-255 jpg图片 166,255,89 0.0-1.0 png图片 0.1,0.2,0.6python
灰度处理之后 rgb---->gray 166,255,89 ---> 190 0.1,0.2,0.6 -- > 0.4app
size = (m,n)dom
import scipy.misc as miscide
import numpy as np
import pandas as pd
from pandas import Series,DataFramesvg
import matplotlib.pyplot as plt
%matplotlib inline函数
face_image = misc.face()
plt.imshow(face_image)字体
face_gray = misc.face(gray=True)
plt.imshow(face_gray,cmap='gray')ui
三种方法spa
plt.imshow(face_image.max(axis=2),cmap='gray')
plt.imshow(face_image.mean(axis=2),cmap='gray')
n = np.array([0.299,0.587,0.114])
plt.imshow(np.dot(face_image,n),cmap='gray')
Matplotlib中的基本图表包括的元素
x = np.arange(-np.pi,np.pi,0.1)
y = np.sin(x)
plt.plot(x,y)
plt.plot(x,np.sin(x),x,np.cos(x))
axes = plt.subplot()
plt.figure(figsize=(8,8))
# 设置字画布,返回的值就是当前字画布的坐标系对象
axes1 = plt.subplot(2,2,1)
axes2 = plt.subplot(222)
axes3 = plt.subplot(223)
axes4 = plt.subplot(224)
绘制正弦余弦
设置grid参数(参数与plot函数相同),使用plt面向对象的方法,建立多个子图显示不一样网格线
# 对不一样的坐标系分别设置网格线
plt.figure(figsize=(16,4))
axes1 = plt.subplot(141)
axes2 = plt.subplot(142)
axes3 = plt.subplot(143)
axes4 = plt.subplot(144)
axes1.grid(True)
axes3.grid(True)
# axis参数设置网格线显示横纵
axes2.grid(axis='x')
axes4.grid(axis='y')
# 设置线宽、透明度、颜色
# red green yellow blue black orange pink gray white purple cyan
axes1.grid(color='red')
axes2.grid(lw = 2)
axes3.grid(alpha = 0.5)
plt.axis([xmin,xmax,ymin,ymax])
plt.figure(figsize=(4,4))
x = np.linspace(-1,1,100)
y = (1-x**2)**0.5
plt.plot(x,y)
plt.axis([-4,4,-3,3])
xlabel方法和ylabel方法
plt.ylabel('y = x^2 + 5',rotation = 60)旋转
loc参数能够是2元素的元组,表示图例左下角的坐标
plt.plot(x,x,x,x*2,x,x*0.5)
# 使用loc参数设置图例位置
plt.legend(['nomral','fast','slow'],loc=[-0.3,0.3])
图例也能够超过图的界限loc = (-0.1,0.9)
ncol控制图例中有几列,在legend中设置ncol,须要设置loc
plt.plot(x,x,x,x*2,x,x*0.5)
# 使用nloc参数设置图例的列数
plt.legend(['nomral','fast','slow'],loc=9,ncol=3)
修改线条样式
x = np.random.randint(-20,30,size=(100,3))
df = DataFrame(x)
df
plt.plot(df.index,df[0].cumsum(),linestyle='--',color='red',marker='o')
plt.plot(df.index,df[1].cumsum(),linestyle='-.',color='blue',marker='H')
plt.plot(df.index,df[2].cumsum(),ls=':',color='green',marker='d')
plt.legend(['one','two','three'])
使用figure对象的savefig的函数
# 获取fig对象
fig = plt.figure()
x = np.arange(-np.pi,np.pi,0.1)
plt.plot(x,np.sin(x))
fig.savefig('dancer.png',dpi=100,facecolor='blue')
fig.savefig('dancer.jpg',dpi=100,facecolor='green')
png = plt.imread('dancer.png')
jpg = plt.imread('dancer.jpg')
display(png,jpg)
plot语句中支持除X,Y之外的参数,以字符串形式存在,来控制颜色、线型、点型等要素,语法形式为:
plt.plot(X, Y, 'format', ...)
参数color或c
x = np.arange(0,100)
plt.plot(x,x**2,c = 'm')
颜色 | 别名 | HTML颜色名 | 颜色 | 别名 | HTML颜色名 |
---|---|---|---|---|---|
蓝色 | b | blue | 绿色 | g | green |
红色 | r | red | 黄色 | y | yellow |
青色 | c | cyan | 黑色 | k | black |
洋红色 | m | magenta | 白色 | w | white |
plt.plot(x,x,color='#0000ff')
plt.plot(x,2*x,color = '#00ff00')
plt.plot(x,x/2,color = '#ff0000')
plt.plot(x,x,color=(0.3,0.3,0.4))
alpha参数
plt.plot(x,x,color=(0.3,0.3,0.4),alpha=0.1)
设置背景色,经过plt.subplot()方法传入facecolor参数,来设置坐标系的背景色
# 使用坐标系对象绘制图形
# fig = plt.figure() # 经过此方法能获得画布对象
axes = plt.subplot(facecolor='c')
axes.plot(x,x,color = 'g')
plt.subplot(facecolor = 'yellow')
plt.plot(x,np.sin(x),color='red')
参数linestyle或ls
线条风格 | 描述 | 线条风格 | 描述 |
---|---|---|---|
'-' | 实线 | ':' | 虚线 |
'--' | 破折线 | 'steps' | 阶梯线 |
'-.' | 点划线 | 'None' / ',' | 什么都不画 |
x = np.arange(0,100,5)
plt.plot(x,x,linestyle = '-',linewidth=1)
plt.plot(x,x*2,linestyle = '--',linewidth=2)
plt.plot(x,x*3,ls = '-.',lw=3)
plt.plot(x,x*4,ls = ':',lw=4)
plt.plot(x,x*5,ls = 'steps',lw=5)
linewidth或lw参数
dashes参数 eg.dashes = [20,50,5,2,10,5]
设置破折号序列各段的宽度
x = np.arange(-np.pi,np.pi,0.1)
plt.plot(x,np.sin(x),dashes=[5,1,10,2,20,4])
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'1' | 一角朝下的三脚架 | '3' | 一角朝左的三脚架 |
'2' | 一角朝上的三脚架 | '4' | 一角朝右的三脚架 |
x = np.arange(0,10,1)
plt.plot(x,x,marker = '3',markersize=15)
plt.plot(x,2*x,marker = '4',markersize=15)
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
's' | 正方形 | 'p' | 五边形 |
'h' | 六边形1 | 'H' | 六边形2 |
'8' | 八边形 |
plt.plot(x,x,marker = 's',markersize = 30)
plt.plot(x,2*x,marker = 'p',markersize = 40)
plt.plot(x,3*x,marker = 'h',markersize = 30)
plt.plot(x,4*x,marker = '8',markersize = 30)
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'.' | 点 | 'x' | X |
'*' | 星号 | '+' | 加号 |
',' | 像素 |
plt.plot(x,x,marker = '.',markersize = 30)
plt.plot(x,2*x,marker = 'x',markersize = 30)
plt.plot(x,3*x,marker = '*',markersize = 30)
plt.plot(x,4*x,marker = ',',markersize = 30)
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'o' | 圆圈 | 'D' | 菱形 |
'd' | 小菱形 | '','None',' ',None | 无 |
plt.plot(x,x,marker = 'o',markersize = 30)
plt.plot(x,2*x,marker = 'D',markersize = 30)
plt.plot(x,3*x,marker = 'd',markersize = 30)
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'_' | 水平线 | '|' | 竖线 |
plt.plot(x,x,marker = '|',markersize = 30)
plt.plot(x,2*x,marker = '_',markersize = 30)
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'v' | 一角朝下的三角形 | '<' | 一角朝左的三角形 |
'^' | 一角朝上的三角形 | '>' | 一角朝右的三角形 |
plt.plot(x,x,marker = 'v',markersize = 30)
plt.plot(x,2*x,marker = '<',markersize = 30)
plt.plot(x,3*x,marker = '>',markersize = 30)
plt.plot(x,4*x,marker = '^',markersize = 30)
颜色、点型、线型,能够把几种参数写在一个字符串内进行设置 'r-.o'
plt.plot(x,x,'r-.o')
参数 | 描述 | 参数 | 描述 |
---|---|---|---|
color或c | 线的颜色 | linestyle或ls | 线型 |
linewidth或lw | 线宽 | marker | 点型 |
markeredgecolor | 点边缘的颜色 | markeredgewidth | 点边缘的宽度 |
markerfacecolor | 点内部的颜色 | markersize | 点的大小 |
plt.plot(x,x,marker = 'H',markersize = 30,markeredgecolor = 'm',markeredgewidth=2,markerfacecolor='b',lw=10,c='blue')
属性名声明,不能够多参数连用
plt.plot(x1, y1, x2, y2, fmt, ...)
plt.plot(x,x,x,2*x,color = 'c',ls='--',marker='d')
多个都进行设置时,多参数连用 plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...)
plt.plot(x,x,'r-.h',x,2*x,'b-->')
# plt.plot函数,返回值的呗绘制的包含每一条线对象的列表
lines = plt.plot(x,x,x,x*2,x,x*3)
# 能够经过line对象进行设置外观
lines[0].set_linewidth(10)
lines[1].set_linestyle('--')
lines[2].set_color('red')
axes = plt.subplot(111)
axes.set_title('axes_title')
axes.set_xlabel('X-Label')
axes.set_ylabel('Y-Label')
axes.set_facecolor('yellow')
axes.set_xticklabels(['-pi',0,'pi'])
axes.set_yticklabels(['min',0,'max'])
axes.set_xticks([-np.pi,0,np.pi])
axes.set_yticks([-1,0,1])
x = np.arange(-np.pi,np.pi,0.1)
axes.plot(x,np.sin(x))
lines = plt.plot(x,x,x,x*2,x,np.sin(x))
plt.setp(lines[0],color='red',ls='--',lw=4)
axes = plt.subplot()
# p->> property属性
plt.setp(axes,title='title')
plt.xticks()和plt.yticks()方法
x = np.arange(0,10,1)
plt.plot(x,x*2)
# 使用plt来设置坐标轴刻度
# 新的刻度标签最好与原始的刻度标签保持一致
# eg1:使用原始刻度
plt.xticks([0,2,4,6,8],list('abcde'))
# 在matplotlib里显示汉字的方法
# eg2:修改原始刻度
plt.yticks([0,4,8,12,16],['ok','good','very good','good good','vv good'])
LaTex语法,用ππ、σσ等表达式在图表上写上希腊字母
x = np.arange(-np.pi,np.pi,0.1)
plt.plot(x,np.sin(x),x,np.cos(x))
# 第一个列表写新的刻度值,注意不要越界(可能会显示不出来)
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
plt.yticks([-1,0,1],['min',0,'max'])
【直方图的参数只有一个x!!!不像条形图须要传入x,y】
hist()的参数
x = np.random.randint(1,100,50)
x
plt.hist(x,bins=10,normed=True,color = 'r',orientation='horizontal')
【条形图有两个参数x,y】
bar()、barh()
x = Series(np.array([3,5,7,8,9,2,4]))
plt.bar(x.index,height = x.values)
plt.barh(x.index,width=x.values)
【饼图也只有一个参数x!】
pie()
饼图适合展现各部分占整体的比例,条形图适合比较各部分的大小
普通各部分占满饼图
x = [89,45,32,16]
plt.pie(x)
普通未占满饼图
x = [0.1,0.3,0.5]
plt.pie(x)
饼图阴影、分裂等属性设置
x = [89,45,32,16]
plt.pie(x,labels=['boy','girl','bgirl','gboy'],labeldistance=0.3,autopct='%1.1f%%',pctdistance=0.8,
explode=[0,0,0,0.2],colors=['m','c','purple','yellow'],shadow=True,startangle=90)
【散点图须要两个参数x,y,但此时x不是表示x轴的刻度,而是每一个点的横坐标!】
scatter()
x = np.random.normal(size = 1000)
y = np.random.normal(size = 1000)
# [0.3,0.6,0.8] 这样的一个数就能够表示一个颜色
# 随机生成1000个颜色
color = np.random.random(size = (1000,3))
# s表示marker的大小
plt.scatter(x,y,marker='d',color=color,s = 30)
控制文字属性的方法:
pyplot函数 | API方法 | 描述 |
---|---|---|
text() | mpl.axes.Axes.text() | 在Axes对象的任意位置添加文字 |
xlabel() | mpl.axes.Axes.set_xlabel() | 为X轴添加标签 |
ylabel() | mpl.axes.Axes.set_ylabel() | 为Y轴添加标签 |
title() | mpl.axes.Axes.set_title() | 为Axes对象添加标题 |
legend() | mpl.axes.Axes.legend() | 为Axes对象添加图例 |
figtext() | mpl.figure.Figure.text() | 在Figure对象的任意位置添加文字 |
suptitle() | mpl.figure.Figure.suptitle() | 为Figure对象添加中心化的标题 |
annnotate() | mpl.axes.Axes.annotate() | 为Axes对象添加注释(箭头可选) |
全部的方法会返回一个matplotlib.text.Text对象
x = np.arange(-np.pi,np.pi,0.1)
plt.plot(x,np.sin(x))
# 画布 fig = plt.figure()
# 坐标系 axes = plt.subplot()
axes = plt.subplot()
axes.text(0.5,0.4,'test')
axes.set_xlabel('X-Label')
axes.set_ylabel('Ylabel')
axes.set_title('title')
fig = plt.figure(figsize=(8,4))
axes1 = plt.subplot(1,2,1)
axes2 = plt.subplot(1,2,2)
axes1.plot(x,np.sin(x))
axes2.plot(x,np.cos(x))
fig.text(0.4,0.5,'test')
fig.suptitle('suptitle')
axes1.set_title('title1')
axes2.set_title('title2')
text()
annotate()
以下都是arrowstyle能够选择的风格样式 ``'->'`` head_length=0.4,head_width=0.2 ``'-['`` widthB=1.0,lengthB=0.2,angleB=None ``'|-|'`` widthA=1.0,widthB=1.0 ``'-|>'`` head_length=0.4,head_width=0.2 ``'<-'`` head_length=0.4,head_width=0.2 ``'<->'`` head_length=0.4,head_width=0.2 ``'<|-'`` head_length=0.4,head_width=0.2 ``'<|-|>'`` head_length=0.4,head_width=0.2 ``'fancy'`` head_length=0.4,head_width=0.4,tail_width=0.4 ``'simple'`` head_length=0.5,head_width=0.5,tail_width=0.2 ``'wedge'`` tail_width=0.3,shrink_factor=0.5
x = np.arange(-np.pi,np.pi,0.1)
axes = plt.subplot()
plt.plot(x,np.sin(x))
# 模式1:使用arrowstyle键,能够选择如上几种预约义的箭头样式
axes.annotate(s='annotation2',xy=[-1.7,-1],xytext=[0.5,-0.5],arrowprops = {'arrowstyle':'fancy'})
# 模式2:不适用arrowstyle键,能够使用{'headlength':10,'headwidth':16,'shrink':0.1来自定义样式
axes.annotate(s='annotation1',xy=[1.7,1],xytext=[-0.5,0.5],arrowprops = {'headlength':10,'headwidth':16,'shrink':0.1})
练习
三个随机正太分布数据
index = np.arange(100)
x = np.random.normal(loc=10,scale=3,size=100)
y = np.random.normal(loc=20,scale=3,size=100)
z = np.random.normal(loc=30,scale=3,size=100)
axes = plt.subplot()
axes.plot(index,x,index,y,index,z)
axes.legend(['plot','2nd plot','last plot'],loc=[0,1.05],ncol=3)
axes.annotate(s='Important value',xy=[50,20],xytext=[15,35],fontsize=15,arrowprops={'arrowstyle':'->'})
导包
使用mershgrid函数切割x,y轴
建立3d坐标系
绘制3d图形
添加colorbar
from mpl_toolkits.mplot3d.axes3d import Axes3D
x = np.arange(100)
y = np.arange(100)
xx,yy = np.meshgrid(x,y)
def create_z(xx,yy):
return np.cos(xx)+np.sin(yy)
z = create_z(xx,yy)
print(z.shape)
axes = plt.subplot(projection = '3d')
p = axes.plot_surface(xx,yy,z,cmap='summer')
plt.colorbar(p,shrink=0.5)
x = np.array([1,2,3])
y = np.array([4,5,6])
xx,yy = np.meshgrid(x,y)
display(xx,yy)
建立极坐标,设置polar属性
绘制极坐标条形图
plt.axes(polar=True)
index = np.arange(-np.pi,np.pi,2*np.pi/6)
plt.bar(x=index,height=[2,3,4,5,6,7],width = 2*np.pi/6)