Matplotlib
Matplotlib 是Python中类似 MATLAB 的绘图工具,熟悉 MATLAB 也可以很快的上手 Matplotlib。
1.Matplotlib基础用法
plot是绘制各种图形的命令子库,相当于快捷方式。
plt.plot(x,y,format_string,**kwargs)常用参数意义:
- x:横坐标
- y:纵坐标
- format_string:定义线条的颜色和样式的操作
- linestyle:线条风格
- linewidth:线条宽度
- alpha:透明度
- color:线段颜色
def matplotlib_1():
"""
matplotlib 最基本的用法
:return: 在平面直角坐标系中画出图像
"""
x = np.linspace(-10, 10, 10000)
y = np.sin(x)
plt.plot(x, y)
plt.show() # 显示出图像。
注意在pycharm中运行一定要有plt.show(),不然不会显示图像。
运行结果:
2.Matplotlib中Figure
在任何绘图之前,我们需要一个Figure对象,可以理解成我们需要一张画板才能开始绘图。
def matplotlib_figure():
"""
我的理解是一个figure对应一个框框,
如果要两个图像显示在两个框框中就在每一个前面都写一个figure
如果不需要则在两个前面写一个figure就可以了
:return: 画出图像
"""
x = np.linspace(-1, 1, 100)
y1 = 2 * x + 1
y2 = x ** 2
# 图像显示在两个figure中
plt.figure()
plt.plot(x, y1)
plt.figure()
plt.plot(x, y2)
# 将图像显示在一个figure中
plt.figure(figsize=(5, 5))
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.plot(x, y2, color='green', linewidth=2.0, linestyle='-.')
plt.show()
运行结果:
两张图分开。
两张图放在一起:
3.Matplotlib设置坐标轴
- plt.xlim()、plt.yli接收元组数据设置坐标轴范围。
- plt.xlabel,plt.ylabel:接收字符串对文本信息进行描述。
- plt.xticks(ticks=None, labels=None, **kwargs)、plt.yticks。ticks:应当放置刻度的位置列表。labels:在给定位置放置的标签。
- plt.gca():进行坐标轴的移动。
- spines:接收位置
- set_color:设置颜色
- set_position设置位置
def matplotlib_3():
"""
设置坐标轴
:return:
"""
x = np.linspace(-1, 1, 100)
y1 = 2 * x + 1
y2 = x ** 2
# 限制x, y 的坐标范围
plt.xlim((-1, 1))
plt.ylim((-1, 2))
# 对横纵坐标进行描述
plt.xlabel("I am X")
plt.ylabel("I am Y")
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.plot(x, y2, color='green', linewidth=2.0, linestyle='-.')
# 新的横坐标
new_ticks = np.linspace(-2, 2, 10)
plt.xticks(new_ticks)
plt.yticks([-1, 0, 1, 2, 3],
['lavel1', 'lavel2', 'lavel3', 'lavel4', 'lavel5'])
# gca get current axis
# 利用plt.gca( )进行坐标轴的移动
ax = plt.gca()
# 设置边框颜色
ax.spines['right'].set_color('red')
ax.spines['top'].set_color('green')
# 把X轴的刻度设置为‘bottom’
# 把Y轴的刻度设置为‘left’
# 设置bottom和left对应到零点位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
plt.show()
4.Matplotlib设置标签
一个Figure中有多条线时不仅可以设置颜色不同,还可以设置标签来标注线段的含义。
plt.legend(*args, **kwargs)
- handles:接收列表代表要标注的线段。
- labels:接收列表和代表和handles一一对应的标签。
- loc:标签设置的位置
def matplotlib_4():
"""
设置图例
:return:显示图像
"""
x = np.linspace(-1, 1, 100)
y1 = 2 * x + 1
y2 = x ** 2
# 限制x, y 的坐标范围
plt.xlim((-1, 1))
plt.ylim((-1, 2))
# 对横纵坐标进行描述
plt.xlabel("I am X")
plt.ylabel("I am Y")
l1, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
l2, = plt.plot(x, y2, color='green', linewidth=2.0, linestyle='-.')
# 设置图例
plt.legend(handles=[l1, l2], labels=['test1', 'test2'], loc='best')
"""
handles = [],中间放线,
labels = [],中间放标签名称
loc = 'best', 系统自动找最合适的位置来放置标签
"""
# 新的横坐标
new_ticks = np.linspace(-1, 1, 10)
plt.xticks(new_ticks)
plt.yticks([-1, 0, 1, 2, 3],
['lavel1', 'lavel2', 'lavel3', 'lavel4', 'lavel5'])
plt.show()
5.Matplotlib设置标注
plt.annotate(text, xy, *args, **kwargs)
- text:注释文本内容
- xy:被指向的数据点(x,y)的位置坐标
- xytext:文字相对于所要标注的点所在的位置
- textcoords :注释文本的坐标系属性(‘offset points’以点为单位偏移。‘offset pixels’以像素为单位偏移)
- arrowprops:箭头的样式,dict(字典)型数据。(arrowstyle:箭头风格。connectionstyle设置箭头样式和弯曲度)
plt.text(x, y, s, fontdict=None, withdash=False, **kwargs)
- x,y:显示内容的坐标位置
- s:显示内容
- fontdict:一个定义s格式的dict
def matplotlib_5():
x = np.linspace(-1, 1, 100)
y1 = 2 * x + 1
y2 = x ** 2
# 限制x, y 的坐标范围
plt.xlim((-1, 1))
plt.ylim((-1, 2))
# 对横纵坐标进行描述
plt.xlabel("I am X")
plt.ylabel("I am Y")
plt.plot(x, y1, color='red', linewidth=2.0, linestyle='--')
plt.plot(x, y2, color='green', linewidth=2.0, linestyle='-.')
# 新的横坐标
new_ticks = np.linspace(-2, 2, 10)
plt.yticks([-1, 0, 1, 2, 3],
['lavel1', 'lavel2', 'lavel3', 'lavel4', 'lavel5'])
# gca get current axis
# 利用plt.gca( )进行坐标轴的移动
ax = plt.gca()
# 设置边框颜色
ax.spines['right'].set_color('red')
ax.spines['top'].set_color('green')
# 把X轴的刻度设置为‘bottom’
# 把Y轴的刻度设置为‘left’
# 设置bottom和left对应到零点位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
x0 = 0.5
y0 = 2 * x0 + 1
# 画点
plt.scatter(x0, y0, s=50, color='blue') # s是大小
# 画虚线
plt.plot([x0, x0], [y0, 0], color='black', linewidth=2.0, linestyle='-') # x0, y0 代表蓝色点,x0,0代表X轴上的点。
plt.annotate(f'2x+1={y0}', xy=(x0, y0), xytext=(+30, -30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'), weight='heavy')
"""
xy代表所指向的点坐标
xytest代表文字描述相对于所指向的点坐标所处的位置
"""
plt.text(-1, 2, 'this is the text', fontdict={'size':'16', 'color':'red'})
plt.show()
6.Matplotlib散点图
plt.scatter
- x、y:点坐标
- color:点颜色
- alpha:透明度
def matplotlib_6():
x = np.random.normal(0, 1, 1500)
y = np.random.normal(0, 1, 1500) # 0-1的正态分布
plt.scatter(x, y, color='red', alpha=0.5) # alpha代表透明度
plt.show()
7.Matplotlib直方图
plt.bar():画直方图
def matplotlib_7():
x = np.arange(10)
y = 2**x + 10
plt.bar(x, y, color='b')
for x,y in zip(x, y): # 将x,y结合成一个整体
plt.text(x+0.4,y,f'{y}',va='bottom', ha='center')
plt.show()
8.Matplotlib等高线
coutour([X, Y,] Z,[levels], **kwargs)
- X,Y类似横纵坐标
- Z:类似矩阵绘制轮廓的高度值
- 代码中,8代表八条线
- cmap代表等高线颜色样式
def f(x, y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
def matplotlib_8():
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)
plt.show()