赞
踩
一、【重点】Matplotlib基础知识
二、设置plot的风格和样式
1、【重点】点和线的样式
2、X、Y轴坐标刻度
三、2D图形
1、示例
2、【重点】直方图
3、【重点】条形图
4、【重点】饼图
5、【重点】散点图
=============以上为重点=================
下面的自学
0.45045045, 0.46546547, 0.48048048, 0.4954955 , 0.51051051,
四、图形内的文字、注释、箭头
1、图形内的文字
2、注释
3、箭头
五、3D图
1、曲面图
Matplotlib中的基本图表包括的元素
In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [ ]:
#pandas 绘图,提供方便
#matplotlib专门绘图工具,样式更加丰富
In [2]:
#用linspace生成10个均匀间隔的数字
x = np.linspace(0,10,10)
x
Out[2]:
array([ 0. , 1.11111111, 2.22222222, 3.33333333, 4.44444444,
5.55555556, 6.66666667, 7.77777778, 8.88888889, 10. ])
In [3]:
#假如plot里面的参数只有一个,x轴的坐标默认从0,1,2...
plt.plot(x)
Out[3]:
[<matplotlib.lines.Line2D at 0x7f7145a12be0>]
In [4]:
#假如plot里面是2个参数,那么就有x轴、y轴,参数可以是函数
plt.plot(x,x**2)
Out[4]:
[<matplotlib.lines.Line2D at 0x7f713d96eb38>]
In [5]:
#scatter,绘制散点图
plt.scatter(x,x**2)
Out[5]:
<matplotlib.collections.PathCollection at 0x7f713d868be0>
1、可以使用多个plot函数(推荐),在一个图中绘制多个曲线
In [6]:
#arange,重新生成一组,等差数组
x = np.arange(0,10,1)
x
Out[6]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [7]:
plt.plot(x,x*2)
plt.plot(x,x/2)
plt.plot(x,x**2)
Out[7]:
[<matplotlib.lines.Line2D at 0x7f713d7dcda0>]
In [8]:
plt.plot(x,x*2)
plt.plot(x,x*5)
plt.plot(x,np.sin(x))
Out[8]:
[<matplotlib.lines.Line2D at 0x7f713d7cdb38>]
2、也可以在一个plot函数中传入多对X,Y值,在一个图中绘制多个曲线
In [9]:
#y轴会自动用不同的颜色显示
lines = plt.plot(x,x*2,x,x*5,x,x/2)
In [10]:
lines[0]
Out[10]:
<matplotlib.lines.Line2D at 0x7f713d782ac8>
绘制正选余弦
In [11]:
x = np.linspace(0,15,1000)
y = np.sin(x)
In [12]:
display(x,y)
array([ 0. , 0.01501502, 0.03003003, 0.04504505, 0.06006006,
......
14.86486486, 14.87987988, 14.89489489, 14.90990991, 14.92492492,
0.74670761, 0.73663654, 0.7263994 , 0.71599849, 0.70543617,
0.69471481, 0.68383682, 0.67280467, 0.66162083, 0.65028784])
使用plt.grid(True)方法为图添加网格线
In [13]:
plt.plot(x,y)
plt.grid(True)
In [14]:
#另外一种产生随机数的方式,对比一下
#用np.pi产生数据,用到arange
x = np.arange(-np.pi,np.pi,0.01)
display(x)
array([-3.14159265e+00, -3.13159265e+00, -3.12159265e+00, -3.11159265e+00,
-3.10159265e+00, -3.09159265e+00, -3.08159265e+00, -3.07159265e+00,
-3.06159265e+00, -3.05159265e+00, -3.04159265e+00, -3.03159265e+00,
-3.02159265e+00, -3.01159265e+00, -3.00159265e+00, -2.99159265e+00,
3.05840735e+00, 3.06840735e+00, 3.07840735e+00, 3.08840735e+00,
3.09840735e+00, 3.10840735e+00, 3.11840735e+00, 3.12840735e+00,
3.13840735e+00])
In [15]:
plt.plot(x,np.sin(x),x,np.cos(x))
plt.grid(True)
设置grid参数(参数与plot函数相同),使用plt面向对象的方法,创建多个子图显示不同网格线
In [16]:
x = np.arange(-20,20,0.1)
y = np.sin(x)
In [17]:
#使用plt创建子视图
#axis 轴;axes 面
#sub = 子
#figsize=(12,9)是对视图的大小进行设置
plt.figure(figsize=(12,9))
#subplot(1,3,1),子视图,1为一行,3为三列,1为第一个
axes1 = plt.subplot(1,3,1)
axes1.plot(x,y)
axes1.grid(True)
axes2 = plt.subplot(1,3,2)
axes2.plot(x,y)
axes2.grid(True,axis = 'x',color = 'purple',alpha = 0.1) #可以Shift+Tab查看具体的方法参数
axes3 = plt.subplot(1,3,3)
x3 = np.linspace(0,6,200)
y3 = np.cos(x3)
axes3.plot(x3,y3)
axes3.grid(True,color = 'g',linestyle = '--',linewidth = 2)
axis方法
如果axis方法没有任何参数,则返回当前坐标轴的上下限axis(xmin =,ymax = )
In [18]:
x = np.arange(0,5,0.01)
y = np.sin(x)
plt.plot(x,y)
#axis 轴:x,y
#axes 面,子视图
plt.axis([-5,10,-2,np.pi])
Out[18]:
(-5.0, 10.0, -2.0, 3.141592653589793)
plt.axis('xxx') 'tight'、'off'、'equal'……
设置坐标轴类型
关闭坐标轴
In [19]:
plt.plot(x,y)
plt.axis('off') #axis('off') 将坐标轴关闭,tight是默认
Out[19]:
(-0.24950000000000003,
5.2395000000000005,
-1.0999969878536957,
1.0999995243978122)
In [20]:
x = np.linspace(-np.pi,np.pi,1000)
#plt.figure(figsize=(4,4))
#figsize=(4,4)与axis('equal')的效果差不多
plt.plot(np.sin(x),np.cos(x))
plt.axis('equal') #axis('equal') 改变最大值、最小值的范围
Out[20]:
(-1.0999986402114572,
1.0999986402114572,
-1.0999997527658723,
1.0999948080833182)
In [21]:
#没有使用axis('equal'),就变成了椭圆
plt.plot(np.sin(x),np.cos(x))
Out[21]:
[<matplotlib.lines.Line2D at 0x7f713c941a58>]
xlim方法和ylim方法
除了plt.axis方法,还可以通过xlim,ylim方法设置坐标轴范围
In [22]:
plt.plot(np.sin(x),np.cos(x))
plt.xlim(-2,2)
plt.ylim(0,2)
Out[22]:
(0.0, 2.0)
### 坐标轴标签
xlabel方法和ylabel方法
plt.ylabel('y = x^2 + 5',rotation = 85)旋转
In [23]:
x = np.linspace(0,5,1000)
y = x**2 + 5
plt.plot(x,y,'red')
plt.xlabel('X',size = 20)
plt.ylabel('f(x) = x^2 + 5',rotation = 85,fontsize = 20)
Out[23]:
Text(0, 0.5, 'f(x) = x^2 + 5')
title方法
In [24]:
x = np.linspace(0,5,1000)
y = x**2 + 5
plt.plot(x,y,'red')
# Set a title of the current axes.
plt.title('function(x):x^2 + 5',size = 18,verticalalignment = 'bottom')
Out[24]:
Text(0.5, 1.0, 'function(x):x^2 + 5')
legend方法
两种传参方法:
In [25]:
x = np.arange(0,10,1)
plt.plot(x,x*4,label = 'fast')
plt.plot(x,x/2,label = 'slow')
plt.plot(x,x,label = 'normal')
#label要想显示,调用legend方发
plt.legend()
Out[25]:
<matplotlib.legend.Legend at 0x7f713c895fd0>
In [26]:
x = np.arange(0,10,1)
plt.plot(x,x*4)
plt.plot(x,x/2)
plt.plot(x,x)
#label要想显示,调用legend方发,下面是通过参数的数组形式传递
plt.legend(['fast','slow','normal'])
Out[26]:
<matplotlib.legend.Legend at 0x7f713ad3b9b0>
label参数为'xxx',则图例中不显示
plt.plot(x, x*1.5, label = 'xxx')
In [27]:
x = np.arange(0,10,1)
plt.plot(x,x*4,label = 'fast')
plt.plot(x,x/2,label = '_slow') #加个下划线“_”,就不会显示
plt.plot(x,x,label = 'normal')
#label要想显示,调用legend方发
plt.legend()
Out[27]:
<matplotlib.legend.Legend at 0x7f713acba748>
字符串 | 数值 | 字符串 | 数值 |
best | 0 | center left | 6 |
upper right | 1 | center right | 7 |
upper left | 2 | lower center | 8 |
lower left | 3 | upper center | 9 |
lower right | 4 | center | 10 |
right | 5 |
|
|
In [28]:
x = np.arange(0,10,1)
plt.plot(x,x*4,label = 'fast')
plt.plot(x,x/2,label = 'slow')
plt.plot(x,x,label = 'normal')
x = np.ones(10)
y = np.arange(0,40,4)
plt.plot(x,y)
#label要想显示,调用legend方发
plt.legend(loc = 4)
Out[28]:
<matplotlib.legend.Legend at 0x7f713ac3c5c0>
loc参数可以是2元素的元组,表示图例左下角的坐标
In [29]:
x = np.arange(0,10,1)
plt.plot(x,x*4,label = 'fast')
plt.plot(x,x/2,label = 'slow')
plt.plot(x,x,label = 'normal')
x = np.ones(10)
y = np.arange(0,40,4)
plt.plot(x,y)
#label要想显示,调用legend方发
#loc 元组,相对值,宽、高
plt.legend( bbox_to_anchor=(0, 1,1,0),mode = 'expand')
Out[29]:
<matplotlib.legend.Legend at 0x7f713abb9898>
图例也可以超过图的界限loc = (-0.1,0.9)
ncol控制图例中有几列
In [30]:
x = np.arange(0,10,1)
plt.plot(x,x*4,label = 'fast')
plt.plot(x,x/2,label = 'slow')
plt.plot(x,x,label = 'normal')
x = np.ones(10)
y = np.arange(0,40,4)
plt.plot(x,y)
#label要想显示,调用legend方发
#loc 元组,相对值,宽高
#bbox_to_anchor 后两个参数是图例的宽高
#前两个参数,坐标
plt.legend( bbox_to_anchor=(0,1,1,0),mode = 'expand',ncol = 3) #ncol = 3,3列
Out[30]:
<matplotlib.legend.Legend at 0x7f713c8732b0>
修改线条样式
In [31]:
y1 = np.random.normal(loc = 0 ,scale= 1,size=100)
y2 = np.random.normal(loc = 10,scale= 1.5,size = 100)
y3 = np.random.normal(loc= - 10 ,scale= 1,size = 100)
plt.plot(y1,linestyle = '--',color = 'green',marker = '+')
plt.plot(y2,linestyle = '-.')
plt.plot(y3,marker = 'v',color = 'cyan')
Out[31]:
[<matplotlib.lines.Line2D at 0x7f713c844d68>]
figure.savefig的选项
In [32]:
y1 = np.random.normal(loc = 0 ,scale= 1,size=100)
y2 = np.random.normal(loc = 10,scale= 1.5,size = 100)
y3 = np.random.normal(loc= - 10 ,scale= 1,size = 100)
plt.plot(y1,linestyle = '--',color = 'green',marker = '+')
plt.plot(y2,linestyle = '-.')
plt.plot(y3,marker = 'v',color = 'cyan')
plt.savefig('fig2.jpg',facecolor = 'red',dpi = 100)
plot语句中支持除X,Y以外的参数,以字符串形式存在,来控制颜色、线型、点型等要素,语法形式为:
plt.plot(X, Y, 'format', ...)
颜色
参数color或c
In [33]:
x = np.linspace(0,10,100)
plt.plot(x,x,c = 'black')
Out[33]:
[<matplotlib.lines.Line2D at 0x7f713c6f0780>]
In [34]:
plt.plot(x,np.sin(x),c = '#100000')
Out[34]:
[<matplotlib.lines.Line2D at 0x7f713c94b2e8>]
颜色值的方式
颜色 | 别名 | HTML颜色名 | 颜色 | 别名 | HTML颜色名 |
蓝色 | b | blue | 绿色 | g | green |
红色 | r | red | 黄色 | y | yellow |
青色 | c | cyan | 黑色 | k | black |
洋红色 | m | magenta | 白色 | w | white |
In [35]:
#ff = 255
#只能使用6位进行表示,红绿蓝
plt.plot(x,x,color = '#887700')
Out[35]:
[<matplotlib.lines.Line2D at 0x7f713aabce48>]
In [36]:
#RGB元组,color
plt.plot(x,x,color = (0.1,0.2,0.7))
Out[36]:
[<matplotlib.lines.Line2D at 0x7f713aaa8be0>]
透明度
alpha参数
In [37]:
plt.plot(x,x,color = (0.1,0.2,0.7),alpha = 0.5)
Out[37]:
[<matplotlib.lines.Line2D at 0x7f713aa73b70>]
背景色
设置背景色,通过plt.subplot()方法传入facecolor参数,来设置坐标轴的背景色
In [38]:
axes = plt.subplot(facecolor = 'green')
axes.plot(x,x,'r')
Out[38]:
[<matplotlib.lines.Line2D at 0x7f713a9edcc0>]
#### 线型
参数linestyle或ls
线条风格 | 描述 |
'-' | 实线 |
'--' | 破折线 |
'-.' | 点划线 |
':' | 虚线 |
'None'/‘,’ | 什么都不画 |
linestyle可选参数
In [39]:
x = np.linspace(0,10,100)
plt.plot(x,np.sin(x),ls = '-.')
Out[39]:
[<matplotlib.lines.Line2D at 0x7f713a953710>]
线宽
linewidth或lw参数
In [48]:
x = np.linspace(0,10,100)
plt.plot(x,np.sin(x),linestyle = 'dotted',linewidth = 4)
Out[48]:
[<matplotlib.lines.Line2D at 0x7f713a487ba8>]
不同宽度的破折线
dashes参数
设置破折号序列各段的宽度
In [49]:
x = np.linspace(0,10,100)
#dashes列表中参数:第一条线长度,间隔,第二条线长度,间隔
plt.plot(x,np.sin(x),dashes = [10,10,3,4,6,2])
Out[49]:
[<matplotlib.lines.Line2D at 0x7f713a49ab38>]
点型
marker参数
标记 | 描述 | 标记 | 描述 |
'1' | 一角朝下的三脚架 | '3' | 一角朝左的三脚架 |
'2' | 一角朝上的三脚架 | '4' | 一角朝右的三脚架 |
In [50]:
x = np.linspace(0,10,100)
#dashes列表中参数:第一条线长度,间隔,第二条线长度,间隔
plt.plot(x,np.sin(x),dashes = [10,10,3,4,6,2],marker = '3',markersize = 10)
Out[50]:
[<matplotlib.lines.Line2D at 0x7f713a3da128>]
标记 | 描述 | 标记 | 描述 |
's' | 正方形 | 'p' | 五边形 |
'h' | 六边形1 | 'H' | 六边形2 |
'8' | 八边形 |
|
|
In [51]:
x = np.linspace(0,10,20)
#dashes列表中参数:第一条线长度,间隔,第二条线长度,间隔
plt.plot(x,np.sin(x),dashes = [10,10,3,4,6,2],marker = 'p',markersize = 10)
Out[51]:
[<matplotlib.lines.Line2D at 0x7f713a33aba8>]
标记 | 描述 | 标记 | 描述 |
'.' | 点 | 'x' | X |
'*' | 星号 | '+' | 加号 |
',' | 像素 |
|
|
In [52]:
x = np.linspace(0,10,20)
#dashes列表中参数:第一条线长度,间隔,第二条线长度,间隔
plt.plot(x,np.sin(x),dashes = [10,10,3,4,6,2],marker = ',',markersize = 10)
Out[52]:
[<matplotlib.lines.Line2D at 0x7f713a29d080>]
标记 | 描述 | 标记 | 描述 |
'o' | 圆圈 | 'D' | 菱形 |
'd' | 小菱形 | '','None',' ',None | 无 |
In [53]:
x = np.linspace(0,10,20)
#dashes列表中参数:第一条线长度,间隔,第二条线长度,间隔
plt.plot(x,np.sin(x),dashes = [10,10,3,4,6,2],marker = 'o',markersize = 10)
Out[53]:
[<matplotlib.lines.Line2D at 0x7f713a211390>]
标记 | 描述 | 标记 | 描述 |
'_' | 水平线 | '|' | 水平线 |
In [54]:
x = np.linspace(0,10,20)
#dashes列表中参数:第一条线长度,间隔,第二条线长度,间隔
plt.plot(x,np.sin(x),dashes = [10,10,3,4,6,2],marker = '_',markersize = 30)
Out[54]:
[<matplotlib.lines.Line2D at 0x7f713a518cf8>]
标记 | 描述 | 标记 | 描述 |
'v' | 一角朝下的三角形 | '<' | 一角朝左的三角形 |
'^' | 一角朝上的三角形 | '>' | 一角朝右的三角形 |
In [55]:
x = np.linspace(0,10,20)
#dashes列表中参数:第一条线长度,间隔,第二条线长度,间隔
plt.plot(x,np.sin(x),dashes = [10,10,3,4,6,2],marker = '^',markersize = 10)
Out[55]:
[<matplotlib.lines.Line2D at 0x7f713a3e2cf8>]
多参数连用
颜色、点型、线型
In [56]:
x = np.linspace(0,10,100)
#dashes列表中参数:第一条线长度,间隔,第二条线长度,间隔
plt.plot(x,np.sin(x),'r--<')
Out[56]:
[<matplotlib.lines.Line2D at 0x7f713a17d6d8>]
更多点和线的设置
参数 | 描述 | 参数 | 描述 |
color或c | 线的颜色 | linestyle或ls | 线型 |
linewidth或lw | 线宽 | marker | 点型 |
markeredgecolor | 点边缘的颜色 | markeredgewidth | 点边缘的宽度 |
markerfacecolor | 点内部的颜色 | markersize | 点的大小 |
In [57]:
x = np.arange(0,10,1)
plt.plot(x,x,'r-.o',markersize = 10,markeredgecolor = 'green',markerfacecolor = 'purple',markeredgewidth = 5)
Out[57]:
[<matplotlib.lines.Line2D at 0x7f713a694d68>]
在一条语句中为多个曲线进行设置
多个曲线同一设置
属性名声明
plt.plot(x1, y1, x2, y2, fmt, ...)
In [58]:
plt.plot(x,x,x,2*x,color = 'r',linestyle = ':')
Out[58]:
[<matplotlib.lines.Line2D at 0x7f713a0ce128>,
<matplotlib.lines.Line2D at 0x7f713a078780>]
多个曲线不同设置
多个都进行设置时,无需声明属性 plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...)
In [ ]:
plt.plot(x,x,'g--o',x,2*x,'r:v')
Out[ ]:
[<matplotlib.lines.Line2D at 0x7fbb6ed977b8>,
<matplotlib.lines.Line2D at 0x7fbb6ed97940>]
In [59]:
plt.plot(x,x,color = 'g',x,2*x,color = 'r')
File "<ipython-input-59-420939186529>", line 1 plt.plot(x,x,color = 'g',x,2*x,color = 'r')
^SyntaxError: positional argument follows keyword argument
三种设置方式
向方法传入关键字参数
In [60]:
plt.plot(x,x,x,2*x,color = 'r')
Out[60]:
[<matplotlib.lines.Line2D at 0x7f713a0912b0>,
<matplotlib.lines.Line2D at 0x7f713a05eb00>]
对实例使用一系列的setter方法
In [61]:
axes1 = plt.subplot()
In [62]:
line1,line2, = plt.plot(x,x,x,2*x)
#现在有了具体的对象了,当然就可以进行设置
line1.set_alpha(0.3)
line1.set_ls('--')
line2.set_marker('*')
line2.set_markersize(10)
使用setp()方法
In [63]:
line1,line2, = plt.plot(x,x,x,2*x)
#属性property
plt.setp([line1,line2],linestyle = '--',color = 'r')
Out[63]:
[None, None, None, None]
xticks()和yticks()方法
In [64]:
x = np.linspace(0,10,1000)
plt.plot(x,np.sin(x))
plt.yticks([-1,0,1],['min',0,'max'])
plt.xticks(np.arange(10),list('abcdefhjik'))
Out[64]:
([<matplotlib.axis.XTick at 0x7f7139ecd748>,
<matplotlib.axis.XTick at 0x7f7139ecd470>,
<matplotlib.axis.XTick at 0x7f7139ecd0b8>,
<matplotlib.axis.XTick at 0x7f7139e7d4a8>,
<matplotlib.axis.XTick at 0x7f7139e7d940>,
<matplotlib.axis.XTick at 0x7f7139e7ddd8>,
<matplotlib.axis.XTick at 0x7f7139e872b0>,
<matplotlib.axis.XTick at 0x7f7139e87748>,
<matplotlib.axis.XTick at 0x7f7139e87be0>,
<matplotlib.axis.XTick at 0x7f7139e8f0b8>],
[Text(0, 0, 'a'),
Text(1, 0, 'b'),
Text(2, 0, 'c'),
Text(3, 0, 'd'),
Text(4, 0, 'e'),
Text(5, 0, 'f'),
Text(6, 0, 'h'),
Text(7, 0, 'j'),
Text(8, 0, 'i'),
Text(9, 0, 'k')])
面向对象方法
set_xticks、set_yticks、set_xticklabels、set_yticklabels方法
In [65]:
x = np.linspace(0,10,1000)
axes = plt.subplot()
axes.plot(x,np.sin(x))
#设置对象的属性(刻度值、标签)
axes.set_yticks([-1,0,1])
axes.set_yticklabels(['min',0,'max'])
Out[65]:
[Text(0, -1, 'min'), Text(0, 0, '0'), Text(0, 1, 'max')]
正弦余弦
LaTex语法,用ππ等表达式在图表上写上希腊字母
In [66]:
np.arange(0,12,np.pi/2)
Out[66]:
array([ 0. , 1.57079633, 3.14159265, 4.71238898, 6.28318531,
7.85398163, 9.42477796, 10.99557429])
In [67]:
np.linspace(0,2*np.pi,5)
Out[67]:
array([0. , 1.57079633, 3.14159265, 4.71238898, 6.28318531])
In [68]:
x = np.linspace(0,2*np.pi,1000)
plt.plot(x,np.sin(x),x,np.cos(x))
plt.yticks(np.arange(-1,2),['min',0,'max'])
plt.xticks(np.linspace(0,2*np.pi,5),[0,'$\sigma/2$','$\delta$','$3\pi/2$','$2\pi$'],size = 20)
Out[68]:
([<matplotlib.axis.XTick at 0x7f7139e080b8>,
<matplotlib.axis.XTick at 0x7f7139e05c50>,
<matplotlib.axis.XTick at 0x7f7139e05898>,
<matplotlib.axis.XTick at 0x7f7139db90f0>,
<matplotlib.axis.XTick at 0x7f7139db9588>],
[Text(0.0, 0, '0'),
Text(1.5707963267948966, 0, '$\\sigma/2$'),
Text(3.141592653589793, 0, '$\\delta$'),
Text(4.71238898038469, 0, '$3\\pi/2$'),
Text(6.283185307179586, 0, '$2\\pi$')])
【直方图的参数只有一个x!!!不像条形图需要传入x,y】
hist()的参数
In [77]:
x = np.random.randint(0,10,10)
x
Out[77]:
array([3, 8, 1, 4, 9, 2, 3, 6, 9, 6])
In [78]:
plt.hist(x,density=True)
Out[78]:
(array([0.125, 0.125, 0.25 , 0.125, 0. , 0. , 0.25 , 0. , 0.125,
0.25 ]),
array([1. , 1.8, 2.6, 3.4, 4.2, 5. , 5.8, 6.6, 7.4, 8.2, 9. ]),
<BarContainer object of 10 artists>)
【条形图有两个参数x,y!】
bar()、barh()
In [79]:
x = [1,2,3,5,6]
y = [4,7,9,2,10]
plt.bar(x,y,width = 0.2)
Out[79]:
<BarContainer object of 5 artists>
水平条形图
barh()
In [80]:
plt.barh(x,y)
Out[80]:
<BarContainer object of 5 artists>
【饼图也只有一个参数x!】
pie()
饼图适合展示各部分占总体的比例,条形图适合比较各部分的大小
普通各部分占满饼图
In [81]:
x = [0.3,0.4,0.3]
plt.pie(x,labels = ['Dog','Cat','Orther'])
plt.axis('equal')
plt.show()
普通未占满饼图
In [82]:
x = [0.3,0.4,0.25]
plt.pie(x,labels = ['A','B','C'])
plt.axis('equal')
plt.show()
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: MatplotlibDeprecationWarning: normalize=None does not normalize if the sum is less than 1 but this behavior is deprecated since 3.3 until two minor releases later. After the deprecation period the default value will be normalize=True. To prevent normalization pass normalize=False
饼图阴影、分裂等属性设置
#labels参数设置每一块的标签;labeldistance参数设置标签距离圆心的距离(比例值)
#autopct参数设置比例值的显示格式(%1.1f%%);pctdistance参数设置比例值文字距离圆心的距离
#explode参数设置每一块顶点距圆形的长度(比例值);colors参数设置每一块的颜色;
#shadow参数为布尔值,设置是否绘制阴影
In [83]:
x = [0.2,0.15,0.15,0.1,0.1,0.2,0.1]
labels = ['USA','China','Europe','Japan','Russia','UK','India']
plt.pie(x,labels = labels,labeldistance=1.3,autopct = '%1.2f%%',pctdistance=0.8,
explode =[0,0,0.2,0.1,0.3,0,0],shadow = True,startangle =0)
plt.axis('equal')
plt.show()
startangle设置旋转角度
【散点图需要两个参数x,y,但此时x不是表示x轴的刻度,而是每个点的横坐标!】
scatter()
In [84]:
s = np.random.normal(loc = 35,scale= 50,size = 1000)
s
Out[84]:
array([ 80.57394296, -43.56574953, -9.97268372, 47.13484284,
......
-12.02232651, -28.62345139, 49.74371119, -42.30824974,
-2.02534908, 5.71458714, 97.39618762, 34.11035012,
-17.27104914, 42.86930113, -17.16743251, 9.44454005])
In [85]:
x = np.random.randn(1000)
y = np.random.randn(1000)
colors = np.random.rand(3000).reshape(1000,3)
plt.scatter(x,y,s = s,color = colors,marker = 'd')
/home/ccoy/.local/lib/python3.7/site-packages/matplotlib/collections.py:922: RuntimeWarning: invalid value encountered in sqrt
scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
Out[85]:
<matplotlib.collections.PathCollection at 0x7f71396e34e0>
控制文字属性的方法:
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对象
text()
使用figtext()
In [86]:
x = np.linspace(0,2*np.pi,1000)
plt.plot(x,np.sin(x))
#调用方法text 坐标是绝对值
plt.text(s = 'sin(0) = 0',x = 0.2,y = 0)
plt.text(s = "sin($\pi$) = 0",x = 3.14,y = 0)
plt.figtext(s = "sin($3\pi/2$) = -1",x = 0.65,y = 0.2)
Out[86]:
Text(0.65, 0.2, 'sin($3\\pi/2$) = -1')
annotate()
xy参数设置箭头指示的位置,xytext参数设置注释文字的位置
arrowprops参数以字典的形式设置箭头的样式
width参数设置箭头长方形部分的宽度,headlength参数设置箭头尖端的长度,
headwidth参数设置箭头尖端底部的宽度,
facecolor设置箭头颜色
shrink参数设置箭头顶点、尾部与指示点、注释文字的距离(比例值)
In [87]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
练习
三个随机正太分布数据
设置图例
bbox_to_anchor,ncol mode,borderaxespad
设置注解 arrowstyle
In [88]:
x1 = np.random.normal(loc = 35,scale= 1,size = 100)
x2 = np.random.normal(loc = 15,scale= 1 ,size = 100)
x3 = np.random.normal(loc= 0,scale= 5,size = 100)
plt.plot(x1)
plt.plot(x2)
plt.plot(x3)
plt.legend(['first','second','third'],
bbox_to_anchor =[0,1,1,0],
ncol = 3,mode = 'expand')
#添加注释
# plt.annotate('this line is important',
# xy = (55,13),
# xytext = (10,30),arrowprops = {'arrowstyle' : '<-'})
# width the width of the arrow in points
# headwidth the width of the base of the arrow head in points
# headlength the length of the arrow head in points
# shrink
plt.annotate('this line is important',
xy = (55,13),
xytext = (10,30),arrowprops = {'width':5,'headwidth':10,'headlength':10,'shrink':0.1})
Out[88]:
Text(10, 30, 'this line is important')
箭头的样式,没必要记
In [89]:
plt.figure(figsize=(12,9))
plt.axis([0, 10, 0, 20]);
arrstyles = ['-', '->', '-[', '<-', '<->', 'fancy', 'simple', 'wedge']
for i, style in enumerate(arrstyles):
plt.annotate(style, xytext=(1, 2+2*i), xy=(4, 1+2*i), arrowprops=dict(arrowstyle=style));
connstyles=["arc", "arc,angleA=10,armA=30,rad=30", "arc3,rad=.2", "arc3,rad=-.2", "angle", "angle3"]
for i, style in enumerate(connstyles):
plt.annotate(style, xytext=(6, 2+2*i), xy=(8, 1+2*i), arrowprops=dict(arrowstyle='->', connectionstyle=style));
plt.show()
曲面图
导包
from mpl_toolkits.mplot3d.axes3d import Axes3D
In [90]:
from mpl_toolkits.mplot3d.axes3d import Axes3D
生成数据
In [91]:
x = np.linspace(0,2*np.pi,100)
y = np.linspace(0,7,100)
#x,y一条线,绘制面,numpy提供方法,可以将,x,y转变成面
X,Y = np.meshgrid(x,y)
Z = 0.7*X + 2 - np.sin(Y) + 2*np.cos(3 - X)
plt.figure(figsize=(14,9))
axes1 = plt.subplot(1,2,1,projection = '3d')
axes1.plot_surface(X,Y,Z)
axes2 = plt.subplot(1,2,2,projection = '3d')
axes2.set_xlabel('X')
axes2.set_ylabel('Y')
axes2.set_zlabel('Z')
axes2.set_xticks(np.linspace(0,2*np.pi,5))
axes2.set_xticklabels(list('abcde'))
#p 3维图形,
p = axes2.plot_surface(X,Y,Z,cmap = 'autumn')
plt.colorbar(p,shrink = 0.5)
Out[91]:
<matplotlib.colorbar.Colorbar at 0x7f71395359b0>
In [92]:
fig = plt.figure(figsize=(14,6))
#创建3d的视图,使用属性projection
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_surface(X,Y,Z,rstride = 15,cstride = 5)
#创建3d视图,使用colorbar,添加颜色柱
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap='rainbow', antialiased=True)
cb = fig.colorbar(p, shrink=0.5)
In [93]:
plt.plot(x,y)
Out[93]:
[<matplotlib.lines.Line2D at 0x7f713942c9b0>]
In [94]:
X
Out[94]:
array([[0. , 0.06346652, 0.12693304, ..., 6.15625227, 6.21971879,
6.28318531],
[0. , 0.06346652, 0.12693304, ..., 6.15625227, 6.21971879,
6.28318531],
[0. , 0.06346652, 0.12693304, ..., 6.15625227, 6.21971879,
6.28318531],
...,
[0. , 0.06346652, 0.12693304, ..., 6.15625227, 6.21971879,
6.28318531],
[0. , 0.06346652, 0.12693304, ..., 6.15625227, 6.21971879,
6.28318531],
[0. , 0.06346652, 0.12693304, ..., 6.15625227, 6.21971879,
6.28318531]])
In [95]:
a = np.array([1,2,6])
b = np.array([3,7,9,0])
A,B = np.meshgrid(a,b)
display(A,B)
array([[1, 2, 6],
[1, 2, 6],
[1, 2, 6],
[1, 2, 6]])
array([[3, 3, 3],
[7, 7, 7],
[9, 9, 9],
[0, 0, 0]])
绘制图形
In [96]:
x = np.random.randint(0,10,size = 10)
y = np.random.randint(10,20,size = 10)
plt.bar(x,y,width = 0.5)
Out[96]:
<BarContainer object of 10 artists>
创建极坐标条形图
使用np.histogram计算一组数据的直方图
In [97]:
wind = np.load('Ravenna_wind.npy')
wind.shape
Out[97]:
(66,)
In [98]:
wind
Out[98]
159.5 , 100. , 80. , 90. , 80. , 80. ,
90. , 90. , 90. , 97. , 89. , 88.0147,
107.004 , 107.004 , 132.503 , 132.503 , 132.503 , 251. ])
In [99]:
np.arange(0,360,45)
Out[99]:
array([ 0, 45, 90, 135, 180, 225, 270, 315])
In [100]:
#绘制玫瑰图,极坐标图,360 :东南西北,东北,西北,西南,东南
#66 个数据分成八份
#range 指明范围,最大值,最小值
degree,ranges = np.histogram(wind,bins = 8,range = [0,360])
In [101]:
degree
Out[101]:
array([ 5, 12, 24, 9, 11, 4, 0, 1])
In [102]:
ranges
Out[102]:
array([ 0., 45., 90., 135., 180., 225., 270., 315., 360.])
In [103]:
#使用玫瑰图显示数据
ranges = np.arange(0,2*np.pi,2*np.pi/8)
# axes(rect, facecolor='w')`` where *rect* = [left, bottom, width,
# height]
# plt.figure(figsize=(10,10))
plt.axes([0,0,1.5,1.5],polar = True,facecolor = 'green')
colors = np.random.rand(8,3)
plt.bar(ranges,degree,color = colors,width = 2*np.pi/8)
Out[103]:
<BarContainer object of 8 artists>
仅供参考学习,严禁转载!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。