美文网首页
Chapter 2 Getting Started with M

Chapter 2 Getting Started with M

作者: 小桥流水啦啦啦 | 来源:发表于2019-10-21 22:39 被阅读0次

    内容摘要:
    1、探索Matplotlib针对单条或duotiao直线的基本绘图能力。
    2、添加信息,诸如说明、轴标签及标题。
    3、保存图片到文件。
    4、描述与IPython的交互。
    5、通过配置文件及Python代码定制Matplotlib。

    采用Matplotlib绘制的第一幅图
    S C:\Users\guyuling> ipython
    Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)]
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.7.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: import matplotlib.pyplot as plt
    
    In [2]: plt.plot([1,3,2,4])
    Out[2]: [<matplotlib.lines.Line2D at 0x1df5bd0ac50>]
    
    In [3]: plt.show()
    
    实际上是1、3、2、4垂直坐标点绘直线。
    image.png
    In [1]: import matplotlib.pyplot as plt
    
    In [2]: x=range(6)
    
    In [3]: plt.plot(x,[xi**2 for xi in x])
    Out[3]: [<matplotlib.lines.Line2D at 0x197324e62b0>]
    
    In [4]: plt.show()
    
    image.png
    In [5]: import matplotlib.pyplot as plt
    
    In [6]: import numpy as np
    
    In [7]: x = np.arange(0.0,6.0,0.01)
    
    In [8]: plt.plot(x,[x**2 for x in x])
    Out[8]: [<matplotlib.lines.Line2D at 0x19738826cf8>]
    
    In [9]: plt.show()
    
    image.png
    多线图
    In [10]: import matplotlib.pyplot as plt
    
    In [11]: x=range(1,5)
    
    In [12]: plt.plot(x,[xi*1.5 for xi in x])
    Out[12]: [<matplotlib.lines.Line2D at 0x1973886b0b8>]
    
    In [13]:  plt.plot(x,[xi*3.0 for xi in x])
    Out[13]: [<matplotlib.lines.Line2D at 0x19738855e80>]
    
    In [14]: plt.plot(x,[xi/3.0 for xi in x])
    Out[14]: [<matplotlib.lines.Line2D at 0x197389c8ba8>]
    
    In [15]: plt.show()
    
    image.png
    大致介绍下NumPy数组
    网格、轴和标签
    添加网格

    plt.grid(True)

    对轴进行处理

    plt.axis() #显示当前轴限制值
    plt.axis([0,5,-1,13]) #设置新的轴限制

    添加轴标签

    plt.xlabel('This is the X axis')
    plt.ylabel('This is the Y axis')

    标题和后端
    一个完整的例子
    In [1]: import matplotlib.pyplot as plt
    
    In [2]: import numpy as np
    
    In [3]: x=np.arange(1,5)
    
    In [4]: plt.plot(x,x*1.5,label='Normal')
    Out[4]: [<matplotlib.lines.Line2D at 0x1addaa1abe0>]
    
    In [5]: plt.plot(x,x*3.0,label='Fast')
    Out[5]: [<matplotlib.lines.Line2D at 0x1addaa65358>]
    
    In [6]: plt.plot(x,x/3.0,label='Slow')
    Out[6]: [<matplotlib.lines.Line2D at 0x1addaa79dd8>]
    
    In [7]: plt.grid(True)
    
    In [8]: plt.title('Sample Growth of a Measure')
    Out[8]: Text(0.5, 1.0, 'Sample Growth of a Measure')
    
    In [9]: plt.xlabel('Samples')
    Out[9]: Text(0.5, 0, 'Samples')
    
    In [10]: plt.ylabel('Values Measured')
    Out[10]: Text(0, 0.5, 'Values Measured')
    
    In [11]: plt.legend(loc='upper left')
    Out[11]: <matplotlib.legend.Legend at 0x1addaaab320>
    
    In [12]: plt.show()
    
    image.png
    保存图片到文件中

    In [1]: import matplotlib.pyplot as plt

    In [2]: plt.plot([1,2,3])
    Out[16]: [<matplotlib.lines.Line2D at 0x1addf31df28>]

    In [3]: plt.savefig('plot123.png')

    交互式导航工具栏
    IPython支持
    ipython -pylab
    plot([1,3,2,4])
    
    控制交互模式
    In [7]: import matplotlib as mpl
    
    In [8]: mpl.rcParams['interactive']
    Out[8]: False
    
    In [9]: mpl.interactive(True)
    
    In [10]: mpl.rcParams['interactive']
    Out[10]: True
    
    禁止函数输出
    In [21]: import matplotlib.pyplot as plt
    
    In [22]: plt.plot([1,2])
    Out[22]: [<matplotlib.lines.Line2D at 0x20e74b402b0>]
    
    In [23]: plt.plot([2,1])
    Out[23]: [<matplotlib.lines.Line2D at 0x20e79623d68>]
    
    配置Matplotlib
    * Global machine configuration file

    linux系统总机器配置文件在/etc/matplotlibrc

    * User configure file

    linux系统用户配置文件在$HOME/.matplotlib/matplotlibrc.
    windows系统用户配置文件在C:\Documents and Settings\yourname.matplotlib(无总配置文件)

    * Configure file in the current directory
    * Python code in the current script or program or interactive session

    Matplotlib有一组默认配置参数,可以按下面顺序定制:

    >>>python编码的Matplotlib函数
    >>>当前路径下的matplotlibrc文件
    >>>用户matplotlibrc文件
    >>>总的matplotlibrc文件
    配置文件
    backend : TkAgg
    image.png
    通过python代码来配置
    In [29]: import matplotlib as mpl
    
    In [30]: mpl.rcParams
    Out[30]: c:\python36\lib\site-packages\IPython\lib\pretty.py:697: MatplotlibDeprecationWarning:
    The examples.directory rcparam was deprecated in Matplotlib 3.0 and will be removed in 3.2. In the future, examples will be found relative to the 'datapath' directory.
      output = repr(obj)
    
    RcParams({'_internal.classic_mode': False,
              'agg.path.chunksize': 0,
              'animation.avconv_args': [],
              'animation.avconv_path': 'avconv',
              'animation.bitrate': -1,
              'animation.codec': 'h264',
              'animation.convert_args': [],
              'animation.convert_path': 'convert',
              'animation.embed_limit': 20.0,
              'animation.ffmpeg_args': [],
              'animation.ffmpeg_path': 'ffmpeg',
              'animation.frame_format': 'png',
              'animation.html': 'none',
              'animation.html_args': [],
              'animation.writer': 'ffmpeg',
              'axes.autolimit_mode': 'data',
              'axes.axisbelow': 'line',
              'axes.edgecolor': 'black',
              'axes.facecolor': 'white',
              'axes.formatter.limits': [-7, 7],
              'axes.formatter.min_exponent': 0,
              'axes.formatter.offset_threshold': 4,
              'axes.formatter.use_locale': False,
              'axes.formatter.use_mathtext': False,
              'axes.formatter.useoffset': True,
              'axes.grid': False,
              'axes.grid.axis': 'both',
              'axes.grid.which': 'major',
              'axes.labelcolor': 'black',
              'axes.labelpad': 4.0,
              'axes.labelsize': 'medium',
              'axes.labelweight': 'normal',
              'axes.linewidth': 0.8,
              'axes.prop_cycle': cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']),
              'axes.spines.bottom': True,
              'axes.spines.left': True,
              'axes.spines.right': True,
              'axes.spines.top': True,
              'axes.titlepad': 6.0,
              'axes.titlesize': 'large',
              'axes.titleweight': 'normal',
              'axes.unicode_minus': True,
              'axes.xmargin': 0.05,
              'axes.ymargin': 0.05,
              'axes3d.grid': True,
              'backend': 'TkAgg',
              'backend_fallback': True,
              'boxplot.bootstrap': None,
              'boxplot.boxprops.color': 'black',
              'boxplot.boxprops.linestyle': '-',
              'boxplot.boxprops.linewidth': 1.0,
              'boxplot.capprops.color': 'black',
              'boxplot.capprops.linestyle': '-',
              'boxplot.capprops.linewidth': 1.0,
              'boxplot.flierprops.color': 'black',
              'boxplot.flierprops.linestyle': 'none',
              'boxplot.flierprops.linewidth': 1.0,
              'boxplot.flierprops.marker': 'o',
              'boxplot.flierprops.markeredgecolor': 'black',
              'boxplot.flierprops.markeredgewidth': 1.0,
              'boxplot.flierprops.markerfacecolor': 'none',
              'boxplot.flierprops.markersize': 6.0,
              'boxplot.meanline': False,
              'boxplot.meanprops.color': 'C2',
              'boxplot.meanprops.linestyle': '--',
              'boxplot.meanprops.linewidth': 1.0,
              'boxplot.meanprops.marker': '^',
              'boxplot.meanprops.markeredgecolor': 'C2',
              'boxplot.meanprops.markerfacecolor': 'C2',
              'boxplot.meanprops.markersize': 6.0,
              'boxplot.medianprops.color': 'C1',
              'boxplot.medianprops.linestyle': '-',
              'boxplot.medianprops.linewidth': 1.0,
              'boxplot.notch': False,
              'boxplot.patchartist': False,
              'boxplot.showbox': True,
              'boxplot.showcaps': True,
              'boxplot.showfliers': True,
              'boxplot.showmeans': False,
              'boxplot.vertical': True,
              'boxplot.whiskerprops.color': 'black',
              'boxplot.whiskerprops.linestyle': '-',
              'boxplot.whiskerprops.linewidth': 1.0,
              'boxplot.whiskers': 1.5,
              'contour.corner_mask': True,
              'contour.negative_linestyle': 'dashed',
              'datapath': 'c:\\python36\\lib\\site-packages\\matplotlib\\mpl-data',
              'date.autoformatter.day': '%Y-%m-%d',
              'date.autoformatter.hour': '%m-%d %H',
              'date.autoformatter.microsecond': '%M:%S.%f',
              'date.autoformatter.minute': '%d %H:%M',
              'date.autoformatter.month': '%Y-%m',
              'date.autoformatter.second': '%H:%M:%S',
              'date.autoformatter.year': '%Y',
              'docstring.hardcopy': False,
              'errorbar.capsize': 0.0,
              'examples.directory': '',
              'figure.autolayout': False,
              'figure.constrained_layout.h_pad': 0.04167,
              'figure.constrained_layout.hspace': 0.02,
              'figure.constrained_layout.use': False,
              'figure.constrained_layout.w_pad': 0.04167,
              'figure.constrained_layout.wspace': 0.02,
              'figure.dpi': 100.0,
              'figure.edgecolor': 'white',
              'figure.facecolor': 'white',
              'figure.figsize': [6.4, 4.8],
              'figure.frameon': True,
              'figure.max_open_warning': 20,
              'figure.subplot.bottom': 0.11,
              'figure.subplot.hspace': 0.2,
              'figure.subplot.left': 0.125,
              'figure.subplot.right': 0.9,
              'figure.subplot.top': 0.88,
              'figure.subplot.wspace': 0.2,
              'figure.titlesize': 'large',
              'figure.titleweight': 'normal',
              'font.cursive': ['Apple Chancery',
                               'Textile',
                               'Zapf Chancery',
                               'Sand',
                               'Script MT',
                               'Felipa',
                               'cursive'],
              'font.family': ['sans-serif'],
              'font.fantasy': ['Comic Sans MS',
                               'Chicago',
                               'Charcoal',
                               'Impact',
                               'Western',
                               'Humor Sans',
                               'xkcd',
                               'fantasy'],
              'font.monospace': ['DejaVu Sans Mono',
                                 'Bitstream Vera Sans Mono',
                                 'Computer Modern Typewriter',
                                 'Andale Mono',
                                 'Nimbus Mono L',
                                 'Courier New',
                                 'Courier',
                                 'Fixed',
                                 'Terminal',
                                 'monospace'],
              'font.sans-serif': ['DejaVu Sans',
                                  'Bitstream Vera Sans',
                                  'Computer Modern Sans Serif',
                                  'Lucida Grande',
                                  'Verdana',
                                  'Geneva',
                                  'Lucid',
                                  'Arial',
                                  'Helvetica',
                                  'Avant Garde',
                                  'sans-serif'],
              'font.serif': ['DejaVu Serif',
                             'Bitstream Vera Serif',
                             'Computer Modern Roman',
                             'New Century Schoolbook',
                             'Century Schoolbook L',
                             'Utopia',
                             'ITC Bookman',
                             'Bookman',
                             'Nimbus Roman No9 L',
                             'Times New Roman',
                             'Times',
                             'Palatino',
                             'Charter',
                             'serif'],
              'font.size': 10.0,
              'font.stretch': 'normal',
              'font.style': 'normal',
              'font.variant': 'normal',
              'font.weight': 'normal',
              'grid.alpha': 1.0,
              'grid.color': '#b0b0b0',
              'grid.linestyle': '-',
              'grid.linewidth': 0.8,
              'hatch.color': 'black',
              'hatch.linewidth': 1.0,
              'hist.bins': 10,
              'image.aspect': 'equal',
              'image.cmap': 'viridis',
              'image.composite_image': True,
              'image.interpolation': 'nearest',
              'image.lut': 256,
              'image.origin': 'upper',
              'image.resample': True,
              'interactive': True,
              'keymap.all_axes': ['a'],
              'keymap.back': ['left', 'c', 'backspace', 'MouseButton.BACK'],
              'keymap.copy': ['ctrl+c', 'cmd+c'],
              'keymap.forward': ['right', 'v', 'MouseButton.FORWARD'],
              'keymap.fullscreen': ['f', 'ctrl+f'],
              'keymap.grid': ['g'],
              'keymap.grid_minor': ['G'],
              'keymap.help': ['f1'],
              'keymap.home': ['h', 'r', 'home'],
              'keymap.pan': ['p'],
              'keymap.quit': ['ctrl+w', 'cmd+w', 'q'],
              'keymap.quit_all': ['W', 'cmd+W', 'Q'],
              'keymap.save': ['s', 'ctrl+s'],
              'keymap.xscale': ['k', 'L'],
              'keymap.yscale': ['l'],
              'keymap.zoom': ['o'],
              'legend.borderaxespad': 0.5,
              'legend.borderpad': 0.4,
              'legend.columnspacing': 2.0,
              'legend.edgecolor': '0.8',
              'legend.facecolor': 'inherit',
              'legend.fancybox': True,
              'legend.fontsize': 'medium',
              'legend.framealpha': 0.8,
              'legend.frameon': True,
              'legend.handleheight': 0.7,
              'legend.handlelength': 2.0,
              'legend.handletextpad': 0.8,
              'legend.labelspacing': 0.5,
              'legend.loc': 'best',
              'legend.markerscale': 1.0,
              'legend.numpoints': 1,
              'legend.scatterpoints': 1,
              'legend.shadow': False,
              'legend.title_fontsize': None,
              'lines.antialiased': True,
              'lines.color': 'C0',
              'lines.dash_capstyle': 'butt',
              'lines.dash_joinstyle': 'round',
              'lines.dashdot_pattern': [6.4, 1.6, 1.0, 1.6],
              'lines.dashed_pattern': [3.7, 1.6],
              'lines.dotted_pattern': [1.0, 1.65],
              'lines.linestyle': '-',
              'lines.linewidth': 1.5,
              'lines.marker': 'None',
              'lines.markeredgecolor': 'auto',
              'lines.markeredgewidth': 1.0,
              'lines.markerfacecolor': 'auto',
              'lines.markersize': 6.0,
              'lines.scale_dashes': True,
              'lines.solid_capstyle': 'projecting',
              'lines.solid_joinstyle': 'round',
              'markers.fillstyle': 'full',
              'mathtext.bf': 'sans:bold',
              'mathtext.cal': 'cursive',
              'mathtext.default': 'it',
              'mathtext.fallback_to_cm': True,
              'mathtext.fontset': 'dejavusans',
              'mathtext.it': 'sans:italic',
              'mathtext.rm': 'sans',
              'mathtext.sf': 'sans',
              'mathtext.tt': 'monospace',
              'patch.antialiased': True,
              'patch.edgecolor': 'black',
              'patch.facecolor': 'C0',
              'patch.force_edgecolor': False,
              'patch.linewidth': 1.0,
              'path.effects': [],
              'path.simplify': True,
              'path.simplify_threshold': 0.1111111111111111,
              'path.sketch': None,
              'path.snap': True,
              'pdf.compression': 6,
              'pdf.fonttype': 3,
              'pdf.inheritcolor': False,
              'pdf.use14corefonts': False,
              'pgf.preamble': '',
              'pgf.rcfonts': True,
              'pgf.texsystem': 'xelatex',
              'polaraxes.grid': True,
              'ps.distiller.res': 6000,
              'ps.fonttype': 3,
              'ps.papersize': 'letter',
              'ps.useafm': False,
              'ps.usedistiller': False,
              'savefig.bbox': None,
              'savefig.directory': '~',
              'savefig.dpi': 'figure',
              'savefig.edgecolor': 'white',
              'savefig.facecolor': 'white',
              'savefig.format': 'png',
              'savefig.frameon': True,
              'savefig.jpeg_quality': 95,
              'savefig.orientation': 'portrait',
              'savefig.pad_inches': 0.1,
              'savefig.transparent': False,
              'scatter.edgecolors': 'face',
              'scatter.marker': 'o',
              'svg.fonttype': 'path',
              'svg.hashsalt': None,
              'svg.image_inline': True,
              'text.antialiased': True,
              'text.color': 'black',
              'text.hinting': 'auto',
              'text.hinting_factor': 8,
              'text.latex.preamble': '',
              'text.latex.preview': False,
              'text.latex.unicode': True,
              'text.usetex': False,
              'timezone': 'UTC',
              'tk.window_focus': False,
              'toolbar': 'toolbar2',
              'verbose.fileo': 'sys.stdout',
              'verbose.level': 'silent',
              'webagg.address': '127.0.0.1',
              'webagg.open_in_browser': True,
              'webagg.port': 8988,
              'webagg.port_retries': 50,
              'xtick.alignment': 'center',
              'xtick.bottom': True,
              'xtick.color': 'black',
              'xtick.direction': 'out',
              'xtick.labelbottom': True,
              'xtick.labelsize': 'medium',
              'xtick.labeltop': False,
              'xtick.major.bottom': True,
              'xtick.major.pad': 3.5,
              'xtick.major.size': 3.5,
              'xtick.major.top': True,
              'xtick.major.width': 0.8,
              'xtick.minor.bottom': True,
              'xtick.minor.pad': 3.4,
              'xtick.minor.size': 2.0,
              'xtick.minor.top': True,
              'xtick.minor.visible': False,
              'xtick.minor.width': 0.6,
              'xtick.top': False,
              'ytick.alignment': 'center_baseline',
              'ytick.color': 'black',
              'ytick.direction': 'out',
              'ytick.labelleft': True,
              'ytick.labelright': False,
              'ytick.labelsize': 'medium',
              'ytick.left': True,
              'ytick.major.left': True,
              'ytick.major.pad': 3.5,
              'ytick.major.right': True,
              'ytick.major.size': 3.5,
              'ytick.major.width': 0.8,
              'ytick.minor.left': True,
              'ytick.minor.pad': 3.4,
              'ytick.minor.right': True,
              'ytick.minor.size': 2.0,
              'ytick.minor.visible': False,
              'ytick.minor.width': 0.6,
              'ytick.right': False})
    

    直接采用代码修改字典:

    mpl.rcParams['<param name>'] = <value>
    
    matplotlib.rcdefaults(): 恢复Matplotlib的默认配置参数值
    matplotlib.rc():           在单条命令中设置多条设置
    

    例如:
    mpl.rc(('figure','savefig'),facecolor='r')
    等价于:
    mpl.rcParam['figure.facecolor'] = 'r'
    mpl.rcParam['savefig.facecolor'] = 'r'

    mpl.rc('line',linewidth=4,linecolor='b')
    等价于:
    mpl.rcParam['line.linewidth'] = 4
    mpl.rcParam['line.linecolor'] = 'b'

    Select backend from code
    In [31]: import matplotlib as mpl
    
    In [32]: mpl.use('TkAgg')
    
    总结
    1、如何创建单个或多个图处理轴限制
    2、如何添加信息到图中,比如后端,标签和标题
    3、如何保存图到文件中来使用
    4、如何使用交互式window提供的工具栏
    5、为什么IPython对于Matplotlib而言在实验室种这么重要
    6、如何根据你的需要定制Matplotlib(要么从配置文件中或者从Python代码中)

    相关文章

      网友评论

          本文标题:Chapter 2 Getting Started with M

          本文链接:https://www.haomeiwen.com/subject/xxwxvctx.html