matplotlab字典

1. matplotlab简介

线图;
散点图;
等高线图;
条形图;
柱状图;
3D 图形,
甚至是图形动画等等.
安装matplotlab之前需要安装numpy,接着在终端输入:

2. 基本用法

from matplotlib import pyplot as plt
import numpy as np

# ---------------------------------
# 画直线图
# 使用np.linspace定义x:范围是(-1,1);个数是50. 仿真一维数据组(x ,y)表示曲线1.
x = np.linspace(-1, 1, 50)
y = 2*x + 1

# 使用plt.figure定义一个图像窗口
plt.figure()
#使用plt.plot画(x ,y)曲线
plt.plot(x, y)
# 使用plt.show显示图像
plt.show()

在这里插入图片描述

3. figure图像

matplotlib 的 figure 就是一个 单独的 figure 小窗口, 小窗口里面还可以有更多的小图片.

使用plt.figure定义一个图像窗口:编号为3;大小为(8, 5). 使用plt.plot画(x ,y2)曲线. 使用plt.plot画(x ,y1)曲线,曲线的颜色属性(color)为红色;曲线的宽度(linewidth)为1.0;曲线的类型(linestyle)为虚线. 使用plt.show显示图像.

from matplotlib import pyplot as plt
import numpy as np

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

# 画虚线及曲线
#使用plt.figure定义一个图像窗口:编号为3;大小为(8, 5). 
plt.figure(num=3, figsize=(8, 5),)
# 使用plt.plot画(x ,y2)曲线.
plt.plot(x, y2)

# 使用plt.plot画(x ,y1)曲线,曲线的颜色属性(color)为红色;
# 曲线的宽度(linewidth)为1.0;曲线的类型(linestyle)为虚线. 使用plt.show显示图像.
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.show()

在这里插入图片描述

4. 设置坐标轴1

在 matplotlib 中如何设置坐标轴的范围, 单位长度, 替代文字等等.

import matplotlib.pyplot as plt
import numpy as np

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

plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

# 使用plt.xlim设置x坐标轴范围:(-1, 2)
plt.xlim((-1, 2))
# 使用plt.ylim设置y坐标轴范围:(-2, 3)
plt.ylim((-2, 3))
# 使用plt.xlabel设置x坐标轴名称:’I am x’
plt.xlabel('I am x')
# 使用plt.ylabel设置y坐标轴名称:’I am y’
plt.ylabel('I am y')

# 使用np.linspace定义范围以及个数:范围是(-1,2);个数是5
new_ticks = np.linspace(-1, 2, 5)
# 使用plt.xticks设置x轴刻度:范围是(-1,2);个数是5.
plt.xticks(new_ticks)

# 使用plt.yticks设置y轴刻度以及名称:刻度为[-2, -1.8, -1, 1.22, 3];
# 对应刻度的名称为[‘really bad’,’bad’,’normal’,’good’, ‘really good’].
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

plt.show()

在这里插入图片描述

5. 设置坐标轴2

如何移动matplotlib 中 axis 坐标轴的位置.

import matplotlib.pyplot as plt
import numpy as np

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

plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))

new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$'])

# 使用plt.gca获取当前坐标轴信息
ax = plt.gca()
# 使用.spines设置边框:右侧边框;使用.set_color设置边框颜色:默认白色
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# 使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置:bottom.
#(所有位置:top,bottom,both,default,none)
ax.xaxis.set_ticks_position('bottom')

# 使用.spines设置边框:x轴;使用.set_position设置边框位置:y=0的位置;
#(位置所有属性:outward,axes,data)
ax.spines['bottom'].set_position(('data', 0))

ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

plt.show()

在这里插入图片描述

6. Legend图例

matplotlib 中的 legend 图例就是为了帮我们展示出每个数据对应的图像名称. 更好的让读者认识到你的数据结构.

import matplotlib.pyplot as plt
import numpy as np

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

plt.figure()
#set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))

# set new sticks
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

# set line syles
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='upper right')
plt.show()

loc参数有多种,’best’表示自动分配最佳位置

 'best' : 0,          
 'upper right'  : 1,
 'upper left'   : 2,
 'lower left'   : 3,
 'lower right'  : 4,
 'right'        : 5,
 'center left'  : 6,
 'center right' : 7,
 'lower center' : 8,
 'upper center' : 9,
 'center'       : 10,

在这里插入图片描述

7. Annotation 标注

当图线中某些特殊地方需要标注时,我们可以使用 annotation. matplotlib 中的 annotation 有两种方法, 一种是用 plt 里面的 annotate,一种是直接用 plt 里面的 text 来写标注.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 2*x + 1

plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].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))

x0 = 1
y0 = 2*x0 + 1
# 画出一条垂直于x轴的虚线.
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')

# 添加注释 annotate, (x0, y0)这个点进行标注.
#参数xycoords='data' 是说基于数据的值来选位置, 
# xytext=(+30, -30) 和 textcoords='offset points' 对于标注位置的描述 和 xy 偏差值, 
# arrowprops是对图中箭头类型的一些设置.
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"))

# 添加注释 text
# 其中-3.7, 3,是选取text的位置
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 16, 'color': 'r'})

在这里插入图片描述

8. tick能见度

当图片中的内容较多,相互遮盖时,我们可以通过设置相关内容的透明度来使图片更易于观察,也即是通过本节中的bbox参数设置来调节图像信息.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 0.1*x

plt.figure()
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
plt.plot(x, y, linewidth=10, zorder=1)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].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))

# label.set_fontsize(12)重新调节字体大小
# bbox设置目的内容的透明度相关参,
# facecolor调节 box 前景色
# edgecolor 设置边框, 本处设置边框为无,alpha设置透明度
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
plt.show()

在这里插入图片描述

9. Scatter 散点图

import matplotlib.pyplot as plt
import numpy as np

n = 1024    # data size
X = np.random.normal(0, 1, n) # 每一个点的X值
Y = np.random.normal(0, 1, n) # 每一个点的Y值
T = np.arctan2(Y,X) # for color value

# 输入X和Y作为location,size=75,颜色为T,color map用默认值
# 透明度alpha 为 50%
plt.scatter(X, Y, s=75, c=T, alpha=.5)

plt.xlim(-1.5, 1.5)
plt.xticks(())  # ignore xticks
plt.ylim(-1.5, 1.5)
plt.yticks(())  # ignore yticks

plt.show()

在这里插入图片描述

10. Bar柱状图

import matplotlib.pyplot as plt
import numpy as np

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)
plt.bar(X, -Y2)

plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())

# 用facecolor设置主体颜色,edgecolor设置边框颜色为白色
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')

# 接下来我们用函数plt.text分别在柱体上方(下方)加上数值
for x, y in zip(X, Y1):
    # ha: horizontal alignment
    # va: vertical alignment
    plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')

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

plt.show()

在这里插入图片描述

11. Contours 等高线图

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)

# use plt.contourf to filling contours
# X, Y and value for (X,Y) point
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)

# use plt.contour to add contour lines
# 8代表等高线的密集程度
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)

plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())

在这里插入图片描述

12. Image图片

这一节我们讲解怎样在matplotlib中打印出图像。这里我们打印出的是纯粹的数字,而非自然图像

import matplotlib.pyplot as plt
import numpy as np

a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)

plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')

# 其中我们添加一个shrink参数,使colorbar的长度变短为原来的92%:
plt.colorbar(shrink=.92)

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

在这里插入图片描述

13. 3D数据

首先在进行 3D Plot 时除了导入 matplotlib ,还要额外添加一个模块,即 Axes 3D 3D 坐标轴显示:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)

# X, Y value
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)    # x-y 平面的网格
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)

# 做出一个三维曲面,并将一个 colormap rainbow 填充颜色,之后将三维图像投影到 XY 平面上做一个等高线图。
# 其中,rstride 和 cstride 分别代表 row 和 column 的跨度。
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))

plt.show()

在这里插入图片描述

14. Subplot 多合一显示


matplotlib 是可以组合许多的小图, 放在一张大图里面显示的. 使用到的方法叫作 subplot.

使用import导入matplotlib.pyplot模块, 并简写成plt. 使用plt.figure创建一个图像窗口.

import matplotlib.pyplot as plt

plt.figure()

# 使用plt.subplot来创建小图. 
# plt.subplot(2,2,1)表示将整个图像窗口分为2行2列, 当前位置为1. 
# 使用plt.plot([0,1],[0,1])在第1个位置创建一个小图.
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])

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

# plt.subplot(2,2,3)可以简写成plt.subplot(223)
plt.subplot(223)
plt.plot([0,1],[0,3])

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

plt.show()  # 展示

在这里插入图片描述
不均匀图中图

# 使用plt.subplot(2,1,1)将整个图像窗口分为2行1列, 当前位置为1. 使用plt.plot([0,1],[0,1])在第1个位置创建一个小图.
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])

# 使用plt.subplot(2,3,4)将整个图像窗口分为2行3列, 当前位置为4.
plt.subplot(2,3,4)
plt.plot([0,1],[0,2])

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

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

plt.show()  # 展示

在这里插入图片描述

15. Subplot 分格显示

matplotlib 的 subplot 还可以是分格的,这里介绍三种方法.

1.subplot2grid

import matplotlib.pyplot as plt

plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax1.plot([1, 2], [1, 2])    # 画小图
ax1.set_title('ax1_title')  # 设置小图的标题

ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')

plt.show()

在这里插入图片描述
2.gridspec

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure()
gs = gridspec.GridSpec(3, 3)

ax6 = plt.subplot(gs[0, :])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax9 = plt.subplot(gs[-1, 0])
ax10 = plt.subplot(gs[-1, -2])

plt.show()

3.subplots

f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
plt.tight_layout()
plt.show()

16. 图中图

# 导入pyplot模块
import matplotlib.pyplot as plt

# 初始化figure
fig = plt.figure()

# 创建数据
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]

# 大图
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8

ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')  # r为red颜色
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')

# 小图
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')

plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g') # 注意对y进行了逆序处理
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')

plt.show()

在这里插入图片描述

17. 次坐标轴

有时候我们会用到次坐标轴,即在同个图上有第2个y轴存在。同样可以用matplotlib做到,而且很简单。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)

y1 = 0.05 * x**2

y2 = -1 * y1

fig, ax1 = plt.subplots()

# 第二个y坐标
ax2 = ax1.twinx()

ax1.plot(x, y1, 'g-')   # green, solid line

ax1.set_xlabel('X data')

ax1.set_ylabel('Y1 data', color='g')

ax2.plot(x, y2, 'b-') # blue

ax2.set_ylabel('Y2 data', color='b')

plt.show()

在这里插入图片描述

18. Animation动画

from matplotlib import 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/10.0))
    return line,

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

# fig 进行动画绘制的figure
# func 自定义动画函数,即传入刚定义的函数animate
# frames 动画长度,一次循环包含的帧数
# init_func 自定义开始帧,即传入刚定义的函数init
# interval 更新频率,以ms计
# blit 选择更新所有点,还是仅更新产生变化的点。应选择True,但mac用户请选择False,否则无法显示动画
ani = animation.FuncAnimation(fig=fig,  
                              func=animate,  
                              frames=100, 
                              init_func=init,  
                              interval=20,  
                              blit=False)  

plt.show()

如果用pycharm ,则需要在 Preferences -> Tools -> Python Scientific 取消勾选show plots in toolwindow,才会出现动画效果

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值