Matplotlib基础知识
设置plot的风格和样式
其他2D图形
图形内的文字、注释、箭头
高阶Matplotlib
3D图
文字的属性、中文字体、LaTeX
绘制图片
后端设置
Further reading
import matplotlib as mpl
import matplotlib.pyplot as plt
from numpy.random import randn
import numpy as np
import pandas as pd
from IPython.display import Image
# This line configures matplotlib to show figures embedded in the notebook, instead of opening a new window for each figure.
%matplotlib inline
Matplotlib中的基本图表包括的元素
水平和垂直的轴线
刻度标示坐标轴的分隔,包括最小刻度和最大刻度
表示特定坐标轴的值
实际绘图的区域
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.grid(True)
plt.title('Sample Growth of a Measure')
plt.xlabel('Samples')
plt.ylabel('Values Measured')
plt.legend(loc='upper left')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 6.0, 0.01)
plt.plot(x, x**2)
plt.show()
import matplotlib.pyplot as plt
x = np.arange(1, 5)
plt.plot(x, x*1.5)
plt.plot(x, x*3.0)
plt.plot(x, x/3.0)
plt.show()
# 也可以在一个plot函数中传入多对X,Y值,在一个图中绘制多个曲线
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
plt.show()
hold属性默认为True,允许在一幅图中绘制多个曲线;将hold属性修改为False,每一个plot都会覆盖前面的plot
import matplotlib.pyplot as plt
plt.interactive(True)# enable interactive mode, in case it was not
plt.hold(False) # empty window will pop up
plt.plot([1, 2, 3])
plt.plot([2, 4, 6])
[<matplotlib.lines.Line2D at 0x9dd9978>]
plt.hold(True) # 将hold属性改回True
grid方法
# 使用grid方法为图添加网格线
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
plt.grid(True)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10,3))
x = np.linspace(0, 5, 100)
# default grid appearance
ax1 = fig.add_subplot(121)
ax1.plot(x, x**2, x, x**3, lw=2)
ax1.grid(True) # 显式网格线
# 对网格线进行设置
ax2 = fig.add_subplot(122)
ax2.plot(x, x**2, x, x**3, lw=2)
ax2.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5) # 用与plot同样的参数设置网格线
plt.grid(b=True, which='major', axis='both')
# which指定绘制的网格刻度类型(major、minor或者both)
# axis指定绘制哪组网格线(both、x或者y)
plt.axis([-1, 1, -10, 10])
plt.axhline(); # 添加水平线,重要参数包括:y轴位置、xmin、xmax,默认在y=0位置绘制水平线
plt.axis([-1, 1, -10, 10])
plt.axvline(0.5, 0.2, 0.8); # 添加垂直线,重要参数包括:x轴位置、ymin、ymax,默认在x=0位置绘制水平线(ymin、ymax都是比例值)
plt.axis([-1, 1, -10, 10])
plt.axhspan(-5, 2); # 绘制一条水平带(矩形),需要ymin、ymax参数指定水平带的宽度(ymin、ymax都是实际值)
plt.axis([-2, 2, -10, 10])
plt.axvspan(-1, 1); # 绘制一条垂直带(矩形),需要xmin、xmax参数指定水平带的宽度(xmin、xmax都是实际值)
如果axis方法没有任何参数,则返回当前坐标轴的上下限
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
plt.axis() # shows the current axis limits values;如果axis方法没有任何参数,则返回当前坐标轴的上下限
# (1.0, 4.0, 0.0, 12.0)
plt.axis([0, 5, -1, 13]) # set new axes limits;axis方法中有参数,设置坐标轴的上下限;参数顺序为[xmin, xmax, ymin, ymax]
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
plt.axis('tight') # 紧凑型坐标轴
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
plt.xlim([0, 5]) # ylim([ymin, ymax])
plt.ylim([-1, 13]) # xlim([xmin, xmax])
plt.show()
xlabel方法和ylabel方法
import matplotlib.pyplot as plt
plt.plot([1, 3, 2, 4])
plt.xlabel('This is the X axis')
plt.ylabel('This is the Y axis')
plt.show()
title方法
import matplotlib.pyplot as plt
plt.plot([1, 3, 2, 4])
plt.title('Simple plot')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal') # 在plot函数中增加label参数
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5)
plt.plot(x, x*3.0)
plt.plot(x, x/3.0)
plt.legend(['Normal', 'Fast', 'Slow']) # 在legend方法中传入字符串列表
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='_nolegend_') # label参数为'_nolegend_',则图例中不显示
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend()
plt.show()
字符串 | 数值 | 字符串 | 数值 |
---|---|---|---|
best | 0 | center left | 6 |
upper right | 1 | center right | 7 |
upper left | 2 | lower center | 8 |
lower left | 3 | upper center | 9 |
lower right | 4 | center | 10 |
right | 5 |
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend(loc=0)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend(loc=(0,1)) # loc参数可以是2元素的元组,表示图例左下角的坐标
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend(loc=(-0.1,0.9)) # 图例也可以超过图的界限
plt.show()
import matplotlib.pyplot as plt
import numpy as np
plt.plot(randn(1000).cumsum(), 'k', label='one') # 在添加subplot时传入label参数
plt.plot(randn(1000).cumsum(), 'k--', label='two') # 要从图例中去除一个或多个元素,不传入label或传入label='_nolegend_'即可
plt.plot(randn(1000).cumsum(), 'k.', label='three')
plt.legend(loc='best') # loc='best'
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend(loc=0, ncol=2) # ncol控制图例中有几列
plt.show()
figure.savefig的选项
含有文件路径的字符串或Python的文件型对象。图像格式由文件扩展名推断得出,例如,.pdf推断出PDF,.png推断出PNG
图像分辨率(每英寸点数),默认为100
图像的背景色,默认为“w”(白色)
显式设置文件格式(“png”、“pdf”、“svg”、“ps”、“eps”……)
图表需要保存的部分。如果设置为“tight”,则将尝试剪除图表周围的空白部分
Matplotlib can generate high-quality output in a number formats, including PNG, JPG, EPS, SVG, PGF and PDF.
For scientific papers, I recommend using PDF whenever possible. (LaTeX documents compiled with pdflatex
can include PDFs using the includegraphics
command). In some cases, PGF can also be good alternative.
# 查看matplotlib中的默认设置
import matplotlib as mpl
mpl.rcParams['figure.figsize'] # figsize以英尺为单位,matplotlib中其他参数都以点为单位
[6.0, 4.0]
mpl.rcParams['savefig.dpi']
72.0
If we are in interactive mode, then the figure is redrawn on every plot command. If we are not in interactive mode, a figure state is updated on every plot command, but the figure is actually drawn only when an explicit call to draw() or show() is made.
matplotlib配置信息是从配置文件读取的。在配置文件中可以为matplotlib的几乎所有属性指定永久有效的默认值
在Windows系统中,没有全局配置文件,用户配置文件的位置在C:\Documents and Settings\yourname\.matplotlib。
在Linux系统中,全局配置文件的位置在/etc/matplotlibrc,用户配置文件的位置在$HOME/.matplotlib/matplotlibrc。
配置方法的优先级为:
通过rcParams字典访问并修改所有已经加载的配置项
# 显示当前的默认配置
import matplotlib as mpl
mpl.rcParams
RcParams({u'agg.path.chunksize': 0, u'animation.avconv_args': [], u'animation.avconv_path': u'avconv', u'animation.bitrate': -1, u'animation.codec': u'mpeg4', u'animation.convert_args': [], u'animation.convert_path': u'convert', u'animation.ffmpeg_args': [], u'animation.ffmpeg_path': u'ffmpeg', u'animation.frame_format': u'png', u'animation.html': u'none', u'animation.mencoder_args': [], u'animation.mencoder_path': u'mencoder', u'animation.writer': u'ffmpeg', u'axes.axisbelow': False, u'axes.edgecolor': u'k', u'axes.facecolor': u'w', u'axes.formatter.limits': [-7, 7], u'axes.formatter.use_locale': False, u'axes.formatter.use_mathtext': False, u'axes.formatter.useoffset': True, u'axes.grid': False, u'axes.grid.axis': u'both', u'axes.grid.which': u'major', u'axes.hold': True, u'axes.labelcolor': u'k', u'axes.labelpad': 5.0, u'axes.labelsize': u'medium', u'axes.labelweight': u'normal', u'axes.linewidth': 1.0, u'axes.prop_cycle': cycler(u'color', [u'b', u'g', u'r', u'c', u'm', u'y', u'k']), u'axes.spines.bottom': True, u'axes.spines.left': True, u'axes.spines.right': True, u'axes.spines.top': True, u'axes.titlesize': u'large', u'axes.titleweight': u'normal', u'axes.unicode_minus': True, u'axes.xmargin': 0.0, u'axes.ymargin': 0.0, u'axes3d.grid': True, u'backend': 'module://ipykernel.pylab.backend_inline', u'backend.qt4': u'PyQt4', u'backend.qt5': u'PyQt5', u'backend_fallback': True, u'boxplot.bootstrap': None, u'boxplot.boxprops.color': u'b', u'boxplot.boxprops.linestyle': u'-', u'boxplot.boxprops.linewidth': 1.0, u'boxplot.capprops.color': u'k', u'boxplot.capprops.linestyle': u'-', u'boxplot.capprops.linewidth': 1.0, u'boxplot.flierprops.color': u'b', u'boxplot.flierprops.linestyle': u'none', u'boxplot.flierprops.linewidth': 1.0, u'boxplot.flierprops.marker': u'+', u'boxplot.flierprops.markeredgecolor': u'k', u'boxplot.flierprops.markerfacecolor': u'b', u'boxplot.flierprops.markersize': 6.0, u'boxplot.meanline': False, u'boxplot.meanprops.color': u'r', u'boxplot.meanprops.linestyle': u'-', u'boxplot.meanprops.linewidth': 1.0, u'boxplot.medianprops.color': u'r', u'boxplot.medianprops.linestyle': u'-', u'boxplot.medianprops.linewidth': 1.0, u'boxplot.notch': False, u'boxplot.patchartist': False, u'boxplot.showbox': True, u'boxplot.showcaps': True, u'boxplot.showfliers': True, u'boxplot.showmeans': False, u'boxplot.vertical': True, u'boxplot.whiskerprops.color': u'b', u'boxplot.whiskerprops.linestyle': u'--', u'boxplot.whiskerprops.linewidth': 1.0, u'boxplot.whiskers': 1.5, u'contour.corner_mask': True, u'contour.negative_linestyle': u'dashed', u'datapath': u'C:\\Anaconda2\\lib\\site-packages\\matplotlib\\mpl-data', u'docstring.hardcopy': False, u'errorbar.capsize': 3.0, u'examples.directory': u'', u'figure.autolayout': False, u'figure.dpi': 80.0, u'figure.edgecolor': (1, 1, 1, 0), u'figure.facecolor': (1, 1, 1, 0), u'figure.figsize': [6.0, 4.0], u'figure.frameon': True, u'figure.max_open_warning': 20, u'figure.subplot.bottom': 0.125, u'figure.subplot.hspace': 0.2, u'figure.subplot.left': 0.125, u'figure.subplot.right': 0.9, u'figure.subplot.top': 0.9, u'figure.subplot.wspace': 0.2, u'figure.titlesize': u'medium', u'figure.titleweight': u'normal', u'font.cursive': [u'Apple Chancery', u'Textile', u'Zapf Chancery', u'Sand', u'Script MT', u'Felipa', u'cursive'], u'font.family': [u'sans-serif'], u'font.fantasy': [u'Comic Sans MS', u'Chicago', u'Charcoal', u'ImpactWestern', u'Humor Sans', u'fantasy'], u'font.monospace': [u'Bitstream Vera Sans Mono', u'DejaVu Sans Mono', u'Andale Mono', u'Nimbus Mono L', u'Courier New', u'Courier', u'Fixed', u'Terminal', u'monospace'], u'font.sans-serif': [u'Bitstream Vera Sans', u'DejaVu Sans', u'Lucida Grande', u'Verdana', u'Geneva', u'Lucid', u'Arial', u'Helvetica', u'Avant Garde', u'sans-serif'], u'font.serif': [u'Bitstream Vera Serif', u'DejaVu Serif', u'New Century Schoolbook', u'Century Schoolbook L', u'Utopia', u'ITC Bookman', u'Bookman', u'Nimbus Roman No9 L', u'Times New Roman', u'Times', u'Palatino', u'Charter', u'serif'], u'font.size': 10.0, u'font.stretch': u'normal', u'font.style': u'normal', u'font.variant': u'normal', u'font.weight': u'normal', u'grid.alpha': 1.0, u'grid.color': u'k', u'grid.linestyle': u':', u'grid.linewidth': 0.5, u'image.aspect': u'equal', u'image.cmap': u'jet', u'image.composite_image': True, u'image.interpolation': u'bilinear', u'image.lut': 256, u'image.origin': u'upper', u'image.resample': False, u'interactive': True, u'keymap.all_axes': [u'a'], u'keymap.back': [u'left', u'c', u'backspace'], u'keymap.forward': [u'right', u'v'], u'keymap.fullscreen': [u'f', u'ctrl+f'], u'keymap.grid': [u'g'], u'keymap.home': [u'h', u'r', u'home'], u'keymap.pan': [u'p'], u'keymap.quit': [u'ctrl+w', u'cmd+w'], u'keymap.save': [u's', u'ctrl+s'], u'keymap.xscale': [u'k', u'L'], u'keymap.yscale': [u'l'], u'keymap.zoom': [u'o'], u'legend.borderaxespad': 0.5, u'legend.borderpad': 0.4, u'legend.columnspacing': 2.0, u'legend.edgecolor': u'inherit', u'legend.facecolor': u'inherit', u'legend.fancybox': False, u'legend.fontsize': u'large', u'legend.framealpha': None, u'legend.frameon': True, u'legend.handleheight': 0.7, u'legend.handlelength': 2.0, u'legend.handletextpad': 0.8, u'legend.isaxes': True, u'legend.labelspacing': 0.5, u'legend.loc': u'upper right', u'legend.markerscale': 1.0, u'legend.numpoints': 2, u'legend.scatterpoints': 3, u'legend.shadow': False, u'lines.antialiased': True, u'lines.color': u'b', u'lines.dash_capstyle': u'butt', u'lines.dash_joinstyle': u'round', u'lines.linestyle': u'-', u'lines.linewidth': 1.0, u'lines.marker': u'None', u'lines.markeredgewidth': 0.5, u'lines.markersize': 6.0, u'lines.solid_capstyle': u'projecting', u'lines.solid_joinstyle': u'round', u'markers.fillstyle': u'full', u'mathtext.bf': u'serif:bold', u'mathtext.cal': u'cursive', u'mathtext.default': u'it', u'mathtext.fallback_to_cm': True, u'mathtext.fontset': u'cm', u'mathtext.it': u'serif:italic', u'mathtext.rm': u'serif', u'mathtext.sf': u'sans\\-serif', u'mathtext.tt': u'monospace', u'nbagg.transparent': True, u'patch.antialiased': True, u'patch.edgecolor': u'k', u'patch.facecolor': u'b', u'patch.linewidth': 1.0, u'path.effects': [], u'path.simplify': True, u'path.simplify_threshold': 0.1111111111111111, u'path.sketch': None, u'path.snap': True, u'pdf.compression': 6, u'pdf.fonttype': 3, u'pdf.inheritcolor': False, u'pdf.use14corefonts': False, u'pgf.debug': False, u'pgf.preamble': [], u'pgf.rcfonts': True, u'pgf.texsystem': u'xelatex', u'plugins.directory': u'.matplotlib_plugins', u'polaraxes.grid': True, u'ps.distiller.res': 6000, u'ps.fonttype': 3, u'ps.papersize': u'letter', u'ps.useafm': False, u'ps.usedistiller': False, u'savefig.bbox': None, u'savefig.directory': u'~', u'savefig.dpi': 72.0, u'savefig.edgecolor': u'w', u'savefig.facecolor': u'w', u'savefig.format': u'png', u'savefig.frameon': True, u'savefig.jpeg_quality': 95, u'savefig.orientation': u'portrait', u'savefig.pad_inches': 0.1, u'savefig.transparent': False, u'svg.fonttype': u'path', u'svg.image_inline': True, u'svg.image_noscale': False, u'text.antialiased': True, u'text.color': u'k', u'text.dvipnghack': None, u'text.hinting': u'auto', u'text.hinting_factor': 8, u'text.latex.preamble': [], u'text.latex.preview': False, u'text.latex.unicode': False, u'text.usetex': False, u'timezone': u'UTC', u'tk.window_focus': False, u'toolbar': u'toolbar2', u'verbose.fileo': u'sys.stdout', u'verbose.level': u'silent', u'webagg.open_in_browser': True, u'webagg.port': 8988, u'webagg.port_retries': 50, u'xtick.color': u'k', u'xtick.direction': u'in', u'xtick.labelsize': u'medium', u'xtick.major.pad': 4.0, u'xtick.major.size': 4.0, u'xtick.major.width': 0.5, u'xtick.minor.pad': 4.0, u'xtick.minor.size': 2.0, u'xtick.minor.visible': False, u'xtick.minor.width': 0.5, u'ytick.color': u'k', u'ytick.direction': u'in', u'ytick.labelsize': u'medium', u'ytick.major.pad': 4.0, u'ytick.major.size': 4.0, u'ytick.major.width': 0.5, u'ytick.minor.pad': 4.0, u'ytick.minor.size': 2.0, u'ytick.minor.visible': False, u'ytick.minor.width': 0.5})
通过matplotlib.rc()传入属性的关键字元组,一条语句中修改多个配置项
matplotlib.rcsetup contains the default Matplotlib parameter values and some validation functions to prevent spurious values from being used in a setting.
重置所有配置
use方法
matplotlib.use()必须在首次import matplotlib后立即使用(在import pylab或pyplot之前)
plot语句中支持除X,Y以外的参数,以字符串形式存在,来控制颜色、线型、点型等要素,语法形式为:
plt.plot(X, Y, 'format', ...)
参数color或c
别名
合法的HTML颜色名
颜色 | 别名 | HTML颜色名 | 颜色 | 别名 | HTML颜色名 |
---|---|---|---|---|---|
蓝色 | b | blue | 绿色 | g | green |
红色 | r | red | 黄色 | y | yellow |
青色 | c | cyan | 黑色 | k | black |
洋红色 | m | magenta | 白色 | w | white |
HTML十六进制字符串
归一化到[0, 1]的RGB元组
灰度
# 别名和HTML颜色名
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, 'y'); # 后面加分号,则不打印plot对象
plt.plot(y+1, 'magenta'); # 没有x,则x默认为[0, 1]
plt.plot(y+2, 'cyan'); # 没有颜色参数时,plot为不同的曲线自动选择不同颜色,有颜色参数,则使用指定的颜色
plt.show()
# HTML颜色名和HTML十六进制字符串、归一化到[0, 1]的RGB元组
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, c="red", alpha=0.5); # 设置半透明
plt.plot(y+1, color="#1155dd"); # RGB hex code for a bluish color
plt.plot(y+2, color="#15cc55"); # RGB hex code for a greenish color
plt.plot(y+3, color=(0.1843, 0.3098, 0.3098)); # 归一化到[0, 1]的RGB元组
plt.show()
# 灰度
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, c="0.1");
plt.plot(y+1, c="0.5");
plt.plot(y+2, c="0.9");
alpha参数
# 透明度
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, c="red", alpha=0.1); # 设置透明度
plt.plot(y+1, c="red", alpha=0.5);
plt.plot(y+2, c="red", alpha=0.9);
设置背景色,通过向plt.axes()或者plt.subplot()方法传入axisbg参数,来设置坐标轴的背景色
import matplotlib.pyplot as plt
plt.subplot(111, axisbg=(0.1843, 0.3098, 0.3098));
参数linestyle或ls
线条风格 | 描述 | 线条风格 | 描述 |
---|---|---|---|
'-' | 实线 | ':' | 虚线 |
'--' | 破折线 | 'steps' | 阶梯线 |
'-.' | 点划线 | 'None',' ','' | 什么都不画 |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, '--', y+1, '-.', y+2, ':');
plt.show()
linewidth或lw参数
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, lw=1);
plt.plot(y+1, lw=2);
plt.plot(y+2, lw=3);
dashes参数
设置破折号序列各段的宽度,如果seq为空或者seq=[None, None],linestyle将被设置为solid
# 第一段线2个点的宽度,接下来的空白区5个点的宽度,第二段线5个点的宽度,空白区2个点的宽度,以此类推
plt.plot(np.linspace(-np.pi, np.pi, 256, endpoint=True), np.cos(np.linspace(-np.pi, np.pi, 256, endpoint=True)), dashes=[2, 5, 5, 2]);
marker参数
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'1' | 一角朝下的三脚架 | '3' | 一角朝左的三脚架 |
'2' | 一角朝上的三脚架 | '4' | 一角朝右的三脚架 |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3, 0.2)
plt.plot(y, '1', y+0.5, '2', y+1, '3', y+1.5, '4');
plt.show()
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'v' | 一角朝下的三角形 | '<' | 一角朝左的三角形 |
'^' | 一角朝上的三角形 | '>' | 一角朝右的三角形 |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3, 0.2)
plt.plot(y, 'v', y+0.5, '^', y+1, '<', y+1.5, '>');
plt.show()
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
's' | 正方形 | 'p' | 五边形 |
'h' | 六边形1 | 'H' | 六边形2 |
'8' | 八边形 |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3, 0.2)
plt.plot(y, 's', y+0.5, 'p', y+1, 'h', y+1.5, 'H', y+2, '8');
plt.show()
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'.' | 点 | 'x' | X |
'*' | 星号 | '+' | 加号 |
',' | 像素 |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3, 0.2)
plt.plot(y, '.', y+0.5, 'x', y+1, '*', y+1.5, '+', y+2, ',');
plt.show()
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'o' | 圆圈 | 'D' | 菱形 |
'd' | 小菱形 | '','None',' ',None | 无 |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3, 0.2)
plt.plot(y, 'o', y+0.5, 'D', y+1, 'd');
plt.plot(y+1.5, marker="None");
plt.show()
标记 | 描述 | 标记 | 描述 | |
---|---|---|---|---|
'_' | 水平线 | ' | ' | 竖线 |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3, 0.2)
plt.plot(y, '_', y+1, '|');
plt.show()
颜色、点型、线型
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 10)
plt.plot(x, x**2, 'b^:') # blue line with dots
plt.plot(x, x**3, 'go-.') # green dashed line
plt.show()
参数 | 描述 | 参数 | 描述 |
---|---|---|---|
color或c | 线的颜色 | linestyle或ls | 线型 |
linewidth或lw | 线宽 | marker | 点型 |
markeredgecolor | 点边缘的颜色 | markeredgewidth | 点边缘的宽度 |
markerfacecolor | 点内部的颜色 | markersize | 点的大小 |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3, 0.3)
plt.plot(y, color='blue', linestyle='dashdot', linewidth=4, marker='o', markerfacecolor='red', markeredgecolor='black', markeredgewidth=3, markersize=12);
plt.show()
plt.plot(x1, y1, x2, y2, fmt, ...)
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
x = np.arange(1, 3)
plt.plot(x, y, x, y+1, x, y+2, color='green'); # 为多个曲线设置同一颜色
plt.xlim([1, 2])
plt.show()
plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...)
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, 'y', y+1, 'm', y+2, 'c'); # 为多个曲线设置不同颜色
plt.show()
plt.plot(x, y, linewidth=1.5);
line, = plt.plot(x, y)
# plt.plot(x, y)返回的是list
# line = plt.plot(x, y),则line是list
# line, = plt.plot(x, y),则line是matplotlib.lines.Line2D实例,所以line后面有个逗号
line.set_linewidth(1.5)
line = plt.plot(x, y)
plt.setp(line, 'linewidth', 1.5);
xticks()和yticks()方法
locs, labels = plt.xticks() # 不传入任何参数,xticks()会返回当前刻度的位置和标签
print locs
for label in labels:
print label,
[ 0. 0.2 0.4 0.6 0.8 1. ] Text(0,0,u'0.0') Text(0.2,0,u'0.2') Text(0.4,0,u'0.4') Text(0.6,0,u'0.6') Text(0.8,0,u'0.8') Text(1,0,u'1.0')
import matplotlib.pyplot as plt
x = [5, 3, 7, 2, 4, 1]
plt.plot(x);
plt.xticks(range(len(x)), ['a', 'b', 'c', 'd', 'e', 'f']); # 传入位置和标签参数,以修改坐标轴刻度
plt.yticks(range(1, 8, 2));
plt.show()
set_xticks、set_yticks、set_xticklabels、set_yticklabels方法
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10, 4))
ax = fig.add_subplot(111)
x = np.linspace(0, 5, 100)
ax.plot(x, x**2, x, x**3, lw=2)
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_xticklabels([r'$\alpha$', r'$\beta$', r'$\gamma$', r'$\delta$', r'$\epsilon$'], fontsize=18)
yticks = [0, 50, 100, 150]
ax.set_yticks(yticks)
ax.set_yticklabels(["$%.1f$" % y for y in yticks], fontsize=18); # use LaTeX formatted labels
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10, 4))
ax = fig.add_subplot(111)
x = np.linspace(0, 5, 100)
ax.plot(x, x**2, x, np.exp(x))
ax.set_title("scientific notation")
ax.set_yticks([0, 50, 100, 150])
from matplotlib import ticker
formatter = ticker.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-1,1))
ax.yaxis.set_major_formatter(formatter)
import matplotlib as mpl
import matplotlib.pyplot as plt
# distance between x and y axis and the numbers on the axes
mpl.rcParams['xtick.major.pad'] = 20
mpl.rcParams['ytick.major.pad'] = 20
import matplotlib.pyplot as plt
x = [5, 3, 7, 2, 4, 1]
plt.plot(x);
plt.xticks(range(len(x)), ['a', 'b', 'c', 'd', 'e', 'f']); # 传入位置和标签参数,以修改坐标轴刻度
plt.yticks(range(1, 8, 2));
plt.show()
# restore defaults
mpl.rcParams['xtick.major.pad'] = 3
mpl.rcParams['ytick.major.pad'] = 3
# 例子
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi, np.pi, 256, endpoint=True) # 生成-Pi到Pi之间具有相同线性距离的256个点
y = np.cos(x) # 计算余弦值
y1 = np.sin(x) # 计算正弦值
plt.plot(x, y) # 绘制余弦图
plt.plot(x, y1) # 绘制正弦图
plt.title("Functions $\sin$ and $\cos$") # LaTex语法,用$\sin$、$\cos$表达式在图表上写上希腊字母
plt.xlim(-3.0, 3.0) # 设置x轴刻度的最大、最小值(当xticks的刻度-np.pi比xlim最小值-3.0更小时,以xticks为准)
plt.ylim(-1.0, 1.0) # 设置y轴刻度的最大、最小值
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']);# LaTex语法,用$-\pi$等表达式在图表上写上希腊字母
plt.yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$']);# 设置x轴、y轴刻度及标签
Image('chart suggestions.png')
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [5,4,3,2]
plt.figure() # 创建一个新的图表
# 如果给方法提供一个字符串参数,例如sample charts,这个字符串就会成为窗口的后台标题
# 如果通过相同的字符串参数调用figure()方法,将会激活相应的图表,并且接下来的绘图操作都在此图表中进行
plt.subplot(231) # 把图表分割成2*3的网格,也可以用plt.subplot(2, 3, 1)这种形式调用,第一个参数是行数,第二个参数是列数,第三个参数表示标号
plt.plot(x, y)
plt.subplot(232)
plt.bar(x, y) # 柱状图
plt.subplot(233)
plt.barh(x, y) # 水平柱状图
plt.subplot(234)
plt.bar(x, y)
y1 = [7,8,5,3]
plt.bar(x, y1, bottom=y, color = 'r') # 绘制堆叠柱状图,将两个柱状图方法调用连在一起,通过设置参数bottom=y,把两个柱状图连接起来形成堆叠柱状图
plt.subplot(235)
plt.boxplot(x) # 箱线图
plt.subplot(236)
plt.scatter(x,y); # 散点图
import matplotlib.pyplot as plt
n = np.array([0,1,2,3,4,5])
xx = np.linspace(-0.7, 1, 100)
x = np.linspace(-3.3, 3.3, 101)
fig, axes = plt.subplots(1, 4, figsize=(12,3))
axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx))) # 散点图
axes[0].set_title("scatter")
axes[1].step(n, n**2, lw=2) # 阶梯图
axes[1].set_title("step")
axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5) # 条形图
axes[2].set_title("bar")
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5); # 条带图
axes[3].set_title("fill_between");
hist()的参数
可以是一个bin数量的整数值,也可以是表示bin的一个序列。默认值为10
bin的范围,当bins参数为序列时,此参数无效。范围外的值将被忽略掉,默认值为None
如果值为True,直方图的值将进行归一化处理,形成概率密度,默认值为False
用于bin边界之间矩形条的居中设置。默认值为mid,其他值为left和right
指定直方图的颜色。可以是单一颜色值或颜色的序列。如果指定了多个数据集合,颜色序列将会设置为相同的顺序。如果未指定,将会使用一个默认的线条颜色
通过设置orientation为horizontal创建水平直方图。默认值为vertical
import matplotlib.pyplot as plt
import numpy as np
y = np.random.randn(1000)
plt.hist(y); # 默认绘制10个bin
plt.show()
import matplotlib.pyplot as plt
import numpy as np
y = np.random.randn(1000)
plt.hist(y, bins=25); # 设置bins参数,绘制25个bin
plt.show()
import matplotlib.pyplot as plt
import numpy as np
n = np.random.randn(100000)
fig, axes = plt.subplots(1, 2, figsize=(12,4))
axes[0].hist(n) # 普通直方图,概率密度函数f(x)
axes[0].set_title("Default histogram")
axes[0].set_xlim((min(n), max(n)))
axes[1].hist(n, cumulative=True, bins=50)
axes[1].set_title("Cumulative detailed histogram") # 累积直方图,分布函数F(x)
axes[1].set_xlim((min(n), max(n)));
import matplotlib.pyplot as plt
import numpy as np
mu = 100
sigma = 15
x = np.random.normal(mu, sigma, 10000) # 生成正态分布数据集
ax = plt.gca() # 获取当前图表
ax.hist(x, bins=35, normed=True, color='r') # 35个bins,颜色为红色,概率密度直方图
ax.set_xlabel('Values')
ax.set_ylabel('Frequency') # 设置x、y轴标题
ax.set_title(r'$\mathrm{Histogram:}\ \mu=%d,\ \sigma=%d$' % (mu, sigma)); # 设置图表标题
errorbar()的参数
color、edgecolor、linewidth、xerr和yerr可以是单一值,也可以是和误差条数目相同长度的序列
给定误差条的宽度,默认值是0.8
如果指定了bottom,其值会加到高度中,默认值为None
指定误差条边界颜色
指定误差条的颜色
误差条边界宽度,可以设为None(默认)和0(此时误差条边界将不显示出来)
有vertical和horizontal两个值
用于在条形图上生成误差条。非对称误差条必须用一个二维数组来指定xerr和yerr,其中第一个列表包括负向误差的值,第二个包含正向误差的值
指定阴影线
+ /
斜线
+ \
反斜线
+ |
垂直线
+ -
水平线
+ +
十字线
+ x
交叉线
+ o
小圆圈
+ 0
大圆圈
+ .
点
+ *
星号
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4, 0.2)
y = np.exp(-x)
e1 = 0.1 * np.abs(np.random.randn(len(y)))
plt.errorbar(x, y, yerr=e1, fmt='x:'); # yerr参数,设置误差条的长度,误差条上下部分的长度均为e1的长度;fmt参数,设置线型
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4, 0.2)
y = np.exp(-x)
e1 = 0.1 * np.abs(np.random.randn(len(y)))
plt.errorbar(x, y, yerr=e1, fmt='None'); # fmt参数为None时,只绘制误差条,不绘制点和连线
plt.show()
# ecolor参数设置误差条的颜色,如果没有该参数,则使用点的颜色;elinewidth参数设置误差条的线宽;capsize参数设置误差条的帽宽
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4, 0.2)
y = np.exp(-x)
e1 = 0.1 * np.abs(np.random.randn(len(y)))
plt.errorbar(x, y, yerr=e1, fmt='.-', ecolor='r', elinewidth=2, capsize=5);
plt.show()
e2 = 0.1 * np.abs(np.random.randn(len(y)))
plt.errorbar(x, y, yerr=e1, xerr=e2, fmt='.-', capsize=0); # xerr绘制水平的误差条
plt.show()
plt.errorbar(x, y, yerr=[e1, e2], fmt='.-'); # 为yerr参数传入数组,绘制不对称的误差条,第一个数是负误差,第二个数是正误差
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# 生成measurements的标号1~10
x = np.arange(1, 11, 1)
# 为每个measurements生成相应的values
y = np.log(x)
# 生成服从标准正态分布的误差
xe = 0.1 * np.abs(np.random.randn(len(y)))
# 绘制误差条形图
plt.bar(x,
y,
yerr=xe, # 在条形图中生成误差条(一个标准差、一个标准误、95%置信区间等)
width=0.4, # 误差条宽度
align='center', # 指定条形的位置
ecolor='r', # 指定误差条的颜色
color='cyan', # 指定条形的填充颜色
label='experiment #1', # 字符串标签,用于生成legend
hatch='-') # 指定阴影线
# give some explainations
plt.xlabel('# measurement')
plt.ylabel('Measured values')
plt.title('Measurements')
plt.legend(loc='upper left')
plt.show()
bar()、barh()
import matplotlib.pyplot as plt
plt.bar([1, 2, 3], [3, 2, 5]); # 第一个参数为条形左下角的x轴坐标,第二个参数为条形的高度;matplotlib会自动设置条形的宽度,本例中条形宽0.8
plt.show()
# width参数设置条形宽度;color参数设置条形颜色;xerr、yerr参数设置水平、垂直误差条;bottom参数设置条形底部的垂直坐标
e1 = 0.3 * np.random.rand(3)
e2 = 0.3 * np.random.rand(3)
import matplotlib.pyplot as plt
plt.bar([1, 2, 3], [3, 2, 5], width=0.5, color='r', xerr=e1, yerr=e2, bottom=1);
plt.ylim([0, 7])
plt.show()
# 例子:从字典中绘制条形图
import matplotlib.pyplot as plt
import numpy as np
dic = {'A': 40, 'B': 70, 'C': 30, 'D': 85}
for i, key in enumerate(dic): # 用for循环,每次绘制一个条形
plt.bar(i, dic[key]);
plt.xticks(np.arange(len(dic))+0.4, dic.keys());
plt.yticks(dic.values());
plt.show()
# 例子:绘制有误差条的并列条形图
import matplotlib.pyplot as plt
import numpy as np
data1 = 10*np.random.rand(5)
data2 = 10*np.random.rand(5)
data3 = 10*np.random.rand(5)
e2 = 0.5 * np.abs(np.random.randn(len(data2)))
locs = np.arange(1, len(data1)+1)
width = 0.27
plt.bar(locs, data1, width=width);
plt.bar(locs+width, data2, yerr=e2, width=width, color='red');
plt.bar(locs+2*width, data3, width=width, color='green') ;
plt.xticks(locs + width*1.5, locs);
plt.show()
barh()
import matplotlib.pyplot as plt
plt.barh([1, 2, 3], [3, 2, 5]);
plt.show()
pie()
饼图适合展示各部分占总体的比例,条形图适合比较各部分的大小
import matplotlib.pyplot as plt
plt.figure(figsize=(4, 4)); # 饼图最好绘制在正方形区域,可以保证饼是圆形而非椭圆形
x = [45, 35, 20] # 当各部分之和大于1时,会自动计算各部分占总体的比例
labels = ['Cats', 'Dogs', 'Fishes']
plt.pie(x, labels=labels); # labels参数可以设置各区域标签
plt.show() # 第一块饼从3点钟方向开始绘制
import matplotlib.pyplot as plt
plt.figure(figsize=(4, 4));
x = [0.1, 0.2, 0.3] # 当各部分之和小于1时,则不计算各部分占总体的比例,饼的大小是数值和1之比
labels = ['Cats', 'Dogs', 'Fishes']
plt.pie(x, labels=labels); # labels参数可以设置各区域标签
plt.show()
# labels参数设置每一块的标签;labeldistance参数设置标签距离圆心的距离(比例值)
# autopct参数设置比例值的显示格式;pctdistance参数设置比例值文字距离圆心的距离
# explode参数设置每一块顶点距圆形的长度(比例值);colors参数设置每一块的颜色;
# shadow参数为布尔值,设置是否绘制阴影
import matplotlib.pyplot as plt
plt.figure(figsize=(4, 4));
x = [4, 9, 21, 55, 30, 18]
labels = ['Swiss', 'Austria', 'Spain', 'Italy', 'France', 'Benelux']
explode = [0.2, 0.1, 0, 0, 0.1, 0]
colors = ['r', 'k', 'b', 'm', 'c', 'g']
plt.pie(x, labels=labels, labeldistance=1.2, explode=explode, colors=colors, autopct='%1.1f%%', pctdistance=0.5, shadow=True);
plt.show()
import matplotlib.pyplot as plt
# 绘制一个正方形的figure and axes
plt.figure(1, figsize=(4, 4))
ax = plt.axes([0.1, 0.1, 0.8, 0.8])
# 圆弧按照逆时针绘制
labels = 'Spring', 'Summer', 'Autumn', 'Winter'
values = [15, 16, 16, 28]
explode =[0.1, 0.1, 0.1, 0.1] # 指定分裂序列,每一个元素表示每个圆弧间的偏移量,为半径的百分比
# 绘制饼图
plt.pie(values,
explode=explode,
labels=labels,
autopct='%1.1f%%', # 格式化绘制圆弧中的标签,标签可以是一个格式化字符串或者一个可调用的对象(函数)
startangle=67) # 指定圆弧开始绘制的角度,默认从角度0(x轴)开始绘制
plt.title('Rainy days by season');
scatter()
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x, y);
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(1000)
y1 = np.random.randn(len(x)) # y1与x不相关
y2 = 1.2 + np.exp(x) # y2与x高度相关
ax1 = plt.subplot(121)
plt.scatter(x, y1, color='indigo', alpha=0.3, edgecolors='white', label='no correl')
plt.xlabel('no correlation')
plt.grid(True)
plt.legend()
ax2 = plt.subplot(122, sharey=ax1, sharex=ax1)
plt.scatter(x, y2, color='green', alpha=0.3, edgecolors='grey', label='correl')
plt.xlabel('strong correlation')
plt.grid(True)
plt.legend()
plt.show()
# s参数设置散点的大小;c参数设置散点的颜色;marker参数设置散点的形状
import matplotlib.pyplot as plt
import numpy as np
size = 50*np.random.randn(1000)
colors = np.random.rand(1000)
plt.scatter(x, y, s=size, c=colors, marker='d');
plt.show()
标记 | 描述 | 标记 | 描述 |
---|---|---|---|
'v' | 一角朝下的三角形 | '<' | 一角朝左的三角形 |
'^' | 一角朝上的三角形 | '>' | 一角朝右的三角形 |
's' | 正方形 | 'o' | 圆圈 |
'd' | 小菱形 | 'p' | 五边形 |
'h' | 六边形1 | '8' | 八边形 |
'+' | 加号 | 'x' | X |
fill_between()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2*np.pi*x)
y2 = 1.2*np.sin(4*np.pi*x)
fig = plt.figure()
ax = plt.gca()
# 绘制曲线
ax.plot(x, y1, x, y2, color='black')
# 填充曲线之间的区域
ax.fill_between(x, y1, y2,
where=y2>=y1, # where指定一个条件来填充曲线,where接受布尔值(可以是表达式)
facecolor='darkblue',
interpolate=True)
ax.fill_between(x, y1, y2, where=y2<=y1, facecolor='deeppink', interpolate=True)
ax.set_title('filled between');
plt.show()
polar()
import matplotlib.pyplot as plt
import numpy as np
theta = np.arange(0., 2., 1./180.)*np.pi
plt.polar(3*theta, theta/5); # theta参数是角度,r参数是距离圆心的距离
plt.polar(theta, np.cos(4*theta));
plt.polar(theta, [1.4]*len(theta));
plt.show()
# polar plot using add_axes and polar projection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = np.linspace(0, 2 * np.pi, 100)
ax.plot(t, t, color='blue', lw=3);
rgrids()和thetagrids()
import matplotlib.pyplot as plt
import numpy as np
theta = np.arange(0., 2., 1./180.)*np.pi
r = np.abs(np.sin(5*theta) - 2.*np.cos(theta))
plt.polar(theta, r);
plt.rgrids(np.arange(0.2, 3.1, .7), angle=0); # radii参数设置网格线的位置;labels参数设置网格线的标签;angle参数设置网格线的角度(默认值22.5)
plt.thetagrids(range(45, 360, 90), frac=0.9); # angles参数设置网格线的角度,labels参数设置网格线的标签;frac参数设置网格线标签的位置(比例值)
plt.show()
import matplotlib.pyplot as plt
# 部分图形对象可以在matplotlib.pyplot中找到,但完整的图形对象集合位于matplotlib.patches中
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3) # 先创建图形对象
circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],
color='g', alpha=0.5)
ax.add_patch(rect) # 再通过ax.add_patch将图形对象添加到subplot中
ax.add_patch(circ)
ax.add_patch(pgon);
text()和figtext()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 7, .01)
y = np.sin(x)
plt.plot(x, y);
plt.text(0.1, -0.04, 'sin(0)=0'); # 位置参数是坐标
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 2*np.pi, .01)
y = np.sin(x)
plt.plot(x, y);
plt.figtext(0.14, 0.5, 'sin(0)=0'); # 位置参数是坐标
plt.show()
annotate()
# xy参数设置箭头指示的位置,xytext参数设置注释文字的位置
# arrowprops参数以字典的形式设置箭头的样式
# width参数设置箭头长方形部分的宽度,headlength参数设置箭头尖端的长度,headwidth参数设置箭头尖端底部的宽度,shrink参数设置箭头顶点、尾部与指示点、注释文字的距离(比例值)
import matplotlib.pyplot as plt
y = [13, 11, 13, 12, 13, 10, 30, 12, 11, 13, 12, 12, 12, 11, 12]
plt.plot(y);
plt.ylim(ymax=35); # 为了让注释不会超出图的范围,需要调整y坐标轴的界限
plt.annotate('this spot must really\nmean something', xy=(6, 30), xytext=(8, 31.5), arrowprops=dict(width=15, headlength=20, headwidth=20, facecolor='black', shrink=0.1));
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# 生成3个正态分布数据数据集
x1 = np.random.normal(30, 3, 100)
x2 = np.random.normal(20, 2, 100)
x3 = np.random.normal(10, 3, 100)
# 绘制3个数据集,并为每个plot指定一个字符串标签
plt.plot(x1, label='plot') # 如果不想在图例中显示标签,可以将标签设置为_nolegend_
plt.plot(x2, label='2nd plot')
plt.plot(x3, label='last plot')
# 绘制图例
plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.102), # 指定边界框起始位置为(0, 1.02),并设置宽度为1,高度为0.102
loc=3, # 设置位置为lower left
ncol=3, # 设置列数为3,默认值为1
mode="expand", # mode为None或者expand,当为expand时,图例框会扩展至整个坐标轴区域
borderaxespad=0.) # 指定坐标轴和图例边界之间的间距
# 绘制注解
plt.annotate("Important value", # 注解文本的内容
xy=(55,20), # 箭头终点所在位置
xycoords='data', # 指定注解和数据使用相同的坐标系
xytext=(5, 38), # 注解文本的起始位置,箭头由xytext指向xy坐标位置
arrowprops=dict(arrowstyle='->')); # arrowprops字典定义箭头属性,此处用arrowstyle定义箭头风格
annotate()
arrow()函数很不好用,所以使用不带注释的annotate()函数绘制箭头
import matplotlib.pyplot as plt
plt.axis([0, 10, 0, 20]);
arrstyles = ['-', '->', '-[', '<-', '<->', 'fancy', 'simple', 'wedge']
for i, style in enumerate(arrstyles):
plt.annotate(style, xytext=(1, 2+2*i), xy=(4, 1+2*i), arrowprops=dict(arrowstyle=style));
connstyles=["arc", "arc,angleA=10,armA=30,rad=15", "arc3,rad=.2", "arc3,rad=-.2", "angle", "angle3"]
for i, style in enumerate(connstyles):
plt.annotate("", xytext=(6, 2+2*i), xy=(8, 1+2*i), arrowprops=dict(arrowstyle='->', connectionstyle=style));
plt.show()
有三种使用Matplotlib的方法:
Matplotlib中的对象从高到低分为三层:
对象 | 描述 |
---|---|
FigureCanvas | Container class for the Figure instance |
Figure | Container for one or more Axes instances |
Axes | The rectangular areas to hold the basic elements, such as lines, text, and so on |
fig.add_axes()可以被用于镶嵌式的多重图表
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 10)
y = x ** 2
# 创建figure实例
fig = plt.figure()
# 使用add_axes方法,创建一个新的Axes实例
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
# 在Axes实例上绘图
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
# 通过在figure实例中添加axis实例,可以任意控制一个figure中axis的数量及位置
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes
# main figure
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')
# insert
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');
import matplotlib.pyplot as plt
import numpy as np
xx = np.linspace(-0.7, 1, 100)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(xx, xx**2, xx, xx**3)
fig.tight_layout()
# inset
inset_ax = fig.add_axes([0.2, 0.5, 0.35, 0.35]) # 参数依次为左下角的X坐标, Y坐标, 宽度, 高度
inset_ax.plot(xx, xx**2, xx, xx**3)
inset_ax.set_title('zoom near origin')
# set axis range
inset_ax.set_xlim(-.2, .2)
inset_ax.set_ylim(-.005, .01)
# set axis tick locations
inset_ax.set_yticks([0, 0.005, 0.01])
inset_ax.set_xticks([-0.1,0,.1]);
与fig.add_axes()方法相比,该方法不能控制Axes对象的具体位置,更无法设置嵌套结构的子图
import matplotlib.pyplot as plt
fig = plt.figure() # 返回一个figure对象,可以在该对象上添加Axes对象
ax1 = fig.add_subplot(211) # fig.add_subplot(numrows, numcols, fignum),为figure对象添加Axes对象(子图);绘制2行1列的子图,ax1指代第1个子图
ax1.plot([1, 2, 3], [1, 2, 3]);
ax2 = fig.add_subplot(212) # 绘制2行1列的子图,ax1指代第2个子图
ax2.plot([1, 2, 3], [3, 2, 1]);
plt.show()
plt.subplots()选项
subplot的行数
subplot的列数
所有subplot应该使用相同的X轴刻度(调节xlim将会影响所有subplot)
所有subplot应该使用相同的Y轴刻度(调节ylim将会影响所有subplot)
用于创建各subplot的关键字字典
创建figure时的其他关键字,如plt.subplots(2,2,figsize=(8,6))
fig, ax = plt.subplots(2, 3)
fig.tight_layout()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(10,4))
axes[0].plot(x, x**2, x, np.exp(x))
axes[0].set_title("Normal scale")
axes[1].plot(x, x**2, x, np.exp(x))
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)");
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
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))
fig.tight_layout()
import matplotlib.pyplot as plt
plt.figure(0)
axes1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
axes2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
axes3 = plt.subplot2grid((3, 3), (1, 2))
axes4 = plt.subplot2grid((3, 3), (2, 0))
axes5 = plt.subplot2grid((3, 3), (2, 1), colspan=2)
# tidy up tick labels size
all_axes = plt.gcf().axes
for ax in all_axes:
for ticklabel in ax.get_xticklabels() + ax.get_yticklabels():
ticklabel.set_fontsize(10)
plt.suptitle("Demo of subplot2grid");
import matplotlib.gridspec as gridspec
fig = plt.figure()
gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1])
for g in gs:
ax = fig.add_subplot(g)
fig.tight_layout()
plt.subplots_adjust()、wspace和hspace参数
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(2):
for j in range(2):
axes[i, j].hist(randn(500), bins=50, color='k', alpha=0.5) # 通过索引选取相应位置的AxesSubplot实例,并用实例的方法绘图
plt.subplots_adjust(wspace=0, hspace=0) # 将subplot之间的间距收缩到了0
自动调节子图的位置,使得子图之间不会发生重叠
import matplotlib.pyplot as plt
fig = plt.figure() # 返回一个figure对象,可以在该对象上添加Axes对象
ax1 = fig.add_subplot(211) # fig.add_subplot(numrows, numcols, fignum),为figure对象添加Axes对象(子图);绘制2行1列的子图,ax1指代第1个子图
ax1.plot([1, 2, 3], [1, 2, 3]);
ax2 = fig.add_subplot(212) # 绘制2行1列的子图,ax1指代第2个子图
ax2.plot([1, 2, 3], [3, 2, 1]);
fig.tight_layout()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.random.randn(len(x))
fig = plt.figure()
ax = fig.add_subplot(111)
l, = plt.plot(x, y) # plot会返回一个Line2D对象的列表,l会得到该列表的第一个(此处也是唯一一个)元素,之后都可以通过l来对该曲线对象的样式进行设置
# plt.plot(x, y)返回的是list
# line = plt.plot(x, y),则line是list
# line, = plt.plot(x, y),则line是matplotlib.lines.Line2D实例,所以line后面有个逗号
l.set_color('r') # 通过l对象对曲线的颜色进行设置
t = ax.set_title('random numbers')
plt.show()
import matplotlib.pyplot as plt
fig1 = plt.figure() # fig1指代第1个figure对象
ax1 = fig1.add_subplot(111) # add_subplot中传入参数111,ax1指代第1幅图
ax1.plot([1, 2, 3], [1, 2, 3]);
fig2 = plt.figure() # fig2指代第2个figure对象
ax2 = fig2.add_subplot(111) # ax2指代第2幅图
ax2.plot([1, 2, 3], [3, 2, 1]);
plt.show()
twinx()和twiny()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0., np.e, 0.01)
y1 = np.exp(-x)
y2 = np.log(x)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1);
ax1.set_ylabel('Y values for exp(-x)');
ax2 = ax1.twinx() # twinx()的作用是在ax1的位置创建了另一个ax2对象覆盖于其上,并保证2个Axes对象的X轴完全一致,从而达到了1幅图中2个Y轴的效果
ax2.plot(x, y2, 'r');
ax2.set_xlim([0, np.e]);
ax2.set_ylabel('Y values for ln(x)');
ax2.set_xlabel('Same X for both exp(-x) and ln(x)');
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 100)
fig, ax1 = plt.subplots()
ax1.plot(x, x**2, lw=2, color="blue")
ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
for label in ax1.get_yticklabels():
label.set_color("blue")
ax2 = ax1.twinx()
ax2.plot(x, x**3, lw=2, color="red")
ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
for label in ax2.get_yticklabels():
label.set_color("red")
set_yscale、set_xscale、semilogx、semilogy、loglog
import matplotlib as mpl
mpl.rcParams['font.size'] = 10.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0., 20, 0.01)
fig = plt.figure()
ax1 = fig.add_subplot(311)
y1 = np.exp(x/6.)
ax1.plot(x, y1);
ax1.grid(True)
ax1.set_yscale('log') # 将Y坐标轴的尺度设为对数
ax1.set_ylabel('log Y');
ax2 = fig.add_subplot(312)
y2 = np.cos(np.pi*x)
ax2.semilogx(x, y2); # semilogx函数是plot()和ax.set_xscale('log')的结合,将X坐标轴的尺度设为对数
ax2.set_xlim([0, 20]);
ax2.grid(True)
ax2.set_ylabel('log X');
ax3 = fig.add_subplot(313)
y3 = np.exp(x/4.)
ax3.loglog(x, y3, basex=3); # loglog将X轴和Y轴的尺度设为对数
ax3.grid(True)
ax3.set_ylabel('log X and Y');
plt.show()
sharex参数和sharey参数
import matplotlib as mpl
mpl.rcParams['font.size'] = 11.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(11)
fig = plt.figure()
ax1 = fig.add_subplot(311)
ax1.plot(x, x);
ax2 = fig.add_subplot(312, sharex=ax1) # ax2对象与ax1对象保持一致的X轴
ax2.plot(2*x, 2*x);
ax3 = fig.add_subplot(313, sharex=ax1) # ax3对象与ax1对象保持一致的X轴
ax3.plot(3*x, 3*x);
plt.show()
ax.spines[].set_color()
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(6,2))
ax = fig.add_subplot(111)
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('blue')
ax.spines['left'].set_color('red')
ax.spines['left'].set_linewidth(2)
# turn off axis spine to the right
ax.spines['right'].set_color("none")
ax.yaxis.tick_left() # only ticks on the left side
ax.spines[].set_position(('data',0))
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0)) # set position of x spine to x=0
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0)) # set position of y spine to y=0
xx = np.linspace(-1., 1., 100)
ax.plot(xx, xx**3);
import matplotlib.pyplot as plt
import numpy as np
# 通过set_color去掉不想显示的轴线、通过set_position把轴线移动到特定位置
x = np.linspace(-np.pi, np.pi, 500)
y = np.sin(x)
plt.plot(x, y)
# gca get current axes,用ax指代当前的图表
ax = plt.gca()
# 隐藏上侧和右侧坐标轴线
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 将下侧和左侧坐标轴线移到图中央
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
# 设置坐标轴刻度标签位置
ax.xaxis.set_ticks_position('bottom') # xaxis类控制x轴
ax.yaxis.set_ticks_position('left') # yaxis类控制y轴
figsize参数、dpi参数
Unfortunately, when saving figures the labels are sometimes clipped, and it can be necessary to adjust the positions of axes a little bit. This can be done using subplots_adjust()
:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 100)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, x**2, x, np.exp(x))
ax.set_yticks([0, 50, 100, 150])
ax.set_title("title")
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.subplots_adjust(left=0.1, right=0.9, bottom=0.3, top=0.7); # 调整图表的大小,四个参数分别代表图表四个边框所在位置(归一化0到1)
alpha = 0.7
phi_ext = 2 * np.pi * 0.5
def flux_qubit_potential(phi_m, phi_p):
return 2 + alpha - 2 * np.cos(phi_p) * np.cos(phi_m) - alpha * np.cos(phi_ext - 2*phi_p)
phi_m = np.linspace(0, 2*np.pi, 100)
phi_p = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
fig, ax = plt.subplots()
p = ax.pcolor(X/(2*np.pi), Y/(2*np.pi), Z, cmap=mpl.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max())
cb = fig.colorbar(p, ax=ax)
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
fig, ax = plt.subplots()
im = ax.imshow(Z, cmap=mpl.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
im.set_interpolation('bilinear')
cb = fig.colorbar(im, ax=ax)
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
fig, ax = plt.subplots()
cnt = ax.contour(Z, cmap=mpl.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
import matplotlib.pyplot as plt
import numpy as np
matr = np.random.rand(21, 31)
cs = plt.contour(matr) # 第一个参数是矩阵;第二个参数是等高线的层次,如果不传入第二个参数,则matplotlib会自动计算最优的层次数
plt.show()
import matplotlib.pyplot as plt
import numpy as np
plt.contour(matr, 2) # 第一个参数是矩阵;第二个参数是等高线的层次,如果不传入第二个参数,则matplotlib会自动计算最优的层次数
plt.show()
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
fig, ax = plt.subplots()
cnt = ax.contourf(Z, cmap=mpl.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
csf = plt.contourf(matr) # contourf对contour的等高线间隙进行填充,深蓝色表示低值,深红色表示高值;可以通过设置cmp参数,用colormap填充等高线
plt.colorbar(); # 绘制一个颜色条(相当于图例)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2, 2, 0.01)
y = np.arange(-2, 2, 0.01)
X, Y = np.meshgrid(x, y) # np.meshgrid将x、y向量转化为坐标矩阵
ellipses = X*X/9 + Y*Y/4 - 1
cs = plt.contour(ellipses)
plt.clabel(cs); # 为等高线绘制表示值的水平的标签
plt.show()
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
axes = fig.add_axes()
y = np.random.randn(9)
col_labels=['col1','col2','col3']
row_labels=['row1','row2','row3']
table_vals=[[11,12,13],[21,22,23],[28,29,30]]
row_colors=['red','gold','green']
# plt.table返回一个Table对象实例,可以访问该实例的借口,对表格进行调整,最后用plt.add_table()方法把表格添加到相应的坐标系实例中
the_table = plt.table(cellText=table_vals,
colWidths = [0.1]*3,
rowLabels=row_labels,
colLabels=col_labels,
rowColours=row_colors,
loc='upper right')
plt.plot(y);

To use 3D graphics in matplotlib, we first need to create an instance of the Axes3D
class. 3D axes can be added to a matplotlib figure canvas in exactly the same way as 2D axes; or, more conveniently, by passing a projection='3d'
keyword argument to the add_axes
or add_subplot
methods.
from mpl_toolkits.mplot3d.axes3d import Axes3D
alpha = 0.7
phi_ext = 2 * np.pi * 0.5
def flux_qubit_potential(phi_m, phi_p):
return 2 + alpha - 2 * np.cos(phi_p) * np.cos(phi_m) - alpha * np.cos(phi_ext - 2*phi_p)
phi_m = np.linspace(0, 2*np.pi, 100)
phi_p = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib as mpl
fig = plt.figure(figsize=(14,6))
# `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)
# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=mpl.cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib as mpl
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1, 1, 1, projection='3d')
p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib as mpl
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-np.pi, cmap=mpl.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-np.pi, cmap=mpl.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*np.pi, cmap=mpl.cm.coolwarm)
ax.set_xlim3d(-np.pi, 2*np.pi);
ax.set_ylim3d(0, 3*np.pi);
ax.set_zlim3d(-np.pi, 2*np.pi);
We can change the perspective of a 3D plot using the view_init
method, which takes two arguments: elevation
and azimuth
angle (in degrees):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib as mpl
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(1,2,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
ax.view_init(30, 45)
ax = fig.add_subplot(1,2,2, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
ax.view_init(70, 30)
fig.tight_layout()
控制文字属性的方法:
Pyplot函数 | API方法 | 描述 |
---|---|---|
text() | mpl.axes.Axes.text() | 在Axes对象的任意位置添加文字 |
xlabel() | mpl.axes.Axes.set_xlabel() | 为X轴添加标签 |
ylabel() | mpl.axes.Axes.set_ylabel() | 为Y轴添加标签 |
title() | mpl.axes.Axes.set_title() | 为Axes对象添加标题 |
legend() | mpl.axes.Axes.legend() | 为Axes对象添加图例 |
figtext() | mpl.figure.Figure.text() | 在Figure对象的任意位置添加文字 |
suptitle() | mpl.figure.Figure.suptitle() | 为Figure对象添加中心化的标题 |
annnotate() | mpl.axes.Axes.annotate() | 为Axes对象添加注释(箭头可选) |
所有的方法会返回一个matplotlib.text.Text对象
Mathtext:用美元$符号包括LaTeX语句
import matplotlib.pyplot as plt
fig = plt.figure()
ax= fig.add_subplot(111)
ax.set_xlim([1, 6]);
ax.set_ylim([1, 9]);
ax.text(2, 8, r"$ \mu \alpha \tau \pi \lambda \omega \tau \ lambda \iota \beta $");
ax.text(2, 6, r"$ \lim_{x \rightarrow 0} \frac{1}{x} $");
ax.text(2, 4, r"$ a \ \leq \ b \ \leq \ c \ \Rightarrow \ a \ \leq \ c$");
ax.text(2, 2, r"$ \sum_{i=1}^{\infty}\ x_i^2$");
ax.text(4, 8, r"$ \sin(0) = \cos(\frac{\pi}{2})$");
ax.text(4, 6, r"$ \sqrt[3]{x} = \sqrt{y}$");
ax.text(4, 4, r"$ \neg (a \wedge b) \Leftrightarrow \neg a \vee \neg b$");
ax.text(4, 2, r"$ \int_a^b f(x)dx$");
plt.show()
imread()和imshow()
读取图片文件,并将其转化为NumPy array
Matplotlib只能读取PNG文件,但如果加载了Python Imaging Library(PIL),则这个包将被用来读取图片文件并返回数组。
默认从图片的左上角开始读取数据,设置origin='lower'(默认设置为origin='upper'),可以从图片的左下角开始读取数据。
Unofficial Windows Binaries for Python Extension Packages
pillow
Pillow is a replacement for PIL, the Python Image Library, which provides image processing functionality and supports many file formats.
Use from PIL import Image
instead of import Image
.
读取NumPy array,并将其显示为图片
语法:
import matplotlib.pyplot as plt
f = plt.imread('/path/to/image/file.ext')
plt.imshow(f)
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2, 2, 0.01)
y = np.arange(-2, 2, 0.01)
X, Y = np.meshgrid(x, y)
ellipses = X*X/9 + Y*Y/4 - 1
plt.imshow(ellipses);
plt.colorbar();
plt.show()
Matplotlib has a number of "backends" which are responsible for rendering graphs. The different backends are able to generate graphics with different formats and display/event loops. There is a distinction between noninteractive backends (such as 'agg', 'svg', 'pdf', etc.) that are only used to generate image files (e.g. with the savefig
function), and interactive backends (such as Qt4Agg, GTK, MaxOSX) that can display a GUI window for interactively exploring figures.
A list of available backends are:
import matplotlib as mpl
print(mpl.rcsetup.all_backends)
[u'GTK', u'GTKAgg', u'GTKCairo', u'MacOSX', u'Qt4Agg', u'Qt5Agg', u'TkAgg', u'WX', u'WXAgg', u'CocoaAgg', u'GTK3Cairo', u'GTK3Agg', u'WebAgg', u'nbAgg', u'agg', u'cairo', u'emf', u'gdk', u'pdf', u'pgf', u'ps', u'svg', u'template']
The default backend, called agg
, is based on a library for raster graphics which is great for generating raster formats like PNG.
Normally we don't need to bother with changing the default backend; but sometimes it can be useful to switch to, for example, PDF or GTKCairo (if you are using Linux) to produce high-quality vector graphics instead of raster based graphics.
svg:可缩放矢量图形
When we use IPython notebook it is convenient to use a matplotlib backend that outputs the graphics embedded in the notebook file. To activate this backend, somewhere in the beginning on the notebook, we add:
%matplotlib inline
It is also possible to activate inline matplotlib plotting with:
%pylab inline
The difference is that %pylab inline
imports a number of packages into the global address space (scipy, numpy), while %matplotlib inline
only sets up inline plotting. In new notebooks created for IPython 1.0+, I would recommend using %matplotlib inline
, since it is tidier and you have more control over which packages are imported and how. Commonly, scipy and numpy are imported separately with:
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
The inline backend has a number of configuration options that can be set by using the IPython magic command %config
to update settings in InlineBackend
. For example, we can switch to SVG figures or higher resolution figures with either:
%config InlineBackend.figure_format='svg'
or:
%config InlineBackend.figure_format='retina'
For more information, type:
%config InlineBackend
Note that when we use an interactive backend, we must call plt.show()
to make the figure appear on the screen.