#1.绘制折线图
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['Simhei']
plt.rcParams['axes.unicode_minus']=False
plt.figure(figsize=(15,10),dpi=80)
x=np.linspace(-5,5,100)
y=x**2
plt.xlim(-5,5)
plt.ylim(0,10)
plt.xticks([-2,-4,0,2,4])
plt.yticks([0,5,10])
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('一元二次函数')
plt.grid()
plt.plot(x,y,c='red',linestyle='-',linewidth=4,marker='*',markersize=10,label='y=x**2')
plt.legend(loc='upper right')
plt.savefig('a.jpg'
plt.show()
2.绘制多个图
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(15,10),dpi=80)
x=np.linspace(-np.pi,np.pi,100)
y1,y2=np.sin(x),np.cos(x)
plt.xlim(-np.pi-1,np.pi+1)
plt.ylim(-1.2,1.2)
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi])
plt.yticks(np.linspace(-1,1,5))
plt.plot(x,y1,label='y=sin(x)')
plt.plot(x,y2,label='y=cos(x)')
plt.legend(loc='upper right')
plt.savefig('sin(x)和cos(x)')
plt.show()
3.绘制子图
import matplotlib.pyplot as plt
import numpy as np
import sympy as sp
def set_axis():
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))
plt.subplots_adjust(hspace=0.8,wspace=0.5)
plt.subplot(3,3,1)
x1=np.linspace(-5,5,100)
y1=5+0*x1
plt.xlim(-2,6)
plt.ylim(-2,6)
plt.xticks(np.linspace(-5,5,6))
plt.yticks(np.linspace(-2,6,5))
set_axis()
plt.title('y=5')
plt.plot(x1,y1)
plt.subplot(3,3,2)
x2=np.linspace(-5,5,100)
y2=x2
plt.title('y=x')
set_axis()
plt.plot(x2,y2)
plt.subplot(3,3,3)
x3=np.linspace(-2*np.pi,2*np.pi,100)
y3=np.sin(x3)
plt.title('y=sin(x)')
set_axis()
plt.plot(x3,y3)
plt.subplot(3,3,4)
x4=np.linspace(-5,5,100)
y4=x4**2
plt.title(f'$y=x^{2}$')
set_axis()
plt.plot(x4,y4)
plt.subplot(3,3,5)
x5=np.linspace(-5,5,100)
y5=x5**3
plt.title(f'$y=x^{3}$')
set_axis()
plt.plot(x5,y5)
plt.subplot(3,3,6)
x6=np.linspace(-2*np.pi,2*np.pi,40)
y6=np.cos(x6)
plt.title('y=cos(x)')
set_axis()
plt.scatter(x6,y6,c='red')
plt.subplot(3,3,7)
x7=np.linspace(-5,1,100)
y7=np.exp(x7)
plt.xlim(-5,2)
plt.ylim(-1.5,3)
plt.xticks([-4,-3,-2,-1,0,1])
plt.yticks(np.linspace(-1,2,4))
plt.title('$y=e^{x}$')
set_axis()
plt.plot(x7,y7)
plt.subplot(3,3,8)
x8=np.linspace(0.5,5,100)
y8=np.log(x8)
plt.xlim(-1,6)
plt.ylim(-1,2.5)
plt.xticks([1,2,3,4,5])
plt.yticks([0,1,2])
plt.title('y=loge(x)')
set_axis()
plt.plot(x8,y8)
plt.subplot(3,3,9)
x9=np.linspace(0,5,100)
y9=x9**0.5
plt.title('$y=\sqrt{x}$')
set_axis()
plt.plot(x9,y9)
plt.show()
|