Matplotlib库
图像属性设置、坐标轴设置、图例、某点的标注、透明度设置:
import matplotlib.pyplot as plt
import numpy as np
#####################图像属性设置、坐标轴设置、图例、某点的标注、透明度设置##################
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x*x+2
plt.figure()
plt.plot(x,y1)
#######figure图像属性设置
plt.figure(num=3, figsize=(8,5)) #figsize(length,height)
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
#######igure坐标轴设置
plt.xlim((-1,3))
plt.ylim((-2,5)) #x,y的显示范围
plt.xlabel('I am X')
plt.ylabel('I am Y') #x,y轴注释
new_ticks = np.linspace(0,3,4)
print(new_ticks)
plt.xticks(new_ticks) #修改x轴的显示范围以及间距
plt.yticks([0,1,2,3,], #修改y轴的显示,改为文字形式
[r'$really\ bad$',r'$bad\ \alpha$',r'$good$',r'$really\ good$'])
####### gca = 'get current axis'
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',2)) #outward,axes
ax.spines['left'].set_position(('data',0)) #设置x轴y轴的定位
#######图例
plt.figure()
x2 = np.linspace(0,2,50)
y4 = x2**0.5
y5 = x2**3
l1, = plt.plot(x2,y4,label='down')
l2, = plt.plot(x2,y5,color='red',linewidth=1.0,linestyle='--',label='up')
plt.legend(handles=[l1,l2,],labels=['aa','bb'],loc='best')
ax = plt.gca()
ax.spines['bottom'].set_position(('data',0)) #outward,axes
ax.spines['left'].set_position(('data',0))
#######作某点的标注
x0 = 1
y0 = x0**3
plt.scatter(x0,y0,s=50,color='b') #打印点
plt.plot([x0,x0],[y0,0],'k--') #k就是black
#method 1
#############################
plt.annotate(r'$x**3=%s$' % y0,xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points',
fontsize=16,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
#method 2
#############################
plt.text(0,3,r'$This\ is\ the\ some\ text.\ \mu\ \sigma_i\ \alpha_t$',
fontdict={'size':16,'color':'r'})
#######透明度
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16) #变大些
label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.8)) #80%
plt.show()
散点图、柱状图、等高线图
import matplotlib.pyplot as plt
import numpy as np
####################散点图、柱状图、等高线图
#######散点图
plt.figure()
n = 1024
X = np.random.normal(0,1,n) #平均为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)
plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))
plt.xticks(())
plt.yticks(())
#######柱状图
plt.figure()
n = 12
X = np.arange(n) # 0~11
Y1 = (1-X/float(n))*np.random.uniform(0.5,1.0,n)
Y2 = (1-X/float(n))*np.random.uniform(0.5,1.0,n)
plt.bar(X,+Y1,facecolor='#66ccff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
for x,y in zip(X,Y1):
# ha:horizontal alignment 横向对齐 va:vertical alignment 纵向对齐
plt.text(x , y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x,y in zip(X,Y2):
# ha:horizontal alignment 横向对齐 va:vertical alignment 纵向对齐
plt.text(x , -y - 0.05, '-%.2f' % y, ha='center', va='top')
plt.xlim(-5,n)
plt.xticks(()) #消掉x轴
plt.ylim(-1.25,1.25)
plt.yticks(()) #消掉y轴
######等高线:
plt.figure()
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) #将xy网格化
# use plt.contourf to fill contours
# X,Y and value for (X,Y) point
plt.contourf(X,Y,f(X,Y),16,alpha=0.75,cmap=plt.cm.hot) # 2.cmap=plt.cm.cool, 16为等高线区别颜色的数量
# use plt.contour to add contour lines
C = plt.contour(X,Y,f(X,Y),16,colors='black',linewidths=.5) # 16为等高线数量
#adding label
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(()) #去掉xy轴
plt.show()
image data
import matplotlib.pyplot as plt
import numpy as np
# image data
a = np.array([0.3,0.33,0.36,
0.39,0.45,0.5,
0.55,0.59,0.65]).reshape(3,3)
"""
for the value of "interpolation",check this:
https://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
"""
plt.imshow(a,interpolation='nearest',cmap='bone',origin='upper') #cmap colormap
plt.colorbar(shrink=0.9)
plt.xticks(())
plt.yticks(())
plt.show()
3D绘图
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
################## 3D数据
fig = plt.figure()
ax = Axes3D(fig) #添加3D的axes
# 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)
# rstride=行跨度 cstride=列跨度 且均为整数
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,edgecolor='black',cmap=plt.get_cmap('rainbow'))
ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2,2)
plt.show()
subplot的多种方法:
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
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(224)
plt.plot([0,1],[0,4])
plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(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()
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# method 1:subplot2grid 单元格
###########################
plt.figure()
ax1 = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1) #行3列1
ax1.plot([1,3],[2,4])
ax1.set_xlabel('aaa')
ax1.set_title('first')
ax2 = plt.subplot2grid((3,3),(1,0),colspan=2,rowspan=1) #行2列1
ax3 = plt.subplot2grid((3,3),(1,2),rowspan=2)
ax4 = plt.subplot2grid((3,3),(2,0))
ax5 = plt.subplot2grid((3,3),(2,1))
# method 2:gridspec
#######################################
plt.figure()
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])
# method 3: easy to define structure
###########################################
f,((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2],[1,2])
plt.tight_layout()
plt.show()
图中图
import matplotlib.pyplot as plt
fig = plt.figure()
x = [1,2,3,4,5,6,7]
y = [1,3,4,2,5,8,6]
left,bottom,width,height = 0.1,0.1,0.8,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')
left,bottom,width,height = 0.2,0.6,0.25,0.25 # 小图占据整个屏幕的位置
ax2 = fig.add_axes([left,bottom,width,height])
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')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()
次坐标轴
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')
ax2.set_ylabel('Y2',color='g')
ax1.set_ylabel('Y1',color='b')
plt.show()
动画效果
import matplotlib.pyplot as plt
import numpy as np
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/1000))
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) # frames贞 interval频率
plt.show()
标签的中文设置
# 只需添加这两句即可,亲测有效
# 设置显示中文
plt.rcParams['font.sans-serif']=['SimHei']
# 设置显示正常字符
plt.rcParams['axes.unicode_minus'] = False
横纵坐标出现日期
# -*- encoding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
'''1.读取并预处理数据'''
# 文件地址
io = r'D:\数学建模\Matlab\数学建模\数据集\德州制造业活动.xls'
# 抽取数据
data1 = pd.read_excel(io,sheet_name=0,usecols=[1],squeeze=True)
Unemployment_rate = np.array(data1)
# 39个失业率样本数据 36+4
# 由于数据量较小,整个数据集充当训练集,同时也充当测试集
x = np.arange(0, 40, 1).reshape(-1,1)
y = data1
x_before = x[:36]
y_before = y[:36]
x_virus = x[36:40]
y_virus = y[36:40]
'''2.图像框架绘制'''
# 横坐标修改为日期
dates = ['2017.1','2017.2','2017.3','2017.4','2017.5','2017.6','2017.7','2017.8','2017.9','2017.10','2017.11','2017.12'
,'2018.1','2018.2','2018.3','2018.4','2018.5','2018.6','2018.7','2018.8','2018.9','2018.10','2018.11','2018.12'
,'2019.1','2019.2','2019.3','2019.4','2019.5','2019.6','2019.7','2019.8','2019.9','2019.10','2019.11','2019.12'
,'2020.1','2020.2','2020.3','2020.4','2020.5','2020.6']
x_range = range(len(dates))
# plt.plot(x_range, y, 'ro-')
plt.xticks(x_range, dates, rotation=60)
plt.subplots_adjust(bottom=0.15)
plt.xlabel("year/month")
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.ylabel("德州制造业活动变化率/%")
plt.title("德州制造业活动")
plt.show()
绘制结果如下:
- 添加网格线:plt.grid()