Python绘制基本图形——基于Spyder的matplotlib基本绘图(课程笔记)
使用的软件是Spyder
1、 折线图
import numpy as np
import matplotlib.pyplot as mp
x = np.array([1, 2, 3, 4, 5, 6])
y = np.array([12, 34, 56, 75, 32, 4])
mp.plot(x, y)
mp.show() # 显示图表
2、 绘制水平线或垂直线
import numpy as np
import matplotlib.pyplot as mp
x = np.array([1, 2, 3, 4, 5, 6])
y = np.array([12, 34, 56, 75, 32, 4])
mp.vlines(4,10,35) # 绘制垂直线
mp.hlines(20,2,6) # 绘制水平线
mp.plot(x, y)
mp.show()
绘制多条长度不同的线
import numpy as np
import matplotlib.pyplot as mp
x = np.array([1, 2, 3, 4, 5, 6])
y = np.array([12, 34, 56, 75, 32, 4])
mp.vlines(4,10,35)
mp.hlines([10, 20, 30, 40],[1, 2, 3, 4],[6, 5, 4, 3])
mp.plot(x, y)
mp.show()
3、绘制弦曲线
3.1 正弦曲线
import numpy as np
import matplotlib.pyplot as mp
# 线性拆分1000个点
x = np.linspace(-np.pi, np.pi, 1000)
y = np.sin(x)
mp.plot(x, y)
mp.show()
3.2 余弦曲线
import numpy as np
import matplotlib.pyplot as mp
# 线性拆分1000个点
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
# 余弦曲线 cos(x)/2
cosx = np.cos(x)/2
mp.plot(x, sinx)
mp.plot(x, cosx)
mp.show()
4、线形、线宽、颜色、透明度
import numpy as np
import matplotlib.pyplot as mp
# 线性拆分1000个点
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
# 余弦曲线 cos(x)/2
cosx = np.cos(x)/2
mp.plot(x, sinx,linestyle="--",linewidth=2,alpha=0.5) # alpha表示透明度
mp.plot(x, cosx,linestyle=":", color="green")
mp.show()
颜色配置
常用颜色、中国传统颜色及多种颜色配色器
https://blog.csdn.net/ziixiaoshenwang/article/details/119831428?spm=1001.2014.3001.5501
5、设置坐标轴范围
import numpy as np
import matplotlib.pyplot as mp
# 线性拆分1000个点
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
# 余弦曲线 cos(x)/2
cosx = np.cos(x)/2
# 设置坐标轴的范围
mp.xlim(0, np.pi)
mp.ylim(0, 1)
mp.plot(x, sinx,linestyle="--",linewidth=2,alpha=0.5)
mp.plot(x, cosx,linestyle=":", color="green")
mp.show()
6、修改刻度文本
import numpy as np
import matplotlib.pyplot as mp
# 线性拆分1000个点
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
# 余弦曲线 cos(x)/2
cosx = np.cos(x)/2
# 修改x轴的刻度文本
vals = [-np.pi, -np.pi/2, 0, np.pi/2, np.pi]
texts = [r'$-\pi$',r'$-\frac{\pi}{2}$','0',r'$\pi$',r'$\frac{\pi}{2}$'] #-π,-π/2,0,π/2,π#
mp.xticks(vals, texts)
mp.plot(x, sinx,linestyle="--",linewidth=2,alpha=0.5)
mp.plot(x, cosx,linestyle=":", color="green")
mp.show()
7、设置坐标轴
import numpy as np
import matplotlib.pyplot as mp
# 线性拆分1000个点
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
# 余弦曲线 cos(x)/2
cosx = np.cos(x)/2
# 修改x轴的刻度及文本
vals = [-np.pi, -np.pi/2, 0, np.pi/2, np.pi]
texts = [r'$-\pi$',r'$-\frac{\pi}{2}$','0',r'$\pi$',r'$\frac{\pi}{2}$']
mp.xticks(vals, texts)
# 设置y轴的刻度
mp.yticks([-1.0,-0.5,0,0.5,1.0])
# 修改坐标轴
ax = mp.gca()
ax.spines['top'].set_color('none') # no表示上轴不显示
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data',0))
mp.plot(x, sinx,linestyle="--",linewidth=2,alpha=0.5)
mp.plot(x, cosx,linestyle=":", color="green")
mp.show()
该内容为课程笔记
https://www.bilibili.com/video/BV1Yo4y197bN?p=20&spm_id_from=pageDriver