matplotlib是一个Python的2D绘图库,通过Matplotlib,可以仅需几行代码,便可生成绘图,直方图,条形图,散点图等。
绘图步骤:
-> 创建图纸(figure)
-> 在图纸上创建一个或多个绘图(plot)区域(也叫子图,坐标系/轴,axis)
-> 在plot区域上描绘点、线等各种marker
-> 为plot添加修饰标签(绘图线上的或坐标轴上的)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2, 100)
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()
plt.show()
import numpy as np
t = np.arange(0., 5., 0.2)
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
x = np.random.rand(10)
y = np.random.rand(10)
plt.scatter(x,y)
plt.show()
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
import numpy as np
import matplotlib. pyplot as plt
np.random.seed(19680801)
dt = 0.01
t = np.arange(0, 30, dt)
nse1 = np.random. randn(len(t))
nse2 = np.random.randn(len(t))
# Two signals with a coherent part at 10Hz and a random part
s1 = np.sin(2*np.pi*10*t)+nse1
s2 = np.sin(2*np.pi*10*t)+nse2
fig, axs = plt.subplots(2, 1)
axs[0].plot(t, s1, t, s2)
axs[0].set_xlim(0,2)
axs[0].set_xlabel('time')
axs[0].set_ylabel('s1 and s2')
axs[0].grid(True)
cxy, f = axs[1].cohere(s1,s2,256, 1./ dt)
axs[1].set_ylabel(' coherence')
fig.tight_layout()
plt. show()
import matplotlib.pyplot as plt
import numpy as np
n = 1204
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X)
plt.scatter(X,Y,s=75,c=T,alpha=0.5)
plt.xlim((-1,1))
plt.ylim((-1,1))
plt.xticks(())
plt.yticks(())
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(9)
y = np.sin(x)
z = np.cos(x)
# marker数据点样式,linewidth线宽,linestyle线型样式,color颜色
plt.plot(x, y, marker="*", linewidth=3, linestyle="--", color="red")
plt.plot(x, z)
plt.title("matplotlib")
plt.xlabel("height")
plt.ylabel("width")
# 设置图例
plt.legend(["Y","Z"], loc="upper right")
plt.grid(True)
plt.show()
x = np.arange(10)
y = np.random.randint(0,30,10)
plt.bar(x, y)
plt.show()
import matplotlib.pyplot as plt
num_list = [1.5,0.6,7.8,6]
plt.bar(range(len(num_list)), num_list,color='rbgy')
plt.show()
import matplotlib.pyplot as plt
name_list = ['Monday','Tuesday','Friday','Sunday']
num_list = [1.5,0.6,7.8,6]
num_list1 = [1,2,3,1]
x =list(range(len(num_list)))
total_width, n = 0.8, 2
width = total_width / n
plt.bar(x, num_list, width=width, label='boy',fc = 'y')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(x, num_list1, width=width, label='girl',tick_label = name_list,fc = 'r')
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
n = 12
X = np.arange(n)
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.axes([0.025,0.025,0.95,0.95])
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.4, y+0.05, '%.2f' % y, ha='center', va= 'bottom')
for x,y in zip(X,Y2):
plt.text(x+0.4, -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()
import matplotlib.pyplot as plt
import numpy as np
n = 12
X = np.arange(n)
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='r',edgecolor='w')
plt.bar(X,-Y2,facecolor='b',edgecolor='w')
for x,y in zip(X,Y1):
plt.text(x-0.1,y+0.05,'%.2f'%y,ha='center',va='bottom') #居中对齐
for x,y in zip(X,Y2):
plt.text(x+0.1,-y-0.05,'-%.2f'%y,ha='center',va='top')
plt.xlim((-0.5,n))
plt.ylim((-2,2))
plt.xticks(())
plt.yticks(())
plt.show()
mean, sigma = 0, 1
x = mean + sigma * np.random.randn(10000)
plt.hist(x,50)
plt.show()
import pandas as pd
import numpy as np
df = pd.DataFrame(3 * np.random.rand(5), index=['a', 'b', 'c', 'd','e'], columns=['x'])
df.plot.pie(subplots=True)
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(15, 4), columns=['a', 'b', 'c', 'd'])
df.plot.area()
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei'] # 用于正常显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号
X = np.linspace(-np.pi,np.pi,256,endpoint=True) #获取x坐标
sin,cos = np.sin(X),np.cos(X) #获取y坐标
plt.plot(X,sin,"b-",lw=2.5,label="正弦Sin()")
#X:x轴;sin:y轴;b-:color="blue",linestyle="-"的简写;lw:linewidth;label:线条的名称,可用于后面的图例
plt.plot(X,cos,"r-",lw=2.5,label="余弦Cos()") #cos:y轴;r-:color="red";
plt.show() #显示图表
import numpy as np
import matplotlib.pyplot as plt
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
plt.axes([0.025,0.025,0.95,0.95])
plt.plot (X, Y+1, color='blue', alpha=1.00)
plt.fill_between(X, 1, Y+1, color='blue', alpha=.25)
plt.plot (X, Y-1, color='blue', alpha=1.00)
plt.fill_between(X, -1, Y-1, (Y-1) > -1, color='blue', alpha=.25)
plt.fill_between(X, -1, Y-1, (Y-1) < -1, color='red', alpha=.25)
plt.xlim(-np.pi,np.pi), plt.xticks([])
plt.ylim(-2.5,2.5), plt.yticks([])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei'] # 用于正常显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号
X = np.linspace(-np.pi,np.pi,256,endpoint=True) #获取x坐标
sin,cos = np.sin(X),np.cos(X) #获取y坐标
plt.plot(X,sin,"b-",lw=2.5,label="正弦Sin()") #X:x轴;sin:y轴;b-:color="blue",linestyle="-"的简写;lw:linewidth
plt.plot(X,cos,"r-",lw=2.5,label="余弦Cos()")
plt.xlim(X.min()*1.5,X.max()*1.5)
plt.ylim(cos.min()*1.5,cos.max()*1.5)
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$'])
plt.yticks([-1,0,1])
plt.title("绘图实例之COS()&SIN()",fontsize=16,color="green")
plt.text(+2.1,-1.4,"By:biyoulin",fontsize=16,color="purple")
ax=plt.gca() #获取Axes对象
ax.spines['right'].set_color('none') #隐藏右边界
ax.spines['top'].set_color('none') #隐藏上边界
ax.xaxis.set_ticks_position('bottom') #x轴坐标刻度设置在坐标轴下面
ax.spines['bottom'].set_position(('data',0)) #x轴坐标轴平移至经过零点(0,0)位置
ax.yaxis.set_ticks_position('left') #y轴坐标刻度设置在坐标轴下面
ax.spines['left'].set_position(('data',0)) #y轴坐标轴平移至经过零点(0,0)位置
plt.legend(loc="upper left",fontsize=12)
t1 = 2*np.pi/3 #设定第一个点的x轴值
t2 = -np.pi #设定第二个点的x轴值
plt.plot([t1,t1],[0,np.sin(t1)],color ='b',linewidth=1.5,linestyle="--")
#第一个列表是x轴坐标值,第二个列表是y轴坐标值
#这两个点坐标分别为(t1,0)和(t1,np.sin(t1)),根据两点画直线l1
plt.plot([t2,t2],[0,np.cos(t2)],color ='r',linewidth=1.5,linestyle="--")
#这两个点坐标分别为(t2,0)和(t2,np.cos(t2)),根据两点画直线l2
plt.scatter([t1,],[np.sin(t1),], 50, color ='b')
plt.scatter([t2,],[np.cos(t2),], 50, color ='r')
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t1,np.sin(t1)), #点的位置
xycoords='data', #注释文字的偏移量
xytext=(+10,+30), #文字离点的横纵距离
textcoords='offset points',
fontsize=14, #注释的大小
arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=.2")) #箭头指向的弯曲度
plt.annotate(r'$\cos(-\pi)=-1$',
xy=(t2,np.cos(t2)), #点的位置
xycoords='data', #注释文字的偏移量
xytext=(0,-40), #文字离点的横纵距离
textcoords='offset points',
fontsize=14, #注释的大小
arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=.2"))
#箭头指向的弯曲度
for label in ax.get_xticklabels()+ax.get_yticklabels(): #获取刻度
label.set_fontsize(18) #设置刻度字体大小
plt.fill_between(X,np.abs(X)<0.5,sin,sin>0.5,color='g',alpha=0.8)
#设置正弦函数的填充区域,其中的一种方式
plt.fill_between(X,cos,where=(-2.5<X)&(X<-0.5),color='purple')
#设置余弦函数的填充区域,另外一种方式
plt.grid()
plt.savefig("C:\\绘图实例之COS()&SIN().PNG",dpi=300)
plt.show() #显示图表
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X,Y,Z = axes3d.get_test_data(0.05)
# Plot the 3D surface
ax.plot_surface(X,Y,Z,rstride=8,cstride=8,alpha=0.3)
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm. coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm. coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm. coolwarm)
ax.set_xlim(-40, 40)
ax.set_ylim(-40, 40)
ax.set_zlim(-100, 100)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
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)
#Z是高度值
Z = np.sin(R)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow')) #stride表示跨度
# ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
# ax.set_zlim(-2,2)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
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)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2,2)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
ax = plt.axes([0.025,0.025,0.95,0.95], polar=True)
N = 20
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = 10*np.random.rand(N)
width = np.pi/4*np.random.rand(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)
for r,bar in zip(radii, bars):
bar.set_facecolor( plt.cm.jet(r/10.))
bar.set_alpha(0.5)
ax.set_xticklabels([])
ax.set_yticklabels([])
# savefig('../figures/polar_ex.png',dpi=48)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
def f(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 10
x = np.linspace(-3,3,3.5*n)
y = np.linspace(-3,3,3.0*n)
X,Y = np.meshgrid(x,y)
Z = f(X,Y)
plt.axes([0.025,0.025,0.95,0.95])
plt.imshow(Z,interpolation='nearest', cmap='bone', origin='lower')
plt.colorbar(shrink=.92)
plt.xticks([]), plt.yticks([])
plt.show()
import numpy as np
import matplotlib.pyplot as plt
n = 8
X,Y = np.mgrid[0:n,0:n]
T = np.arctan2(Y-n/2.0, X-n/2.0)
R = 10+np.sqrt((Y-n/2.0)**2+(X-n/2.0)**2)
U,V = R*np.cos(T), R*np.sin(T)
plt.axes([0.025,0.025,0.95,0.95])
plt.quiver(X,Y,U,V,R, alpha=.5)
plt.quiver(X,Y,U,V, edgecolor='k', facecolor='None', linewidth=.5)
plt.xlim(-1,n), plt.xticks([])
plt.ylim(-1,n), plt.yticks([])
plt.show()
import numpy as np
import matplotlib.pyplot as plt
eqs = []
eqs.append((r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$"))
eqs.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$"))
eqs.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$"))
eqs.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$"))
eqs.append((r"$F_G = G\frac{m_1m_2}{r^2}$"))
plt.axes([0.025,0.025,0.95,0.95])
for i in range(24):
index = np.random.randint(0,len(eqs))
eq = eqs[index]
size = np.random.uniform(12,32)
x,y = np.random.uniform(0,1,2)
alpha = np.random.uniform(0.25,.75)
plt.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=alpha,
transform=plt.gca().transAxes, fontsize=size, clip_on=True)
plt.xticks([]), plt.yticks([])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
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)
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
C = plt.contour(X,Y,f(X,Y),8,colors='black',lw=0.5) #等高线分多少部分
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()