matplotlib 总结(比较基础版)

1.基础

  • 导入库
    import matplotlib.pyplot as plt
  • 画直线
    plt.plot(x,y)
  • 展示图
    plt.show()
  • 创建一个图
    plt.figure(num=3, figsize=(8, 5),)
  • 展示线的颜色、风格、粗细
    plt.plot(x, y1, color=‘red’, linewidth=1.0, linestyle=’–’)
  • 设置取值范围
    plt.xlim((-1,2))
    plt.ylim((-1,2))
  • 设置坐标轴的名字
    plt.xlabel(‘l am x’)
    plt.ylabel(‘l am y’)
  • 设置坐标轴的分度
    plt.yticks([-2, -1.8, -1, 1.22, 3],
            [r’$really\ bad$’, r’$bad$’, r’$normal$’, r’$good$’, r’$really\ good$’])
    !!! 如果不想用Latex的格式可以去掉两边的$,和开头的r
  • 设置坐标轴的位置
# gca = 'get current axis' 得到当前的坐标轴
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

#[ 'top' | 'bottom' | 'both' | 'default' | 'none' ]
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data',0))
  • 设置图例
    plt.plot(x, y1, label=‘linear line’)
    plt.plot(x, y2, color=‘red’, linewidth=1.0, linestyle=’–’, label=‘square line’)
    plt.legend(loc=‘upper right’)
    ### 高阶图例用法
    l1, = plt.plot(x, y1, label=‘linear line’)
    l2, = plt.plot(x, y2, color=‘red’, linewidth=1.0, linestyle=’–’, label=‘square line’)
    plt.legend(handles=[l1, l2], labels=[‘up’, ‘down’], loc=‘best’)

一般

  • 散点图
    plt.scatter(x,y,s=50,color=‘r’)
  • 柱形图
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
# 给每个柱形上面加数字
for x, y in zip(X, Y1):
    # ha: 横向对齐,用哪个点
    # va: 纵向对齐,用那个点
    plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
  • 等高线图
import matplotlib.pyplot as plt
import numpy as np

def f(x,y):
    # the height function
    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)
# 画颜色   分成x+2份(这是8+2份) alpha 透明度  cmap映射表 
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)

# 画边缘 
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
# 画标签    inlie 不画在线里面
plt.clabel(C, inline=True, fontsize=10)

plt.xticks(())
plt.yticks(())
plt.show()

在这里插入图片描述

  • 展示图片imshow
# a是每个像素的大小  interploation风格  
plt.imshow(a, interpolation='nearest', cmap='bone')
# shrink是缩短情况
plt.colorbar(shrink=.92)

# 去掉 坐标轴
plt.xticks(())
plt.yticks(())
  • 3D 图片
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 初始化模板
fig = plt.figure()
# 将模板换成3D模板
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.cos(r)

# !!!画3D图
# rstride,cstride ---> 跨度     edgecolor 边缘颜色
ax.plot_surface(x,y,z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'),edgecolor='black')
# 画3D的投影图   zdir 投影到那个轴  offset 偏移量
ax.contourf(x,y,z,zdir='z',offset=-2,cmap='rainbow')

ax.set_zlim(-2,2)

plt.show()

3D图片

  • 添加注解
    解释一下参数,1:文字,2:箭头指向的坐标,3:按规则4:文字的偏移5:按规则
    fontsize:文字大小,arrowprops:指针的字典,arrowstyle:箭头风格,connectionstyle:箭头风格
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"))

1:坐标,2:文字,3:文字字典

plt.text(-3.7, 3, r'\$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t\$',
         fontdict={'size': 16, 'color': 'r'})
  • 设置坐标轴刻度文字的属性
for label in ax.get_xticklabels() + ax.get_yticklabels():
	# 字体大小
    label.set_fontsize(12)
    # facecolor 前景色,edgecolor 边缘,alpha 透明度  ,zorder=2 规则
    label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.8, zorder=2))

中上等

  • subplot多合一显示
import matplotlib.pyplot as plt

plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])

plt.subplot(2,3,4)
plt.plot([0,1],[0,1])

plt.subplot(2,3,5)
plt.plot([0,1],[0,1])

plt.subplot(2,3,6)
plt.plot([0,1],[0,1])

plt.show()

多合一

  • 我最喜欢的一种多合一
# 导入包
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
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[2,0])
ax5 = plt.subplot(gs[2,1])
plt.show()
  • 动图
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np

fig, ax=plt.subplots()

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/30))
    return line,

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

#!!! 必须要有 ani =  fig:图片,func:动作的函数,frames:帧数,inin_func:初始时候, interval:隔多长更新一下
ani = animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=20,blit=False)
# 保存我们的动图
ani.save('1.gif',writer='imagemagick')
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自由小冰儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值