科学计算系列学习 01:Numpy
科学计算系列学习 02:Pandas
科学计算系列学习 03:Matplotlib
关于Matplotlib:
matplotlib是python上的一个2D绘图库,它可以在夸平台上边出很多高质量的图像。
matplotlib.pyplot:提供一个类似matlab的绘图框架。plot: /plɑt/ 绘图;情节;阴谋
安装numpy和matplotlib
pip install numpy
pip install matplotlib
一、坐标图: plot
import matplotlib.pyplot as plt
import numpy
x=numpy.linspace(-1,1,50) # 创建一个指定起始点,指定个数的数列
y=2*x+1
plt.plot(x,y) # 绘一条线
plt.show # 展示图
1、显示框:Figure
一个figure就是一个图形,;下面的代码创建两个figure; figure:计算,图形,显示
import numpy
from matplotlib import pyplot
x=numpy.linspace(-3,3,50)
y1=2*x+1
y2=x**2
pyplot.figure()
pyplot.plot(x,y1)
pyplot.show()
pyplot.figure(num=3,figsize=(8,5))
pyplot.plot(x,y2,)
pyplot.plot(x,y1,color='red',linewidth=1,linestyle="-")
pyplot.show()
2、坐标轴 取值、标签、刻度:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3,3,40)
y1=2*x+1
y2=x**2
plt.figure() # 创建一个图像
plt.plot(x, y1, color='k') # 创建一个坐标图
plt.plot(x, y2)
plt.xlim(-4,4) # 设置坐标轴显示值的范围
plt.ylim(-4,4)
plt.xlabel('this is xlabel') # 给坐标轴添加标签
plt.ylabel('this is ylabel')
new_ticks = np.linspace(-4, 4, 17) # 设置坐标轴刻度间隔的大小
plt.xticks(new_ticks)
plt.yticks([-2, -1, 0, 1, 2],['rbad', 'bad', 'normal', 'good', 'rgood']) # 将坐标轴的刻度值代替为其它值
plt.show()
3、调整坐标轴元点:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3,3,40)
y1=2*x+1
y2=x**2
plt.figure() # 创建一个图像
plt.plot(x, y1, color='k') # 创建一个坐标图
plt.plot(x, y2)
plt.xlim(-4,4) # 设置坐标轴显示值的范围
plt.ylim(-4,4)
plt.xlabel('this is xlabel') # 给坐标轴添加标签
plt.ylabel('this is ylabel')
new_ticks = np.linspace(-4, 4, 17) # 设置坐标轴刻度间隔的大小
plt.xticks(new_ticks)
plt.yticks([-2, -1, 0, 1, 2],['rbad', 'bad', 'normal', 'good', 'rgood']) # 将坐标轴的刻度值代替为其它值
ax = plt.gca() # gca :get current axis 得到目前的坐标轴的框架
ax.spines['right'].set_color('none') # spine:脊柱,只显示下面的x轴,和左面的y轴
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)) # 设置x轴绑定在y轴的0位置
ax.spines['left'].set_position(('data', 0)) # 设置y轴绑定在x轴的0位置
plt.show()
4、添加图例:legend 传奇,图例
# 在plt.plot定义线条部分,增加label;
l1, = plt.plot(x,y1,label='up',color='red',linewidth=1,linestyle="-")
l2, = plt.plot(x,y2,label='down')
plt.legend(handles=[l1,l2],labels=['aaa','bbb'],loc='best')
5、注解:
import numpy
import matplotlib.pyplot as plt
x=numpy.linspace(-3,3,50)
y=2*x+1
plt.figure(num=2)
plt.plot(x,y)
ax=plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
# 添加标注:Annotation
x0=1
y0=2*x0+1
plt.scatter(x0,y0,s=50,color='r') # 展示一个点,大小为50,颜色为红色,r为简写red
plt.plot([x0,x0],[y0,0],'k--',lw=2.5) # 展示要注释点的虚线,参数代表: 虚线两点的x坐标和y坐标;线形式为黑色(k)- -,以及线的宽度为2.5
plt.annotate(r'$2x+1=%s$' %y0, xy=(x0,y0),xycoords='data',xytext=(+30,-30), # 对点的文字描述,和文字描述的位置,基于data位置(点的位置),x+30,y-30
textcoords='offset points',
fontsize=16,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2')) # 字体大小16,描述样式->,弯曲线.
#添加注解文字:
plt.text(-3,3,'This is the text')
plt.text(-3,2,r"$this\ is\ beautiful\ text\ \sigma_i\ \alpha_t$",fontdict={'size':14,'color':'r'})
plt.show()
6、tick 能见度
当线条过粗或过多,挡住坐标轴上的数据时,可以透过线条
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-4,4,3)
y=0.1*x
plt.figure()
plt.plot(x,y,linewidth=10,zorder=1)
plt.ylim(-2,2)
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))
ax.spines['left'].set_position(('data',0))
# 设置透明度
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(14)
label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.9,zorder=1))
label.set_zorder(2)
plt.show()
# zorder=1 label.set_zorder(2) 这两个还不明白
二、其它种类图
1、饼图:pie
import matplotlib.pyplot as plt
# Pie chart, where the slices will be ordered and plotted counter-clockwise # 饼图会逆时针排序
labels = ['Forgs','Hogs','Dogs','Logs'] # 元素的标签
sizes = [15,30,45,10] # 元素的比例
explode = (0,0.1,0,0) # only "explode" the 2nd slice('Hogs') 第二个爆炸出来,0表示不爆炸,1爆炸间隔最大
fig1,ax1=plt.subplots()
ax1.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',shadow=False,startangle=30)
ax1.axis('equal') # Equal aspect ratio ensure that pie is drawn as a circle
plt.show() # 相等的宽比确保饼图被画成一个圆,无此项会变成椭圆形
2、散点图scatter:
import numpy as np
import matplotlib.pyplot as plt
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) # 百分之50tou
plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))
plt.show()
3、柱状图bar
import numpy as np
import matplotlib.pyplot as plt
n = 12
X = np.arange(n) # arange 相当于列表生成器,生成从0,到n-1的一个列表
Y1=(1-X/float(n))*np.random.uniform(0.5,1.0,n) # 从0,5-1.0 随机采样 n个值
Y2=(1-X/float(n))*np.random.uniform(0.5,1.0,n) # 从0,5-1.0 随机采样 n个值
plt.bar(X,+Y1,facecolor='#9999ff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
for x,y in zip(X,Y1):
plt.text(x+0.2,y+0.05,'%.2f'%y,ha='center',va='bottom')
for x,y in zip(X,Y2):
plt.text(x+0.2,-y-0.05,'%.2f'%y,ha='center',va='top')
plt.xlim((5,n))
plt.ylim((-1.25,1.25))
plt.show()
4、等高线图 contours
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
# the height function
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n=256
x=np.linspace(-3,3,n)
y=np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
# use plt.contourf to filling contours
# X,Y and value for (X,Y) point
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
# use plt.contour to add contour lines
C=plt.contour(X,Y,f(X,Y),8,colors='black')
# adding label
plt.clabel(C,inline=True,fontsize=10,linewidth=.5)
plt.xticks(())
plt.yticks(())
plt.show()
5、3D图
import numpy as np
import matplotlib.pyplot as plt
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)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
"""
============= ================================================
Argument Description
============= ================================================
*X*, *Y*, *Z* Data values as 2D arrays
*rstride* Array row stride (step size), defaults to 10
*cstride* Array column stride (step size), defaults to 10
*color* Color of the surface patches
*cmap* A colormap for the surface patches.
*facecolors* Face colors for the individual patches
*norm* An instance of Normalize to map values to colors
*vmin* Minimum value to map
*vmax* Maximum value to map
*shade* Whether to shade the facecolors
============= ================================================
"""
# I think this is different from plt12_contours
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
"""
========== ================================================
Argument Description
========== ================================================
*X*, *Y*, Data values as numpy.arrays
*Z*
*zdir* The direction to use: x, y or z (default)
*offset* If specified plot a projection of the filled contour
on this position in plane normal to zdir
========== ================================================
"""
ax.set_zlim(-2, 2)
plt.show()
6、图片
import matplotlib.pyplot as plt
import numpy as np
# image data
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
plt.colorbar(shrink=.92)
plt.xticks(())
plt.yticks(())
plt.show()
三、多图合并展示
1、多个坐标图
import matplotlib.pyplot as plt
import numpy as np
plt.figure() # 创建一个fingure
plt.subplot(2,1,1) # 2行1列,第一个位置
plt.plot([0,1],[0,1])
plt.subplot(2,3,4) # 2行3列,地4个位置
plt.plot([0,1],[0,2])
plt.subplot(235) # 简写去掉逗号
plt.plot([0,1],[0,3])
plt.subplot(236)
plt.plot([0,1],[0,4])
plt.show()
2、分格展示
import matplotlib.pyplot as plt
plt.figure()
ax1=plt.subplot2grid((3,3),(0,0),rowspan=1,colspan=3) # 三行三列;第0行,第0列;占一行三列,默认都是1
ax1.set_title('ax1_title')
ax1.set_xlabel('a')
ax1.set_xlim(0,3)
ax1.set_ylim(0,3)
ax1.plot([0,3],[0.1,3]) # 起点坐标(0,0.1),终点坐标(3,3)
ax2=plt.subplot2grid((3,3),(1,0),colspan=2,)
ax2.scatter([0,1],[0,1])
ax3=plt.subplot2grid((3,3),(1,2),rowspan=2,colspan=1)
ax4=plt.subplot2grid((3,3),(2,0))
ax5=plt.subplot2grid((3,3),(2,1))
plt.tight_layout() # tight 紧的,密封的
plt.show()
import matplotlib.pyplot as plt
f,((ax11,ax12),(ax21,ax22))=plt.subplots(2,2,sharex=True,sharey=True) # 两行两列,同一行共享y轴,同一列共享x轴
ax11.scatter([1,2],[1,2])
plt.tight_layout()
plt.show()
3、图中图
import matplotlib.pyplot as plt
fig=plt.figure()
x=[0,1,2,3,4,5,6,7] # 手动定义x,y数列
y=[0,1,3,4,2,5,8,6]
left,bottom,width,height = 0.1,0.1,0.8,0.8 # 坐标四个边,距离figure边框的的距离
ax1 = fig.add_axes([left,bottom,width,height]) # 往figure里添加第一个坐标图
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title one')
left,bottom,width,height = 0.2,0.6,0.25,0.25
ax2 = fig.add_axes([left,bottom,width,height]) # 往figure里添加第一个坐标图
ax2.plot(y,x,'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title two')
plt.axes([.63,.2,.25,.25])
plt.plot(y[::-1],x,'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title three')
plt.show()
4、次坐标轴:两个y轴坐标,左右各一个
import matplotlib.pyplot as plt
import numpy as np
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_xlabel('X data')
ax1.set_ylabel('Y1',color='g')
ax2.set_ylabel('Y2',color='b')
plt.show()
参考:
https://matplotlib.org/gallery/index.html
https://blog.csdn.net/sinat_34022298/article/details/76348969?locationNum=9&fps=1
https://study.163.com/course/courseLearn.htm?courseId=1003240004#/learn/video?lessonId=1003683077&courseId=1003240004