ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Matplotlib 入门指南

2021-11-19 21:03:36  阅读:203  来源: 互联网

标签:指南 plot plt 入门 Matplotlib set np ax subplot


文章目录

基本用法

image-20211118221205286

import matplotlib.pyplot as plt
import numpy as np

# 横坐标 [-1,1] 划分 50 个
x = np.linspace(-1,1,50)
y = 2 * x + 1

plt.plot(x,y)
plt.show()

Figure图像

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10, 10, 50)
y1 = 2 * x + 1
y2 = x ** 2

# 第一张图
plt.figure()
plt.plot(x, y1)

# 第二张图,包含两个函数,设置线段颜色、宽度和风格
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1,color = 'red',linewidth=1.0,linestyle='--')

# 显示图像
plt.show()

坐标轴设置

在这里插入图片描述

# 坐标轴范围
plt.xlim((-1,2))
plt.ylim((-2,3))

# 坐标轴描述
plt.xlabel("X")
plt.ylabel("Y")

# 坐标轴单位 - 设置英文字体 - 希腊字母
plt.xticks(np.linspace(-1,2,5))
plt.yticks([-2,0,2],[r'$good$',r'$midle\ score$',r'$bad$'])

# 坐标轴边框及原点
ax = plt.gca()

# 消失边框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# 设置x,y坐标轴
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# 移动x,y轴
ax.spines['bottom'].set_position(('data', -1))
ax.spines['left'].set_position(('data', 0))

Legend图例

在这里插入图片描述

# 设置legend
l1, = plt.plot(x, y2)
l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.legend(handles=[l1,l2], labels=['up','down'], loc='best')

Annotation标注

在这里插入图片描述

# Annotation标注
# 方法一
x0 = 1
y0 = 2 * x0 + 1
plt.scatter(x0, y0, s=50, color='r')
plt.plot([x0, x0], [y0, 0], 'r--', lw=2)

# 方法二
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data',
             xytext=(+30, -30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))

# 方法三
plt.text(-3,3,r'$This\ is\ a\ test\ \sigma_t\ .$',fontdict={'size':16,'color':'r'})

Tick 能见度

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hqgOSdZ8-1637326030461)(https://i.loli.net/2021/11/19/Bnbk13j9KJmxRyv.png)]

# Tick 能见度
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='red', edgecolor='None', alpha=0.5))

Scatter散点图

在这里插入图片描述

# 构造数据范围
n = 1024
X = np.random.normal(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.scatter(np.arange(5), np.arange(5), c='red')

# 坐标轴范围
plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))

# 隐藏 x,y 的 ticks
plt.xticks(())
plt.yticks(())

Bar柱状图

在这里插入图片描述

# 构造数据范围
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='blue', edgecolor='white')
plt.bar(X, -Y2, facecolor='pink', edgecolor='white')

# 加上文字描述
for x, y in zip(X, Y1):
    plt.text(x, y+0.05, '-%.2f' % y, ha='center', va='bottom')

for x, y in zip(X, Y2):
    plt.text(x, -y-0.05, '%.2f' % y, ha='center', va='top')

Contours等高线图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fR51fQ6h-1637326030472)(https://i.loli.net/2021/11/19/mnKZdclbgjes3pq.png)]

# 构造数据范围
def height(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, height(X, Y), 8, alpha=0.75, cmap=plt.cm.cool)

# 绘制等高线
C = plt.contour(X, Y, height(X, Y), 8, color='black', linewidth=.5)

# 加上文字
plt.clabel(C, inline=True, fontsize=10)

Image图片

z.png)]

# 图片数据
a = np.array([0.313, 0.365, 0.423, 0.365, 0.439,
             0.525, 0.423, 0.525, 0.651]).reshape(3, 3)

# Image 图片
plt.imshow(a, interpolation='none', cmap='bone', origin='upper')

# 显示 bar
plt.colorbar(shrink=0.8)

3D 数据

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3bwqeoOa-1637326030476)(https://i.loli.net/2021/11/19/vmRXCsBrV7qzfWG.png)]

# 设置 3D 画布
fig = plt.figure()
ax = Axes3D(fig)

# 构造数据范围
X = np.arange(-4, 4, 0.5)
Y = np.arange(-4, 4, 0.5)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# 绘制 3D
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')

# 绘制等高线
ax.contourf(X, Y, Z, zdir='x', offset=-4, cmap='rainbow')

# 设置 z 轴范围
ax.set_zlim(-2, 2)

Subplot 多合一

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Yacg1v45-1637326030477)(https://i.loli.net/2021/11/19/3nQCNygAJEZUbat.png)]

# 创建画布
plt.figure()

# 画布划分 2 行 1 列,取第一个位置
plt.subplot(2, 1, 1)
plt.plot([-1, 1], [-1, 1])

# 画布划分 2 行 3 列,取第四个位置
plt.subplot(2, 3, 4)
plt.plot([-1, 1], [-1, 1])

# 画布划分 2 行 3 列,取第五个位置
plt.subplot(2, 3, 5)
plt.plot([-1, 1], [-1, 1])

# 画布划分 2 行 3 列,取第六个位置
plt.subplot(2, 3, 6)
plt.plot([-1, 1], [-1, 1])

Subplot 分格显示

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-z2IVGJ8C-1637326030479)(https://i.loli.net/2021/11/19/QZBod3PmCJ52Kbv.png)]

# 方法一
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=1)
ax3 = plt.subplot2grid((3, 3), (1, 2), colspan=1, rowspan=1)
ax3 = plt.subplot2grid((3, 3), (2, 0), colspan=3, rowspan=1)

# 方法二
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])

# 方法三
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax1.plot()
ax2.plot()
ax3.plot()
ax4.plot()

Animation动画

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yGYfR2Mf-1637326030480)(https://i.loli.net/2021/11/19/PDRZnXB9SpiAOgo.png)]

# 定义两个区域
fig, ax = plt.subplots()

# 绘制 x
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/100))
    return line,

def init():
    line.set_ydata(np.sin(x))
    return line,

# 动起来
ani = animation.FuncAnimation(
    fig, func=animate, frames=100, init_func=init, interval=20, blit=True)

微信关注『方糖算法』

各类面试资料、内推资源,关注微信公众号获取哦。
在这里插入图片描述

标签:指南,plot,plt,入门,Matplotlib,set,np,ax,subplot
来源: https://blog.csdn.net/xg987599519/article/details/121430690

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有