Matplotlib数据可视化

1
2
import matplotlib.pyplot as plt
import numpy as np
1
2
3
4
5
6
##基本使用
#基本用法
x = np.linspace(-1, 1, 50)
y = 2*x + 1
plt.plot(x, y)
plt.show
<function matplotlib.pyplot.show(*args, **kw)>

png

1
2
3
4
5
6
7
8
9
10
11
12
#figure图像
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()#一图
plt.plot(x, y1)

plt.figure(num = 3, figsize = (8, 5))#两图
plt.plot(x, y2)
plt.plot(x, y1, color = 'red', linewidth = 5.0 ,linestyle = '--')

plt.show
<function matplotlib.pyplot.show(*args, **kw)>

png

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#设置坐标轴
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure(1)
plt.plot(x, y2)
plt.plot(x, y1, color = 'red', linewidth = 5.0 ,linestyle = '--')

plt.xlim((-1, 2))
plt.ylim((-2, 3))

plt.xlabel('i am x')
plt.ylabel('i am y')

new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.5, -1, 1.22, 3],[r'$really\ bad$', '$bad\ \\alpha$', '$normal$', '$good$', '$really\ good$'])#\转义,$$之间为读取,r正则

plt.figure(2)
#gca = 'get current axis'
ax = plt.gca()
plt.plot(x, y2)
plt.plot(x, y1, color = 'red', linewidth = 5.0 ,linestyle = '--')

plt.xlim((-1, 2))
plt.ylim((-2, 3))

plt.xlabel('i am x')
plt.ylabel('i am y')

new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.5, -1, 1.22, 3],[r'$really\ bad$', '$bad\ \\alpha$', '$normal$', '$good$', '$really\ good$'])#\转义,$$之间为读取,r正则

ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.spines['bottom'].set_position(('data', 0))#outward, axes
ax.spines['left'].set_position(('data', 0))

plt.show
[-1.   -0.25  0.5   1.25  2.  ]
[-1.   -0.25  0.5   1.25  2.  ]





<function matplotlib.pyplot.show(*args, **kw)>

png

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#legend图例
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure(1)

plt.xlim((-1, 2))
plt.ylim((-2, 3))

plt.xlabel('i am x')
plt.ylabel('i am y')

new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.5, -1, 1.22, 3],[r'$really\ bad$', '$bad\ \\alpha$', '$normal$', '$good$', '$really\ good$'])#\转义,$$之间为读取,r正则

l1, = plt.plot(x, y2, label = 'up')#l1,特殊形式,为可传入handles,可去掉
l2, = plt.plot(x, y1, color = 'red', linewidth = 5.0 ,linestyle = '--', label = 'down')
plt.legend(handles =[l1, l2,] , labels =['aaa', 'bbb'] , loc = 'best')#handles可选择展示的图例,如可自选l1;loc etc:upper/lower right/left

plt.show()
[-1.   -0.25  0.5   1.25  2.  ]

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#anootation 标注
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1

plt.figure(1, figsize = (8, 5))
plt.plot(x, y1)

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.spines['bottom'].set_position(('data', 0))#outward, axes
ax.spines['left'].set_position(('data', 0))

x0 = 1
y0 = 2*x0 + 1
plt.scatter(x0, y0, color = 'b')
plt.plot([x0,x0], [y0, 0], 'k--', lw = 2.5)#k = black, lw = linewidth

#methon 1
plt.annotate(r'$2x+1 = %s$'%y0,xy=(x0,y0),xycoords='data',xytext = (30,-30), textcoords='offset points',\
fontsize=16,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=0.2'))

#methon 2
plt.text(-3.5,3,'this is the some text')

plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#tick 能见度
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1

plt.figure(1, figsize = (8, 5))
plt.plot(x, y1,linewidth=10)

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.spines['bottom'].set_position(('data', 0))#outward, axes
ax.spines['left'].set_position(('data', 0))

for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor='white',edgecolor='none',alpha=0.7))

plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#scatter 散点
n = 1024
x = np.random.normal(0,1,n)
y = np.random.normal(0,1,n)
t = np.arctan2(y,x) #for color value

plt.scatter(x,y,s=75,c=t,alpha=0.5)#s='size'
#plt.scatter(np.arange(5),np.arange(5))

plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))

plt.xticks(())
plt.yticks(())

plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#bar 柱状图
import matplotlib.pyplot as plt
import numpy as np

n = 12
x0 = np.arange(n)
y1 = (1-x0/float(n)) * np.random.uniform(0.5,1.0,n)
y2 = (1-x0/float(n)) * np.random.uniform(0.5,1.0,n)

plt.figure()
plt.bar(x0,+y1,facecolor='#9999ff',edgecolor='white')
plt.bar(x0,-y1,facecolor='#ff9999',edgecolor='white')

for x,y in zip(x0,y1):
plt.text(x+0.4,y+0.05,'%.2f'%y,ha='center',va='bottom')#ha:horizontal alignment
for x,y in zip(x0,y2):
plt.text(x+0.4,-y-0.05,'%-.2f'%y,ha='center',va='top')#ha:horizontal alignment

plt.xlim(-.5,n)
plt.xlim(-1.25,1.25)
plt.xticks(())
plt.yticks(())

plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#contours 等高线图
def f(x,y):
#the height function
return (1 - x/2 + x**5 + y**3)*np.exp(-x**2 - y**2)

n = 256
x0 = np.linspace(-3.3,n)
y0 = np.linspace(-3.3,n)
x,y = np.meshgrid(x0,y0)

#filling
plt.contourf(x,y,f(x,y),8,alpha=0.75,cmap=plt.cm.hot)#8 层次数

#lines
c = plt.contour(x,y,f(x,y),colors='black',linewidth=.5)

#add label
plt.clabel(c,inline=True,fontsize=10)

plt.xticks(())
plt.yticks(())
plt.show()
D:\anzhuang\Anaconda2\envs\python3\lib\site-packages\matplotlib\contour.py:960: UserWarning: The following kwargs were not used by contour: 'linewidth'
  s)

png

1
2
3
4
5
6
7
8
9
10
11
12
#image 图片
#image data
a = np.array([0.31,0.36,0.42,0.36,0.43,0.52,0.48,0.58,0.65]).reshape(3,3)

plt.imshow(a,interpolation='nearest',cmap=plt.cm.bone,origin='upper')
plt.colorbar(shrink=0.9)



plt.xticks(())
plt.yticks(())
plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#3D 数据
from mpl_toolkits.mplot3d import Axes3D

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

#x,y value
x = np.arange(-4,4,0.25)
y = np.arange(-4,4,0.25)
x,y = np.meshgrid(x,y)
r = np.sqrt(x**2+y**2)
#height value
z = np.sin(r)

#在3D下方contour
ax.plot_surface(x,y,z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))#rstride:行列宽
ax.contourf(x,y,z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2,2)

plt.show()
#

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#subplot 多合一显示
plt.figure(1)

plt.subplot(2,2,1)#2*2 第1个
plt.plot([0,1],[0,1])
plt.subplot(2,2,2)#2*2 第2个
plt.plot([0,1],[0,1])
plt.subplot(2,2,3)#2*2 第3个
plt.plot([0,1],[0,1])
plt.subplot(2,2,4)#2*2 第4个
plt.plot([0,1],[0,1])

plt.figure(2)
plt.subplot(2,1,1)#第1行1个
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)#第2行3个
plt.plot([0,1],[0,1])
plt.subplot(2,3,5)#
plt.plot([0,1],[0,1])
plt.subplot(2,3,6)#
plt.plot([0,1],[0,1])

plt.show()

png

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#分格显示
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

#method 1
plt.figure(1)
ax1 = plt.subplot2grid((3,3),(0,0),colspan=3)#三行三列,colspan=3,rowspan=1行列跨度
ax1.plot([1,2],[1,2])
ax.set_title('ax1_title')
ax2 = plt.subplot2grid((3,3),(1,0),colspan=2)#colspan=3,rowspan=1行列跨度
ax3 = plt.subplot2grid((3,3),(1,2),rowspan=2)#colspan=3,rowspan=1行列跨度
ax4 = plt.subplot2grid((3,3),(2,0))#colspan=3,rowspan=1行列跨度
ax4 = plt.subplot2grid((3,3),(2,1))#colspan=3,rowspan=1行列跨度

#method 2
plt.figure(2)
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1:,2])
ax4 = plt.subplot(gs[2,0])#ax4 = plt.subplot(gs[-1,0])
ax5 = plt.subplot(gs[2,1])#ax5 = plt.subplot(gs[-1,-2])

#method 3
plt.figure(3)
f,((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2,sharex=True,sharey=True)
#ax11.scatter([1,2],[1,2])

plt.tight_layout()
plt.show()

png

png

<Figure size 432x288 with 0 Axes>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#图中图
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

x = [1,2,3,4,5,6,7]
y = [1,3,2,4,5,8,5]

fig = plt.figure()
left = 0.1
bottom = 0.1
width = 0.8
height=0.8 #定位比例
ax1 = fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')

left2 = 0.2
bottom2 = 0.6
width2 = 0.25
height2=0.25 #定位比例
ax2 = fig.add_axes([left2,bottom2,width2,height2])

ax2.plot(y,x,'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')


plt.axes([0.6,0.2,0.25,0.25])#另一种方法
plt.plot(y[::-1],x,'g')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title inside 2')

plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#次坐标
x = np.arange(0,10,0.1)
y1 = 0.05*x**2
y2 = -1*y1
fig,ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x,y1,'g-')
ax2.plot(x,y2,'b--')

ax1.set_xlim(0,10)

ax1.set_xlabel('x data')
ax1.set_ylabel('y1',color='g')
ax2.set_ylabel('y2',color='b')

plt.show()
<Figure size 432x288 with 0 Axes>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#animation 动画
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig, ax = plt.subplots()

x = np.arange(0,2*np.pi,0.01)
line, = ax.plot(x,np.sin(x))

def animate(i):
line.set_ydata(np.sin(x+i/100))
return line

def init():
line.set_ydata(np.sin(x))
return line

ani= animation.FuncAnimation(fig = fig,func=animate,frames=100,init_func=init,interval=20,blit=False)

plt.show()

png