zoukankan      html  css  js  c++  java
  • matplotlib之pyplot 学习示例

     现在通过numpy和matplotlib.pyplot 在Python上实现科学计算和绘图,而且和matlab极为相像(效率差点,关键是方便简单)

    这里有大量plots代码例子。

     1. 简单的绘图(plot)   2、subplot 示例   3、直方图(hist) 4、路径(path)示例
     5、3d图(mplot3d)   6、流线图(Streamplot) 7、椭圆(Ellipses) 8、条形图(Bar) 
     9、饼图(Pie)    10、表的示例(Table) 11、散点图(Scatter) 12、滑块示例(Slider)
     13、填充示例(Fill)   14、日期刻度示例 15、对数 图  16、极图(Polar) 
     17、自动图例(Legend)  18、数学表达式(Mathtext) 19、数学文本的TeX渲染(usetex) 20、EEG 示例(pbrain)
     21、XKCD-风格草图           

    其他网址链接

    .plot 显示中文字符 pyplot常用库函数大全
     subplot 子图  


    1. 最简单的绘图实例 

      这是一个非常基本的带文字标签的plot()

    import matplotlib.pyplot as plt

    import numpy as np

    t = np.arange(0.0, 2.0, 0.01)

    s = 1 + np.sin(2*np.pi*t)

    plt.plot(t, s)

    plt.xlabel('time (s)')

    plt.ylabel('voltage (mV)')

    plt.title('About as simple as it gets, folks')

    plt.grid(True)

    plt.savefig("test.png")

    plt.show()

    ../_images/simple_plot.png

    2、subplot 示例

        使用  subplot() 命令创建多个轴(即子图) 

    import numpy as np
    import matplotlib.pyplot as plt

    x1 = np.linspace(0.0, 5.0)
    x2 = np.linspace(0.0, 2.0)

    y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
    y2 = np.cos(2 * np.pi * x2)

    plt.subplot(2, 1, 1)
    plt.plot(x1, y1, 'o-')
    plt.title('A tale of 2 subplots')
    plt.ylabel('Damped oscillation')

    plt.subplot(2, 1, 2)
    plt.plot(x2, y2, '.-')
    plt.xlabel('time (s)')
    plt.ylabel('Undamped')

    plt.show()

    ../_images/subplot_demo1.png

    3、直方图(Histograms)

      hist()命令自动生成直方图并返回容器的计数或概率:

    import numpy as np
    import matplotlib.mlab as mlab
    import matplotlib.pyplot as plt

    np.random.seed(0)

    mu = 100 # mean of distribution
    sigma = 15 # standard deviation of distribution
    x = mu + sigma * np.random.randn(437)

    num_bins = 50

    fig, ax = plt.subplots()

    # the histogram of the data
    n, bins, patches = ax.hist(x, num_bins, normed=1)

    # add a 'best fit' line
    y = mlab.normpdf(bins, mu, sigma)
    ax.plot(bins, y, '--')
    ax.set_xlabel('Smarts')
    ax.set_ylabel('Probability density')
    ax.set_title(r'Histogram of IQ: $mu=100$, $sigma=15$')

    # Tweak spacing to prevent clipping of ylabel
    fig.tight_layout()
    plt.show()

    ../_images/histogram_demo_features1.png

    4、路径示例

     可以使用  matplotlib.path 模块在matplotlib中添加任意路径 : 

    import matplotlib.path as mpath
    import matplotlib.patches as mpatches
    import matplotlib.pyplot as plt


    fig, ax = plt.subplots()

    Path = mpath.Path
    path_data = [
    (Path.MOVETO, (1.58, -2.57)),
    (Path.CURVE4, (0.35, -1.1)),
    (Path.CURVE4, (-1.75, 2.0)),
    (Path.CURVE4, (0.375, 2.0)),
    (Path.LINETO, (0.85, 1.15)),
    (Path.CURVE4, (2.2, 3.2)),
    (Path.CURVE4, (3, 0.05)),
    (Path.CURVE4, (2.0, -0.5)),
    (Path.CLOSEPOLY, (1.58, -2.57)),
    ]
    codes, verts = zip(*path_data)
    path = mpath.Path(verts, codes)
    patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
    ax.add_patch(patch)

    # plot control points and connecting lines
    x, y = zip(*path.vertices)
    line, = ax.plot(x, y, 'go-')

    ax.grid()
    ax.axis('equal')
    plt.show()

    ../_images/path_patch_demo1.png

    5、3d图(mplot3d)

    mplot3d工具包(请参阅mplot3d教程和 mplot3d示例)支持简单的3d图形,包括曲面,线框,散点图和条形图。

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    import numpy as np


    fig = plt.figure()
    ax = fig.gca(projection='3d')

    # Make data.
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2 + Y**2)
    Z = np.sin(R)

    # Plot the surface.
    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)

    # Customize the z axis.
    ax.set_zlim(-1.01, 1.01)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show()

    ../_images/surface3d_demo.png

    6、流线图(Streamplot)

    streamplot()函数绘制矢量场的流线。除了简单绘制流线之外,它还允许将流线的颜色和/或线宽映射到单独的参数中,例如矢量场的速度或局部强度。

    import numpy as np
    import matplotlib.pyplot as plt

    Y, X = np.mgrid[-3:3:100j, -3:3:100j]
    U = -1 - X**2 + Y
    V = 1 + X - Y**2
    speed = np.sqrt(U*U + V*V)

    fig0, ax0 = plt.subplots()
    strm = ax0.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)
    fig0.colorbar(strm.lines)

    fig1, (ax1, ax2) = plt.subplots(ncols=2)
    ax1.streamplot(X, Y, U, V, density=[0.5, 1])

    lw = 5*speed / speed.max()
    ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)

    plt.show()

    ../_images/streamplot_demo_features_001.png

    ../_images/streamplot_demo_features_011.png

    7、椭圆(Ellipses)

    为了支持 凤凰号火星飞行任务(使用matplotlib显示航天器的地面跟踪),Michael Droettboom在Charlie Moad的基础上建立了一个非常精确的8次样条逼近椭圆弧(请参考资料 Arc),并对缩放不敏感。

    import matplotlib.pyplot as plt
    import numpy.random as rnd
    from matplotlib.patches import Ellipse

    NUM = 250

    ells = [Ellipse(xy=rnd.rand(2)*10, width=rnd.rand(), height=rnd.rand(), angle=rnd.rand()*360)
    for i in range(NUM)]

    fig = plt.figure(0)
    ax = fig.add_subplot(111, aspect='equal')
    for e in ells:
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_alpha(rnd.rand())
    e.set_facecolor(rnd.rand(3))

    ax.set_xlim(0, 10)
    ax.set_ylim(0, 10)

    plt.show()

    ../_images/ellipse_demo1.png

    8、条形图(Bar)

        使用 bar() 命令创建条形图是简单的,它包括诸如自定义错误条等。

    import numpy as np
    import matplotlib.pyplot as plt

    n_groups = 5

    means_men = (20, 35, 30, 35, 27)
    std_men = (2, 3, 4, 1, 2)

    means_women = (25, 32, 34, 20, 25)
    std_women = (3, 5, 2, 3, 3)

    fig, ax = plt.subplots()

    index = np.arange(n_groups)
    bar_width = 0.35

    opacity = 0.4
    error_config = {'ecolor': '0.3'}

    rects1 = plt.bar(index, means_men, bar_width,
    alpha=opacity,
    color='b',
    yerr=std_men,
    error_kw=error_config,
    label='Men')

    rects2 = plt.bar(index + bar_width, means_women, bar_width,
    alpha=opacity,
    color='r',
    yerr=std_women,
    error_kw=error_config,
    label='Women')

    plt.xlabel('Group')
    plt.ylabel('Scores')
    plt.title('Scores by group and gender')
    plt.xticks(index + bar_width / 2, ('A', 'B', 'C', 'D', 'E'))
    plt.legend()

    plt.tight_layout()
    plt.show()

    ../_images/barchart_demo3.png

        创建堆积条(bar_stacked.py)或水平条形图(barh_demo.py也很简单

    9、饼图(Pie)

      该 pie()命令允许您轻松创建饼图。可选功能包括自动标记面积百分比,从饼图中心突起一个或多个楔子,以及阴影效果。仔细查看附件中的代码,只需几行代码即可生成此图。

    import matplotlib.pyplot as plt

    # Pie chart, where the slices will be ordered and plotted counter-clockwise:
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
    shadow=True, startangle=90)
    ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.

    plt.show()

    ../_images/pie_demo_features2.png

    10、表的示例(Table)

       table()命令将一个文本表添加到轴。

    import numpy as np
    import matplotlib.pyplot as plt

    data = [[ 66386, 174296, 75131, 577908, 32015],
    [ 58230, 381139, 78045, 99308, 160454],
    [ 89135, 80552, 152558, 497981, 603535],
    [ 78415, 81858, 150656, 193263, 69638],
    [ 139361, 331509, 343164, 781380, 52269]]

    columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
    rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]

    values = np.arange(0, 2500, 500)
    value_increment = 1000

    # Get some pastel shades for the colors
    colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
    n_rows = len(data)

    index = np.arange(len(columns)) + 0.3
    bar_width = 0.4

    # Initialize the vertical-offset for the stacked bar chart.
    y_offset = np.array([0.0] * len(columns))

    # Plot bars and create text labels for the table
    cell_text = []
    for row in range(n_rows):
    plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
    y_offset = y_offset + data[row]
    cell_text.append(['%1.1f' % (x/1000.0) for x in y_offset])
    # Reverse colors and text labels to display the last value at the top.
    colors = colors[::-1]
    cell_text.reverse()

    # Add a table at the bottom of the axes
    the_table = plt.table(cellText=cell_text,
    rowLabels=rows,
    rowColours=colors,
    colLabels=columns,
    loc='bottom')

    # Adjust layout to make room for the table:
    plt.subplots_adjust(left=0.2, bottom=0.2)

    plt.ylabel("Loss in ${0}'s".format(value_increment))
    plt.yticks(values * value_increment, ['%d' % val for val in values])
    plt.xticks([])
    plt.title('Loss by Disaster')

    plt.show()

    ../_images/table_demo1.png

    11、散点图(Scatter)

    scatter()命令使用(可选)大小和颜色参数生成散点图。此示例绘制了Google股票价格的变化情况,通过标记:反映交易量的尺寸和随时间变化的颜色。这里,alpha属性用于制作半透明的圆形标记。

     import numpy as np
    import matplotlib.pyplot as plt

    import matplotlib.cbook as cbook

    # Load a numpy record array from yahoo csv data with fields date,
    # open, close, volume, adj_close from the mpl-data/example directory.
    # The record array stores python datetime.date as an object array in
    # the date column
    datafile = cbook.get_sample_data('goog.npy')
    try:
    # Python3 cannot load python2 .npy files with datetime(object) arrays
    # unless the encoding is set to bytes. However this option was
    # not added until numpy 1.10 so this example will only work with
    # python 2 or with numpy 1.10 and later
    price_data = np.load(datafile, encoding='bytes').view(np.recarray)
    except TypeError:
    price_data = np.load(datafile).view(np.recarray)
    price_data = price_data[-250:] # get the most recent 250 trading days

    delta1 = np.diff(price_data.adj_close)/price_data.adj_close[:-1]

    # Marker size in units of points^2
    volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2
    close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2]

    fig, ax = plt.subplots()
    ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5)

    ax.set_xlabel(r'$Delta_i$', fontsize=15)
    ax.set_ylabel(r'$Delta_{i+1}$', fontsize=15)
    ax.set_title('Volume and percent change')

    ax.grid(True)
    fig.tight_layout()

    plt.show()

    ../_images/scatter_demo2.png

    12、滑块示例(Slider)

    Matplotlib具有独立于所用图形用户界面的基本GUI控件,允许您编写跨GUI图形的控件。这个示例很有意思,大家多看看,详情请参阅matplotlib.widgets和 widget examples

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.widgets import Slider, Button, RadioButtons

    fig, ax = plt.subplots()
    plt.subplots_adjust(left=0.25, bottom=0.25)
    t = np.arange(0.0, 1.0, 0.001)
    a0 = 5
    f0 = 3
    s = a0*np.sin(2*np.pi*f0*t)
    l, = plt.plot(t, s, lw=2, color='red')
    plt.axis([0, 1, -10, 10])

    axcolor = 'lightgoldenrodyellow'
    axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)

    sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
    samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)


    def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp*np.sin(2*np.pi*freq*t))
    fig.canvas.draw_idle()
    sfreq.on_changed(update)
    samp.on_changed(update)

    resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')


    def reset(event):
    sfreq.reset()
    samp.reset()
    button.on_clicked(reset)

    rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
    radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)


    def colorfunc(label):
    l.set_color(label)
    fig.canvas.draw_idle()
    radio.on_clicked(colorfunc)

    plt.show()

     ../_images/slider_demo.png

    13、填充演示(Fill)

        fill()命令让您绘制填充曲线和多边形:

    import numpy as np
    import matplotlib.pyplot as plt

    x = np.linspace(0, 1, 500)
    y = np.sin(4 * np.pi * x) * np.exp(-5 * x)

    fig, ax = plt.subplots()

    ax.fill(x, y, zorder=10)
    ax.grid(True, zorder=5)
    plt.show()

    ../_images/fill_demo2.png

    14、日期刻度示例(dates模块)

        您可以绘制日期数据,包括主要和次要刻度以及两种自定义刻度格式。

     import datetime

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import matplotlib.cbook as cbook

    years = mdates.YearLocator() # every year
    months = mdates.MonthLocator() # every month
    yearsFmt = mdates.DateFormatter('%Y')

    datafile = cbook.get_sample_data('goog.npy')
    try:
    r = np.load(datafile, encoding='bytes').view(np.recarray)
    except TypeError:
    r = np.load(datafile).view(np.recarray)

    fig, ax = plt.subplots()
    ax.plot(r.date, r.adj_close)


    # format the ticks
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)

    datemin = datetime.date(r.date.min().year, 1, 1)
    datemax = datetime.date(r.date.max().year + 1, 1, 1)
    ax.set_xlim(datemin, datemax)


    # format the coords message box
    def price(x):
    return '$%1.2f' % x
    ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
    ax.format_ydata = price
    ax.grid(True)

    # rotates and right aligns the x labels, and moves the bottom of the
    # axes up to make room for them
    fig.autofmt_xdate()

    plt.show()

    ../_images/date_demo1.png

    请参阅matplotlib.tickermatplotlib.dates了解详细信息和用法。

    15、对数图

        函数semilogx(), semilogy()和 loglog()简化了对数图的创建。

    import numpy as np
    import matplotlib.pyplot as plt

    plt.subplots_adjust(hspace=0.4)
    t = np.arange(0.01, 20.0, 0.01)

    # log y axis
    plt.subplot(221)
    plt.semilogy(t, np.exp(-t/5.0))
    plt.title('semilogy')
    plt.grid(True)

    # log x axis
    plt.subplot(222)
    plt.semilogx(t, np.sin(2*np.pi*t))
    plt.title('semilogx')
    plt.grid(True)

    # log x and y axis
    plt.subplot(223)
    plt.loglog(t, 20*np.exp(-t/10.0), basex=2)
    plt.grid(True)
    plt.title('loglog base 2 on x')

    # with errorbars: clip non-positive values
    ax = plt.subplot(224)
    ax.set_xscale("log", nonposx='clip')
    ax.set_yscale("log", nonposy='clip')

    x = 10.0**np.linspace(0.0, 2.0, 20)
    y = x**2.0
    plt.errorbar(x, y, xerr=0.1*x, yerr=5.0 + 0.75*y)
    ax.set_ylim(ymin=0.1)
    ax.set_title('Errorbars go negative')

    plt.show()

    ../_images/log_demo2.png

    16、极图(Polar)

          polar()命令生成极地图。

    import numpy as np
    import matplotlib.pyplot as plt


    r = np.arange(0, 2, 0.01)
    theta = 2 * np.pi * r

    ax = plt.subplot(111, projection='polar')
    ax.plot(theta, r)
    ax.set_rmax(2)
    ax.set_rticks([0.5, 1, 1.5, 2]) # less radial ticks
    ax.set_rlabel_position(-22.5) # get radial labels away from plotted line
    ax.grid(True)

    ax.set_title("A line plot on a polar axis", va='bottom')
    plt.show()

    ../_images/polar_demo.png

    17、自动图例(Legend)

        legend()命令自动生成图例,并带有与MATLAB兼容的图例布局命令。

    import numpy as np
    import matplotlib.pyplot as plt

    # Make some fake data.
    a = b = np.arange(0, 3, .02)
    c = np.exp(a)
    d = c[::-1]

    # Create plots with pre-defined labels.
    fig, ax = plt.subplots()
    ax.plot(a, c, 'k--', label='Model length')
    ax.plot(a, d, 'k:', label='Data length')
    ax.plot(a, c + d, 'k', label='Total message length')

    legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')

    # Put a nicer background color on the legend.
    legend.get_frame().set_facecolor('#00FFCC')

    plt.show()

    ../_images/legend_demo6.png

    18、数学表达式(Mathtext模块)

         matplotlib内部mathtext引擎现在支持许多TeX表达式。mathtext模块使用FreeType 和DejaVu,BaKoMa计算机现代版或STIX 字体提供TeX风格的数学表达式请参阅matplotlib.mathtext模块了解更多详情。

    from __future__ import print_function
    import matplotlib.pyplot as plt
    import os
    import sys
    import re
    import gc

    # Selection of features following "Writing mathematical expressions" tutorial
    mathtext_titles = {
    0: "Header demo",
    1: "Subscripts and superscripts",
    2: "Fractions, binomials and stacked numbers",
    3: "Radicals",
    4: "Fonts",
    5: "Accents",
    6: "Greek, Hebrew",
    7: "Delimiters, functions and Symbols"}
    n_lines = len(mathtext_titles)

    # Randomly picked examples
    mathext_demos = {
    0: r"$W^{3eta}_{delta_1 ho_1 sigma_2} = "
    r"U^{3eta}_{delta_1 ho_1} + frac{1}{8 pi 2} "
    r"int^{alpha_2}_{alpha_2} d alpha^prime_2 left[frac{ "
    r"U^{2eta}_{delta_1 ho_1} - alpha^prime_2U^{1eta}_"
    r"{ ho_1 sigma_2} }{U^{0eta}_{ ho_1 sigma_2}} ight]$",

    1: r"$alpha_i > eta_i, "
    r"alpha_{i+1}^j = { m sin}(2pi f_j t_i) e^{-5 t_i/ au}, "
    r"ldots$",

    2: r"$frac{3}{4}, inom{3}{4}, stackrel{3}{4}, "
    r"left(frac{5 - frac{1}{x}}{4} ight), ldots$",

    3: r"$sqrt{2}, sqrt[3]{x}, ldots$",

    4: r"$mathrm{Roman} , mathit{Italic} , mathtt{Typewriter} "
    r"mathrm{or} mathcal{CALLIGRAPHY}$",

    5: r"$acute a, ar a, reve a, dot a, ddot a, grave a, "
    r"hat a, ilde a, vec a, widehat{xyz}, widetilde{xyz}, "
    r"ldots$",

    6: r"$alpha, eta, chi, delta, lambda, mu, "
    r"Delta, Gamma, Omega, Phi, Pi, Upsilon, abla, "
    r"aleph, eth, daleth, gimel, ldots$",

    7: r"$coprod, int, oint, prod, sum, "
    r"log, sin, approx, oplus, star, varpropto, "
    r"infty, partial, Re, leftrightsquigarrow, ldots$"}


    def doall():
    # Colors used in mpl online documentation.
    mpl_blue_rvb = (191./255., 209./256., 212./255.)
    mpl_orange_rvb = (202/255., 121/256., 0./255.)
    mpl_grey_rvb = (51./255., 51./255., 51./255.)

    # Creating figure and axis.
    plt.figure(figsize=(6, 7))
    plt.axes([0.01, 0.01, 0.98, 0.90], facecolor="white", frameon=True)
    plt.gca().set_xlim(0., 1.)
    plt.gca().set_ylim(0., 1.)
    plt.gca().set_title("Matplotlib's math rendering engine",
    color=mpl_grey_rvb, fontsize=14, weight='bold')
    plt.gca().set_xticklabels("", visible=False)
    plt.gca().set_yticklabels("", visible=False)

    # Gap between lines in axes coords
    line_axesfrac = (1. / (n_lines))

    # Plotting header demonstration formula
    full_demo = mathext_demos[0]
    plt.annotate(full_demo,
    xy=(0.5, 1. - 0.59*line_axesfrac),
    xycoords='data', color=mpl_orange_rvb, ha='center',
    fontsize=20)

    # Plotting features demonstration formulae
    for i_line in range(1, n_lines):
    baseline = 1. - (i_line)*line_axesfrac
    baseline_next = baseline - line_axesfrac*1.
    title = mathtext_titles[i_line] + ":"
    fill_color = ['white', mpl_blue_rvb][i_line % 2]
    plt.fill_between([0., 1.], [baseline, baseline],
    [baseline_next, baseline_next],
    color=fill_color, alpha=0.5)
    plt.annotate(title,
    xy=(0.07, baseline - 0.3*line_axesfrac),
    xycoords='data', color=mpl_grey_rvb, weight='bold')
    demo = mathext_demos[i_line]
    plt.annotate(demo,
    xy=(0.05, baseline - 0.75*line_axesfrac),
    xycoords='data', color=mpl_grey_rvb,
    fontsize=16)

    for i in range(n_lines):
    s = mathext_demos[i]
    print(i, s)
    plt.show()

    if '--latex' in sys.argv:
    # Run: python mathtext_examples.py --latex
    # Need amsmath and amssymb packages.
    fd = open("mathtext_examples.ltx", "w")
    fd.write("\documentclass{article} ")
    fd.write("\usepackage{amsmath, amssymb} ")
    fd.write("\begin{document} ")
    fd.write("\begin{enumerate} ")

    for i in range(n_lines):
    s = mathext_demos[i]
    s = re.sub(r"(?<!\)$", "$$", s)
    fd.write("\item %s " % s)

    fd.write("\end{enumerate} ")
    fd.write("\end{document} ")
    fd.close()

    os.system("pdflatex mathtext_examples.ltx")
    else:
    doall()

    ../_images/mathtext_examples_01_00.png

        Matplotlib的mathtext基础架构是一个独立的实现,不需要在您的计算机上安装TeX或任何外部软件包。请参阅编写数学表达式的教程

    19、数学文本的TeX渲染(usetex)

    尽管matplotlib的内部数学渲染引擎非常强大,但有时您需要TeX。Matplotlib使用usetex选项支持对字符串进行外部TeX呈现。

    import numpy as np
    import matplotlib.pyplot as plt


    # Example data
    t = np.arange(0.0, 1.0 + 0.01, 0.01)
    s = np.cos(4 * np.pi * t) + 2

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    plt.plot(t, s)

    plt.xlabel(r' extbf{time} (s)')
    plt.ylabel(r' extit{voltage} (mV)',fontsize=16)
    plt.title(r"TeX is Number "
    r"$displaystylesum_{n=1}^inftyfrac{-e^{ipi}}{2^n}$!",
    fontsize=16, color='gray')
    # Make room for the ridiculously large title.
    plt.subplots_adjust(top=0.8)

    plt.savefig('tex_demo')
    plt.show()

    ../_images/tex_demo1.png

    20、EEG 演示(pbrain)

    您可以将matplotlib嵌入到pygtk,wx,Tk或Qt应用程序中。这是一个名为pbrain的EEG查看器屏幕截图。

    ../_images/eeg_small.png

    较低的轴用specgram() 绘制其中一个EEG通道的光谱图。

    有关如何在不同工具包中嵌入matplotlib的示例,请参阅:

    21、XKCD-风格草图

        matplotlib支持绘制 xkcd 风格

    import numpy as np
    import matplotlib.pyplot as plt

    with plt.xkcd():
    # Based on "Stove Ownership" from XKCD by Randall Monroe
    # http://xkcd.com/418/

    fig = plt.figure()
    ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    plt.xticks([])
    plt.yticks([])
    ax.set_ylim([-30, 10])

    data = np.ones(100)
    data[70:] -= np.arange(30)

    plt.annotate(
    'THE DAY I REALIZED I COULD COOK BACON WHENEVER I WANTED',
    xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))

    plt.plot(data)

    plt.xlabel('time')
    plt.ylabel('my overall health')
    fig.text(
    0.5, 0.05,
    '"Stove Ownership" from xkcd by Randall Monroe',
    ha='center')

    # Based on "The Data So Far" from XKCD by Randall Monroe
    # http://xkcd.com/373/

    fig = plt.figure()
    ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
    ax.bar([0, 1], [0, 100], 0.25)
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_xticks([0, 1])
    ax.set_xlim([-0.5, 1.5])
    ax.set_ylim([0, 110])
    ax.set_xticklabels(['CONFIRMED BY EXPERIMENT', 'REFUTED BY EXPERIMENT'])
    plt.yticks([])

    plt.title("CLAIMS OF SUPERNATURAL POWERS")

    fig.text(
    0.5, 0.05,
    '"The Data So Far" from xkcd by Randall Monroe',
    ha='center')

    plt.show()

    ../_images/xkcd_001.png
    ../_images/xkcd_011.png
  • 相关阅读:
    ASP.NET Core应用程序容器化、持续集成与Kubernetes集群部署(二)
    ASP.NET Core应用程序容器化、持续集成与Kubernetes集群部署(一)
    2018年9月15日上海MVP线下技术交流活动简报
    在.NET中使用机器学习API(ML.NET)实现化学分子式数据格式的判定
    使用Roslyn的C#语言服务实现UML类图的自动生成
    ASP.NET Core应用程序的参数配置及使用
    微软最有价值专家(Microsoft MVP)项目经验分享
    漫谈单体架构与微服务架构(上):单体架构
    ASP.NET Core Web API下事件驱动型架构的实现(五):在微服务中使用自我监听模式保证数据库更新与消息派发的可靠性
    使用C#读写结构化的二进制文件
  • 原文地址:https://www.cnblogs.com/cjtds/p/9073143.html
Copyright © 2011-2022 走看看