Python自学 day06 ---Matplotlib

同之前

先在此放一些大佬写好的总结吧~

转载自大佬:止战 --> Python--matplotlib绘图可视化知识点整理

Notzuonotdied --> Python Matplotlib简易教程

以下是本菜鸟练习的笔记..

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

# <editor-fold desc="基本用法">
# x = np.linspace(-1,1,50)        # 从-1到1生成50个点
# y = 2*x + 1
# plt.plot(x, y)
# plt.show()
# </editor-fold>

# <editor-fold desc="Figure 图形化窗口">
# x = np.linspace(-3, 3, 50)
# y1 = 2*x + 1
# y2 = x**2
# plt.figure()        # 定义figure
# plt.plot(x, y1)
#
# plt.figure()        # figure2
# plt.plot(x, y2)
#
# # 在一个figure中输出多条线
# plt.figure(num=3, figsize=(8, 5),)      # 定义第三个figure 长宽8,5
# plt.plot(x, y2)
# plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# plt.show()
# </editor-fold>

# <editor-fold desc="设置坐标轴1 设置名字和间隔">
# 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))       # x轴取值范围
# plt.ylim((-2, 3))       # y轴取值范围
# plt.xlabel('I am x')    # x轴的lable 描述x轴
# plt.ylabel('I am y')    # y轴的lable 描述y轴
#
# new_ticks = np.linspace(-1, 2, 5)       # 小标 换成-1到2 五个单位
# print(new_ticks)
# plt.xticks(new_ticks)                   # 设置(替换)x值的ticks
#
# plt.yticks([-2, -1.8, -1, 1.22, 3],[r'really\ bad', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
# # $really$  数学类型显示数据 换成好看的字体
# # \alpha 转译成(输出)α
# plt.show()
# </editor-fold>

# <editor-fold desc="设置坐标轴2 设置不同名字和位置 调整坐标轴">
# 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$'])
#
# # gca = 'get current axis'  取出轴
# # spines 脊梁, 四个边框
# ax = plt.gca()
# ax.spines['right'].set_color('none')            # 右边的边框设置成none
# ax.spines['top'].set_color('none')
#
#
# # 调整坐标轴
# ax.xaxis.set_ticks_position('bottom')           # x轴用bottom(下面)代替
#
# ax.spines['bottom'].set_position(('data', 0))   # 选择bottom  放在原点
#
# ax.yaxis.set_ticks_position('left')             # y轴用left(左边)代替
# # 位置所有属性:outward,axes,data
# ax.spines['left'].set_position(('data',0))
# plt.show()
# </editor-fold>

# <editor-fold desc="Legend 图例">
# 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')      # 加‘逗号’ 传入legend
# l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
#
# plt.legend(loc='upper right')       # loc 位置
#
# #调整位置和名称
# plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='best')
# 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,
# </editor-fold>

# <editor-fold desc="Annotation 标注 移动坐标,添加注释">
# # 画出基本图
# 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))
#
# # scatter 散点图
# # plot 直线图
# x0 = 1
# y0 = 2*x0 + 1
# plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)     # k-- 表示 黑色虚线
# # set dot styles
# plt.scatter([x0, ], [y0, ], s=50, color='b')
#
# # 添加注释 annotate 方法1
# # 正则,坐标,xy的基准值,文字描述,文字描述基准,字体大小,方向线(线的形式,线的弧度)
# 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 方法2
# # 位置,内容,sigma(_i)角标,字体,颜色
# plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma\ \alpha_t$',
#          fontdict={'size': 16, 'color': 'r'})
#
# plt.show()
# </editor-fold>

# <editor-fold desc="tick 能见度">
# #生成图形
# 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))
#
# # 调整坐标
# 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()
# </editor-fold>

# <editor-fold desc="Scatter 散点图">
# # 产生随机数据,图像化数据集 生成1024个呈标准正态分布的二维数据组
# n = 1024    # data size
# X = np.random.normal(0, 1, n) # 每一个点的X值     # 平均值为0, 方差为1, 1024个数
# Y = np.random.normal(0, 1, n) # 每一个点的Y值
# T = np.arctan2(Y,X) # for color value
#
# plt.scatter(X, Y, s=75, c=T, alpha=.5)          # 位置,大小,(colormap)颜色,透明度
#
# plt.xlim(-1.5, 1.5)
# plt.xticks(())  # ignore xticks
# plt.ylim(-1.5, 1.5)
# plt.yticks(())  # ignore yticks
#
# plt.show()
# </editor-fold>

# <editor-fold desc="Bar 柱状图">
# # 生成基本图形    向上向下分别生成12个数据,X为 0 到 11 的整数 ,
# # Y是相应的均匀分布的随机数据。 使用的函数是plt.bar,参数为X和Y:
# 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分别在柱体上方(下方)加上数值,用%.2f保留两位小数,
# # 横向居中对齐ha='center',纵向底部(顶部)对齐va='bottom':
# 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()
# </editor-fold>

# <editor-fold desc="Contours 等高线图">
# # 画等高线
# # 数据集即三维点 (x,y) 和对应的高度值,共有256个点。
# # 高度值使用一个 height function f(x,y) 生成。 x, y 分别是在区间 [-3,3] 中均匀分布的256个值
# # 并用meshgrid在二维平面中将每一个x和每一个y分别对应起来,编织成栅格:
# 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,y
#
# # 接下来进行颜色填充。使用函数plt.contourf把颜色加进去,
# # 位置参数分别为:X, Y, f(X,Y)。透明度0.75
# # 并将 f(X,Y) 的值对应到color map的暖色组中寻找对应颜色
# # 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)      # cmap = colormap [hot,cool等]
#
# #接下来进行等高线绘制。使用plt.contour函数划线。位置参数为:X, Y, f(X,Y)。
# # 颜色选黑色,线条宽度选0.5。现在的结果如下图所示,只有颜色和线条,还没有数值Label:
# # use plt.contour to add contour lines
# C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
# # 0代表2部分
# # 8代表等高线分为10部分
#
# # 添加高度数字
# #  其中,8代表等高线的密集程度,这里被分为10个部分。如果是0,则图像被一分为二。
# # 最后加入Label,inline控制是否将Label画在线里面,字体大小为10。并将坐标轴隐藏:
# plt.clabel(C, inline=True, fontsize=10)
# plt.xticks(())
# plt.yticks(())
#
# plt.show()
# </editor-fold>

# <editor-fold desc="Image 图片">
# # 随机矩阵画图
# # 这里我们打印出的是纯粹的数字,而非自然图像。
# # 我们今天用这样 3x3 的 2D-array 来表示点的颜色,每一个点就是一个pixel。
# a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
#               0.365348418405, 0.439599930621, 0.525083754405,
#               0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
#
# # imageshow 图像,输出方式,color map , [lower,upper]黑色,白色位置反转
# #  出图方式: http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
# plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
#
# # colorbar
# # 下面我们添加一个colorbar ,其中我们添加一个shrink参数,使colorbar的长度变短为原来的92%:
# plt.colorbar(shrink=.92)
#
# plt.xticks(())
# plt.yticks(())
# plt.show()
# </editor-fold>

# <editor-fold desc="3D 三维曲面+等高线">
# # 添加新模块
# # from mpl_toolkits.mplot3d import Axes3D
#
# # 定义一个图像窗口,在窗口上添加3D坐标轴
# fig = plt.figure()
# ax = Axes3D(fig)
#
# # 接下来给进 X 和 Y 值,并将 X 和 Y 编织成栅格。
# # 每一个(X, Y)点对应的高度值我们用下面这个函数来计算。
# # 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 平面上做一个等高线图。
# # 坐标轴,跨度为1(密集),5(疏松),颜色
# ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
#
# # 投影
# # 下面添加 XY 平面的等高线:
# # 坐标,从z轴压下去,压到比0点低2个单位,
# ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
#
# plt.show()
# </editor-fold>

# <editor-fold desc="Subplot 多合一显示">
# # 一个figure中创建多个小图
# 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)表示将整个图像窗口分为2行2列, 当前位置为2.
# #  使用plt.plot([0,1],[0,2])在第2个位置创建一个小图.
# plt.subplot(2,2,2)
# plt.plot([0,1],[0,2])
#
# # plt.subplot(2,2,3)表示将整个图像窗口分为2行2列,当前位置为3.
# # plt.subplot(2,2,3)可以简写成plt.subplot(223), matplotlib同样可以识别.
# # 使用plt.plot([0,1],[0,3])在第3个位置创建一个小图.
# plt.subplot(223)
# plt.plot([0,1],[0,3])
#
# # plt.subplot(224)表示将整个图像窗口分为2行2列, 当前位置为4.
# # 使用plt.plot([0,1],[0,4])在第4个位置创建一个小图.
# plt.subplot(224)
# plt.plot([0,1],[0,4])
#
# plt.show()  # 展示
# </editor-fold>

# <editor-fold desc="Subplot 分格显示">
# subplot 分格显示
# 方法1:subplot2grid
# 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.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()
# </editor-fold>

# <editor-fold desc="图中图">
# # 初始化figure
# fig = plt.figure()
#
# # 创建数据
# x = [1, 2, 3, 4, 5, 6, 7]
# y = [1, 3, 4, 2, 5, 8, 6]
# # 绘制大图   相当于整个figure的0.1 10%
# left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# # 将大图坐标系添加到figure中,颜色为r(red),取名为title:
# ax1 = fig.add_axes([left, bottom, width, height])
# ax1.plot(x, y, 'r')
# 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()
# </editor-fold>

# <editor-fold desc="次坐标轴">
# x = np.arange(0, 10, 0.1)
# y1 = 0.05 * x**2
# y2 = -1 * y1
# # 获取figure默认的坐标系 ax1:
# fig, ax1 = plt.subplots()
#
# # 对ax1调用twinx()方法,生成如同镜面效果后的ax2:
# ax2 = ax1.twinx()
# # 接着进行绘图, 将 y1, y2 分别画在 ax1, ax2 上:
# ax1.plot(x, y1, 'g-')   # 绿色的线
# 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()
# </editor-fold>

# <editor-fold desc="Animation 动画">
# from matplotlib import animation

# fig, ax = plt.subplots()
# # 数据是一个0~2π内的正弦曲线:
# x = np.arange(0, 2*np.pi, 0.01)
# line, = ax.plot(x, np.sin(x))
# # 构造自定义动画函数animate,用来更新每一帧上各个x对应的y坐标值,参数表示第i帧:
# def animate(i):
#     line.set_ydata(np.sin(x + i/10.0))
#     return line,
# # 然后,构造开始帧函数init:
# def init():
#     line.set_ydata(np.sin(x))
#     return line,
#
# #接下来,我们调用FuncAnimation函数生成动画。参数说明:
#
# # 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=True)
#
# plt.show()
# # 当然,你也可以将动画以mp4格式保存下来,
# # 但首先要保证你已经安装了ffmpeg 或者mencoder, 更多信息参考matplotlib animation api:
# # ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
# </editor-fold>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值