python扩充库之matplotlib(二)

上接python扩充库之matplotlib(一)

代码py3测试都可运行,此处不贴图,可自行运行查看结果

3.8 bar 柱状图

import matplotlib.pyplot  as plt 
import numpy as np 

n = 12 
X = np.arange(n) #返回0-n(不包括n的离散数据)
print(type(X))

Y1 = (1-X/float(n))*np.random.uniform(0.5,1.0,n)  #uniform 均匀分布
print(type(Y1))
Y2 = (1-X/float(n))*np.random.uniform(0.5,1.0,n)  

plt.figure(num = 'bar')
ax = plt.gca() #获取四周边框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.bar(X,+Y1,facecolor='#9999ff',edgecolor='white')  #柱状图 
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')  #状图颜色,边界颜色

print(type(zip(X,Y1)))

#zip(A,B) 分别从AB中取数据放入x,y中  函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

#如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
for x,y in zip(X,Y1):

	#ha horizontal alignment 水平对齐
	plt.text(x+0.1,y+0.05,'%.2f'%y,ha='center',va='bottom')


for x,y in zip(X,Y2):
	#ha horizontal alignment 水平对齐
	plt.text(x+0.1,-y-0.05,'%.2f'%y,ha='center',va='top')





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

plt.show()

 

3.9 contours 等高线

#matplotlib_contours.py #等高线
import matplotlib.pyplot as plt 
import numpy as np 

#定义高度函数
def hight(x,y):
	return (1-x/2 + x**5 + y**3)*np.exp(-x**2-y**2)

#生成x,y点
n = 256
x = np.linspace(-3,3,n)
print(type(x))
y = np.linspace(-3,3,n)

#定义网格 
X,Y = np.meshgrid(x,y)

#颜色设定 alpha=透明度; 数字8=等高线被分成几部分;cmap(colormap)=将点与颜色对应.hot指暖色调
plt.contourf(X,Y,hight(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
#plt.contourf 用于填充等高线的点

#plt.contour用于画等高线的线
C= plt.contour(X,Y,hight(X,Y),color="black",lw=.5)

#数字描述
plt.clabel(C,inline=True,fontsize=10)


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


3.10 image 图像

#image 图像

import matplotlib.pyplot as plt 
import numpy as np 

a = np.random.rand(9,9)

print(type(a))

plt.figure(num='Image')
#对于interpolation更多属性,请参考https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html#sphx-glr-gallery-images-contours-and-fields-interpolation-methods-py
plt.imshow(a,interpolation='none',cmap=plt.cm.bone,origin='lower')
#添加colorbar  ; shrink = 压缩colorbar长度
plt.colorbar(shrink=.9)
plt.xticks(())
plt.yticks(())
plt.show()

                          

3.11 3Dplot 3d图像

#3D plot 3 
import matplotlib.pyplot as plt 
import numpy as np 
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(num='3Dplot')
#添加3D坐标轴
ax = Axes3D(fig)
#添加X,Y的值
X = np.arange(-4,4,.25)
Y = np.arange(-4,4,.25)
X,Y = np.meshgrid(X,Y)
R = np.sqrt(X**2+Y**2)

#设置高度
Z = np.sin(R)

#rstride /cstride 行和列跨度
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'),edgecolor='black')

#映射图
#d等高线图 zdir=从那条轴映射 ;offset=等高线在z平面哪个高度
ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2,2)
#沿x轴映射
ax.contourf(X,Y,Z,zdir='x',offset=-5,cmap='rainbow')
ax.set_xlim(-5,5)
plt.show()



3.12subplot 多合一合并显示

#matplotlib_subplot 多合一显式

import matplotlib.pyplot as plt
import numpy as np 

plt.figure(num="subplot")

#使用subplot分成两行两列均分
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])

plt.subplot(2,2,2)
plt.plot([0,1],[0,2])

#等价操作
plt.subplot(223)
plt.plot([0,1],[0,3])

plt.subplot(2,2,4)
plt.plot([0,1],[0,4])
plt.show()

#非均分
plt.figure(num="subplot——2")

#使用subplot分成两行两列均分
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])

plt.subplot(2,3,4)
plt.plot([0,1],[0,1])

#等价操作
plt.subplot(235)
plt.plot([0,1],[0,1])

plt.subplot(236)
plt.plot([0,1],[0,4])

plt.show()


 

方法二:分为三种方式 subplot2grid  /  Gridspec /  subplots

# matplotlib_subplot2 分格显式

import matplotlib.pyplot as plt

import matplotlib.gridspec as gridspec

#method1:subplot2grid
plt.figure(num="method1:subplot2grid")
#分成五个小图
#(3,3)三行三列 ;(0,0)起始点;colspan=列跨度 ,roespan=行跨度
ax1 = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1)
ax1.plot([1,2],[1,2])
ax1.set_title('ax1')# set_xlim() set_xlabel()

ax2 = plt.subplot2grid((3,3),(1,0),colspan=2,)
ax3 = plt.subplot2grid((3,3),(1,2),rowspan=2)
ax4 = plt.subplot2grid((3,3),(2,0),colspan=2,rowspan=1)
 
#method2:gridspec
plt.figure(num="method2:gridspec")
#(3,3)三行三列的girdspec
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[-1,0]) #倒数第一行
ax5 = plt.subplot(gs[-1,-2])

#method3:easy to define structure
#subplots返回两个参数一个为figure 另外一个为plot   四个参数分别含义为 2行 2列 共享x轴 共享y轴
f,((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2,sharex=True,sharey = True)
f.num="sfs"
ax11.scatter([1,2],[1,2])
ax2 = plt.plot([1,2],[1,2]) 
ax3 = plt.plot([1,2],[1,2]) 
ax4 = plt.plot([1,2],[1,2]) 
plt.show()


3.13  plot in plot 图中图

#matplotlin_plotinplot
import matplotlib.pyplot as plt 
import numpy as np 

fig = plt.figure(num="plotinplot")

#numpy.linspace是用于创建一个一维数组,并且是等差数列构成的一维数组(起始位置,终止位置,元素个数)
x = np.linspace(1,8,8)
#函数说明:arange([start,] stop[, step,], dtype=None)根据start与stop指定的范围以及step设定的步长,生成一个 ndarray。
y = np.arange(2,10,1)
y = np.random.randint(2,10,(8,))
print(type(x))
print(y)

#做一张大图
left,bottom,width,height = 0.1,0.1,0.8,0.8
#设定大图在figure 距离左部,底部,宽度,高度,占的比例
ax1 =fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,'r')        
ax1.set_xlabel('x')
ax1.set_ylabel('y')


#做一张小图
left,bottom,width,height = 0.2,0.6,0.25,0.25
#设定大图在figure 距离左部,底部,宽度,高度,占的比例
ax2 =fig.add_axes([left,bottom,width,height])
ax2.plot(y,x,'r')
ax2.set_xlabel('x')
ax2.set_ylabel('y')

plt.axes([.6,.2,.25,.25])
#实现y'的逆序
y = y[::-1]
plt.plot(y,x,'g')
plt.xlabel('x')
plt.ylabel('y')

plt.show()

3.14  secondaxex 次坐标轴

#matplotlib_secondaxes 主次坐标轴
import numpy as np 
import matplotlib.pyplot as plt
x = np.arange(1,10,0.1)
y1 = 0.05*x**2
y2 = -y1

#subplots 会返回两个对象 fig:matplotlib.figure.Figure对象
#ax:Axes(轴)对象或Axes(轴)对象数组。
fig , ax1 = plt.subplots()
#次坐标轴为主坐标轴的镜面映射
ax2=ax1.twinx()

ax1.plot(x,y1,'g-')
ax2.plot(x,y2,'r--')

ax1.set_xlabel('X DATA')
ax1.set_ylabel('Y1',color='g')
ax2.set_ylabel('Y1',color='r')


plt.show()

3.15  Animation 动画

#matplotlib_Animation 动画


import numpy as np 
import matplotlib.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 init():
	line.set_ydata(np.sin(x))
	return line,


def animate(i):
	line.set_ydata(np.sin(x+i/100))
	return line,
#fig =figure对象 fun = 函数  frames=循环点  init_func=最开始的一帧 interval=时间间隔 blit=是否只更新变化的点
ani = animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=20,blit=True)


plt.show()

完结散花~~后续会进行更改填补

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值