用python 画k线(python怎么画k线)

jijinwang


散点图

import numpy as np\nimport matplotlib.pyplot as plt\n\ncountries = ['Brazil', 'Madagascar', 'S. Korea', 'United States',\n 'Ethiopia', 'Pakistan', 'China', 'Belize']\n# Birth rate per 1000 population\nbirth_rate = [16.4, 33.5, 9.5, 14.2, 38.6, 30.2, 13.5, 23.0]\n# Life expectancy at birth, years\nlife_expectancy = [73.7, 64.3, 81.3, 78.8, 63.0, 66.4, 75.2, 73.7]\n# Per person income fixed to US Dollars in 2000\nGDP = np.array([4800, 240, 16700, 37700, 230, 670, 2640, 3490])\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n# Some random colours: \ncolours = range(len(countries))\nax.scatter(birth_rate, life_expectancy, c=colours, s=GDP/20)\nax.set_xlim(5, 45)\nax.set_ylim(60, 85)\nax.set_xlabel('Birth rate per 1000 population')\nax.set_ylabel('Life expectancy at birth (years)')\n\nplt.show()\n


要给气泡标上标签,在显示图形之前添加以下代码:

offset = 1\nfor x, y, s, country in zip(birth_rate, life_expectancy, GDP, countries):\n ax.text(x+offset, y, country, va='center')\n


曲线图

数据eg7-marriage-ages.txt

Median age at First Marriage, 1890-2010\nSource: U.S. Bureau of the Census, www.census.gov\nYear Men Women\n1890 26.1 22.0\n1900 25.9 21.9\n1910 25.1 21.6\n1920 24.6 21.2\n1930 24.3 21.3\n1940 24.3 21.5\n1950 22.8 20.3\n1960 22.8 20.3\n1970 23.2 20.8\n1980 24.7 22.0\n1990 26.1 23.9\n2000 26.8 25.1\n2010 28.2 26.1

import numpy as np\nimport matplotlib.pyplot as plt\n\nyear, age_m, age_f = np.loadtxt('eg7-marriage-ages.txt', unpack=True,skiprows=3)\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n# Plot ages with male or female symbols as markers\nax.plot(year, age_m, marker='$\\u2642$', markersize=14, c='blue', lw=2,\n mfc='blue', mec='blue')\nax.plot(year, age_f, marker='$\\u2640$', markersize=14, c='magenta', lw=2,\n mfc='magenta', mec='magenta')\nax.grid()\n\nax.set_xlabel('Year')\nax.set_ylabel('Age')\nax.set_title('Median age at first marriage in the US, 1890 - 2010')\n\nplt.show()\n




以下程序将这些数据绘制在一组轴上,每个轴具有不同的线型。

import matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\ncities = ['Boston', 'Houston', 'Detroit', 'San Jose', 'Phoenix']\n# line styles: solid, dashes, dots, dash-dots, and dot-dot-dash\nlinestyles = [{'ls': '-'}, {'ls': '--'}, {'ls': ':'}, {'ls': '-.'},\n {'dashes': [2, 4, 2, 4, 8, 4]}]\n\nfor i, city in enumerate(cities):\n filename = '{}.tsv'.format(city.lower()).replace(' ', '_')\n yr, pop = np.loadtxt(filename, unpack=True)\n line, = ax.plot(yr, pop/1.e6, label=city, color='k', **linestyles[i])\nax.legend(loc='upper left')\nax.set_xlim(1800, 2020)\nax.set_xlabel('Year')\nax.set_ylabel('Population (millions)')\nplt.show()\n

请注意如何使用城市名称来推断相应的文件名。


\n\n\n\n\n\n\n\n\n\n

\n\n\n\n\n\n\n\n\n\n



指数衰减的寿命

下面的程序绘制了用寿命标记的描述的指数衰减,(nτ for n=0,1,⋯)这样,在每个寿命之后,y的值下降了一个因子e。

import numpy as np\nimport matplotlib.pyplot as plt\n\n# Initial value of y at t=0, lifetime in s\nN, tau = 10000, 28\n# Maximum time to consider (s)\ntmax = 100\n# A suitable grid of time points, and the exponential decay itself\nt = np.linspace(0, tmax, 1000)\ny = N * np.exp(-t/tau)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(t, y)\n\n# The number of lifetimes that fall within the plotted time interval\nntau = tmax // tau + 1\n# xticks at 0, tau, 2*tau, ..., ntau*tau; yticks at the corresponding y-values\nxticks = [i*tau for i in range(ntau)]\nyticks = [N * np.exp(-i) for i in range(ntau)]\nax.set_xticks(xticks)\nax.set_yticks(yticks)\n\n# xtick labels: 0, tau, 2tau, ...\nxtick_labels = [r'$0$', r'$\\tau$'] + [r'${}\\tau$'.format(k) for k in range(2,ntau)]\nax.set_xticklabels(xtick_labels)\n# corresponding ytick labels: N, N/e, N/2e, ...\nytick_labels = [r'$N$',r'$N/e$'] + [r'$N/{}e$'.format(k) for k in range(2,ntau)]\nax.set_yticklabels(ytick_labels)\n\nax.set_xlabel(r'$t\\;/\\mathrm{s}$')\nax.set_ylabel(r'$y$')\nax.grid()\nplt.show()\n

x轴标记被设置为1,τ,2τ,…y轴标记为N,N/e,N/2e,…

注意,标记序列的长度必须与所需的标记值列表的长度相对应。


注释图

另一个注释图的例子,这次是英国石油公司(BP plc, LSE: BP)的股价,其中添加了一些值得注意的事件。

数据来源 https://consent.yahoo.com/v2/collectConsent?sessionId=4_cc-session_adac4516-5607-4dd8-a394-f9ca47541e5b

import datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import strpdate2num\nfrom datetime import datetime\n\ndef date_to_int(s):\n epoch = datetime(year=1970, month=1, day=1)\n date = datetime.strptime(s, '%Y-%m-%d')\n return (date - epoch).days\n\ndef bindate_to_int(bs):\n return date_to_int(bs.decode('ascii'))\n\ndt = np.dtype([('daynum','i8'), ('close', 'f8')])\nshare_price = np.loadtxt('bp-share-prices.csv', skiprows=1, delimiter=',',\n usecols=(0,4), converters={0: bindate_to_int},\n dtype=dt)\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(share_price['daynum'], share_price['close'], c='g')\nax.fill_between(share_price['daynum'], 0, share_price['close'], facecolor='g',\n alpha=0.5)\n\ndaymin, daymax = share_price['daynum'].min(), share_price['daynum'].max()\nax.set_xlim(daymin, daymax)\n\nprice_max = share_price['close'].max()\n\ndef get_xy(date):\n """ Return the (x,y) coordinates of the share price on a given date. """\n x = date_to_int(date)\n return share_price[np.where(share_price['daynum']==x)][0]\n\n# A horizontal arrow and label\nx,y = get_xy('1999-10-01')\nax.annotate('Share split', (x,y), xytext = (x+1000,y), va='center',\n arrowprops=dict(facecolor='black', shrink=0.05))\n# A vertical arrow and label\nx,y = get_xy('2010-04-20')\nax.annotate('Deepwater Horizon\\noil spill', (x,y), xytext = (x,price_max*0.9),\n arrowprops=dict(facecolor='black', shrink=0.05), ha='center')\n\nyears = range(1989,2015,2)\nax.set_xticks([date_to_int('{:4d}-01-01'.format(year)) for year in years])\nax.set_xticklabels(years, rotation=90)\n\nplt.show()\n


设置置信区域

import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\n\nFEMALE, MALE = 0, 1\ndt = np.dtype([('mass', 'f8'), ('height', 'f8'), ('gender', 'i2')])\ndata = np.loadtxt('body.dat.txt', usecols=(22,23,24), dtype=dt)\n\nfig, ax = plt.subplots()\n\ndef get_cov_ellipse(cov, centre, nstd, **kwargs):\n """\n Return a matplotlib Ellipse patch representing the covariance matrix\n cov centred at centre and scaled by the factor nstd.\n\n """\n\n # Find and sort eigenvalues and eigenvectors into descending order\n eigvals, eigvecs = np.linalg.eigh(cov)\n order = eigvals.argsort()[::-1]\n eigvals, eigvecs = eigvals[order], eigvecs[:, order]\n\n # The anti-clockwise angle to rotate our ellipse by \n vx, vy = eigvecs[:,0][0], eigvecs[:,0][1]\n theta = np.arctan2(vy, vx)\n\n # Width and height of ellipse to draw\n width, height = 2 * nstd * np.sqrt(eigvals)\n return Ellipse(xy=centre, width=width, height=height,\n angle=np.degrees(theta), **kwargs)\n\nlabels, colours =['Female', 'Male'], ['magenta', 'blue']\nfor gender in (FEMALE, MALE):\n sdata = data[data['gender']==gender]\n height_mean = np.mean(sdata['height'])\n mass_mean = np.mean(sdata['mass'])\n cov = np.cov(sdata['mass'], sdata['height'])\n ax.scatter(sdata['height'], sdata['mass'], color=colours[gender],\n label=labels[gender], s=3)\n e = get_cov_ellipse(cov, (height_mean, mass_mean), 3,\n fc=colours[gender], alpha=0.4)\n ax.add_artist(e)\n\nax.set_xlim(140, 210)\nax.set_ylim(30, 120)\nax.set_xlabel('Height /cm')\nax.set_ylabel('Mass /kg')\nax.legend(loc='upper left', scatterpoints=1)\nplt.show()\n

该函数np.arctan2返回“双参数反正切”:np.arctan2(y, x)是正切之间的弧度角x-轴和点 ( x , y).


刻度线自定义

下面的程序创建一个带有主要和次要刻度线的绘图,自定义为比默认值更粗和更宽,主要刻度线指向绘图区域的内外。

import numpy as np\nimport matplotlib.pyplot as plt\n\n# A selection of functions on rn abcissa points for 0 <= x < 1\nrn = 100\nrx = np.linspace(0, 1, rn, endpoint=False)\n\ndef tophat(rx):\n """ Top hat function: y = 1 for x < 0.5, y=0 for x >= 0.5 """\n ry = np.ones(rn)\n ry[rx>=0.5]=0\n return ry\n\n# A dictionary of functions to choose from\nry = {'half-sawtooth': lambda rx: rx.copy(),\n 'top-hat': tophat,\n 'sawtooth': lambda rx: 2 * np.abs(rx-0.5)}\n\n# Repeat the chosen function nrep times\nnrep = 4\nx = np.linspace(0, nrep, nrep*rn, endpoint=False)\ny = np.tile(ry['top-hat'](rx), nrep)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x,y, 'k', lw=2)\n# Add a bit of padding around the plotted line to aid visualization\nax.set_ylim(-0.1,1.1)\nax.set_xlim(x[0]-0.5, x[-1]+0.5)\n# Customize the tick marks and turn the grid on\nax.minorticks_on()\nax.tick_params(which='major', length=10, width=2, direction='inout')\nax.tick_params(which='minor', length=5, width=2, direction='in')\nax.grid(which='both')\nplt.show()\n

该np.tile方法通过重复给定的数组nrep次数来构造一个数组。要绘制不同的周期函数,请在此处选择'half-sawtooth'或'sawtooth'。


饼图

温室气体排放

以下程序按“碳当量”的质量描述了温室气体的排放量。数据来自 2007 IPCC 报告

import numpy as np\nimport matplotlib.pyplot as plt\n\n# Annual greenhouse gas emissions, billion tons carbon equivalent (GtCe)\ngas_emissions = np.array([(r'$\\mathrm{CO_2}$-d', 2.2),\n (r'$\\mathrm{CO_2}$-f', 8.0),\n ('Nitrous\\nOxide', 1.0),\n ('Methane', 2.3),\n ('Halocarbons', 0.1)],\n dtype=[('source', 'U17'), ('emission', 'f4')])\n\n# 5 colours beige\ncolours = ['#C7B299', '#A67C52', '#C69C6E', '#754C24', '#534741']\n\nexplode = [0, 0, 0.1, 0, 0]\n\nfig, ax = plt.subplots()\nax.axis('equal') # So our pie looks round!\nax.pie(gas_emissions['emission'], colors=colours, shadow=True, startangle=90,\n explode=explode, labels=gas_emissions['source'], autopct='%.1f%%',\n pctdistance=1.15, labeldistance=1.3)\n\nplt.show()\n

百分比值格式化为一位小数 ( autopct='%.1f%%')


分类柱状图

德国的可再生能源

该文件germany-energy-sources.txt包含 1990 年至 2018 年德国生产的可再生电力数据:

Renewable electricity generation in Germany in GWh (million kWh)\nYear Hydro Wind Biomass Photovoltaics\n2018 17974 109951 50851 45784\n2017 20150 105693 50917 39401\n2016 20546 79924 50928 38098\n2015 18977 80624 50326 38726\n2014 19587 58497 48287 36056\n2013 22998 52737 45513 31010\n2012 21755 51680 43203 26380\n2011 17671 49857 36891 19599\n2010 20953 38547 33924 11729\n2009 19031 39420 30886 6583\n2008 20443 41385 28014 4420\n2007 21170 40507 24616 3075\n2006 20031 31324 18934 2220\n2005 19638 27774 14706 1282\n2004 20745 26019 10636 557\n2003 18322 19087 8948 313\n2002 23124 16102 6048 162\n2001 22733 10719 5214 76\n2000 21732 9703 4731 60\n1999 19647 5639 3585 30\n1998 17216 4579 3256 35\n1997 17357 3025 2273 18\n1996 21957 2073 2098 12\n1995 21780 1530 2010 7\n1994 19930 927 1875 7\n1993 17878 612 1635 3\n1992 17397 281 1558 4\n1991 14891 102 1471 1\n1990 17426 72 1435 1


Renewable electricity generation in Germany in GWh (million kWh)\nYear Hydro Wind Biomass Photovoltaics\n2013 21200 49800 47800 29300\n2012 21793 50670 43350 26380\n2011 17671 48883 37603 19559\n...\n

下面的程序将这些数据绘制为堆积条形图,使用 Matplotlib 的填充图案来区分不同的来源。

import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt('germany-energy-sources.txt', skiprows=2, dtype='f8')\nyears = data[:,0]\nn = len(years)\n\n# GWh to TWh\ndata[:,1:] /= 1000\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nsources = ('Hydroelectric', 'Wind', 'Biomass', 'Photovoltaics')\nhatch = ['oo', '', 'xxxx', '//']\nbottom = np.zeros(n)\nbars = [None]*n\nfor i, source in enumerate(sources):\n bars[i] = ax.bar(years, bottom=bottom, height=data[:,i+1], color='w',\n hatch=hatch[i], align='center', edgecolor='k')\n bottom += data[:,i+1]\n\nax.set_xticks(years)\nplt.xticks(rotation=90)\nax.set_xlim(1989, 2019)\nax.set_ylabel('Renewable Electricity (TWh)')\nax.set_title('Renewable Electricity Generation in Germany, 1990-2018')\nplt.legend(bars, sources, loc='best')\nplt.show()\n

要包含图例,每个条形图对象必须存储在一个列表bars中,该列表通过ax.legend相应的标签序列传递给方法sources。


子图

该代码生成了10个子图,描述了n=0,1,⋯⋯9时sin(nπx)的图形。子地块间距的配置使它们在垂直方向上相互“碰撞”。

import numpy as np\nimport matplotlib.pyplot as plt\n\nnrows = 10\nfig, axes = plt.subplots(nrows,1)\n# Zero vertical space between subplots\nfig.subplots_adjust(hspace=0)\n\nx = np.linspace(0,1,1000)\nfor i in range(nrows):\n # n=nrows for the top subplot, n=0 for the bottom subplot\n n = nrows - i\n axes[i].plot(x, np.sin(n * np.pi * x), 'k', lw=2)\n # We only want ticks on the bottom of each subplot\n axes[i].xaxis.set_ticks_position('bottom')\n if i < nrows-1:\n # Set ticks at the nodes (zeros) of our sine functions\n axes[i].set_xticks(np.arange(0, 1, 1/n))\n # We only want labels on the bottom subplot xaxis\n axes[i].set_xticklabels('')\n axes[i].set_yticklabels('')\nplt.show()\n





电磁频谱的描述

下面的程序使用text、axvline、axhline和axvspan注释一个简单的波图,以指示电磁频谱的不同区域。

import numpy as np\nimport matplotlib.pyplot as plt\n\n# wavelength range, nm\nlmin, lmax = 250, 1000\nx = np.linspace(lmin, lmax, 1000)\n# A wave with a smoothly increasing wavelength\nwv = (np.sin(10 * np.pi * x / (lmax+lmin-x)))[::-1]\n\nfig = plt.figure()\nax = fig.add_subplot(111, facecolor='k')\nax.plot(x, wv, c='w', lw=2)\nax.set_xlim(250,1000)\nax.set_ylim(-2,2)\n\n# Label and delimit the different regions of the electromagnetic spectrum\nax.text(310, 1.5, 'UV', color='w', fontdict={'fontsize': 20})\nax.text(530, 1.5, 'Visible', color='k', fontdict={'fontsize': 20})\nax.annotate('', (400, 1.3), (750, 1.3), arrowprops={'arrowstyle': '<|-|>',\n 'color': 'w', 'lw': 2})\nax.text(860, 1.5, 'IR', color='w', fontdict={'fontsize': 20})\nax.axvline(400, -2, 2, c='w', ls='--')\nax.axvline(750, -2, 2, c='w', ls='--')\n# Horizontal "axis" across the centre of the wave\nax.axhline(c='w')\n# Ditch the y-axis ticks and labels; label the x-axis\nax.yaxis.set_visible(False)\nax.set_xlabel(r'$\\lambda\\;/\\mathrm{nm}$')\n\n# Finally, add some colourful rectangles representing a rainbow in the\n# visible region of the spectrum.\n# Dictionary mapping of wavelength regions (nm) to approximate RGB values\nrainbow_rgb = { (400, 440): '#8b00ff', (440, 460): '#4b0082',\n (460, 500): '#0000ff', (500, 570): '#00ff00',\n (570, 590): '#ffff00', (590, 620): '#ff7f00',\n (620, 750): '#ff0000'}\nfor wv_range, rgb in rainbow_rgb.items():\n ax.axvspan(*wv_range, color=rgb, ec='none', alpha=1)\nplt.show()\n


五颜六色的几何图形


import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon, Circle, Rectangle\n\nred, blue, yellow, green = '#ff0000', '#0000ff', '#ffff00', '#00ff00'\nsquare = Rectangle((0.7, 0.1), 0.25, 0.25, facecolor=red)\ncircle = Circle((0.8, 0.8), 0.15, facecolor=blue)\ntriangle = Polygon(((0.05,0.1), (0.396,0.1), (0.223, 0.38)), fc=yellow)\nrhombus = Polygon(((0.5,0.2), (0.7,0.525), (0.5,0.85), (0.3,0.525)), fc=green)\n\nfig = plt.figure()\nax = fig.add_subplot(111, facecolor='k', aspect='equal')\nfor shape in (square, circle, triangle, rhombus):\n ax.add_artist(shape)\nax.xaxis.set_visible(False)\nax.yaxis.set_visible(False)\n\nplt.show()\n



电偶极子的静电势

下面的代码给出了p=(qd,0,0)的电偶极子在(x,y)平面的电势等势面图,其中q=1.602×10−19C,d=1pm,使用点偶极近似。

import numpy as np\nimport matplotlib.pyplot as plt\n\n# Dipole charge (C), Permittivity of free space (F.m-1)\nq, eps0 = 1.602e-19, 8.854e-12\n# Dipole +q, -q distance (m) and a convenient combination of parameters\nd = 1.e-12\nk = 1/4/np.pi/eps0 * q * d\n\n# Cartesian axis system with origin at the dipole (m)\nX = np.linspace(-5e-11, 5e-11, 1000)\nY = X.copy()\nX, Y = np.meshgrid(X, Y)\n\n# Dipole electrostatic potential (V), using point dipole approximation\nPhi = k * X / np.hypot(X, Y)**3\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n# Draw contours at values of Phi given by levels\nlevels = np.array([10**pw for pw in np.linspace(0,5,20)])\nlevels = sorted(list(-levels) + list(levels))\n# Monochrome plot of potential\nax.contour(X, Y, Phi, levels=levels, colors='k', linewidths=2)\nplt.show()\n



简单的等高线图

import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nX = np.linspace(0,1,100)\nY = X.copy()\nX, Y = np.meshgrid(X, Y)\nalpha = np.radians(25)\ncX, cY = 0.5, 0.5\nsigX, sigY = 0.2, 0.3\nrX = np.cos(alpha) * (X-cX) - np.sin(alpha) * (Y-cY) + cX\nrY = np.sin(alpha) * (X-cX) + np.cos(alpha) * (Y-cY) + cY\n\nZ = (rX-cX)*np.exp(-((rX-cX)/sigX)**2) * np.exp(- ((rY-cY)/sigY)**2)\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n# Reversed Greys colourmap for filled contours\ncpf = ax.contourf(X,Y,Z, 20, cmap=cm.Greys_r)\n# Set the colours of the contours and labels so they're white where the\n# contour fill is dark (Z < 0) and black where it's light (Z >= 0)\ncolours = ['w' if level<0 else 'k' for level in cpf.levels]\ncp = ax.contour(X, Y, Z, 20, colors=colours)\nax.clabel(cp, fontsize=12, colors=colours)\nplt.show()\n


分形图

巴恩斯利蕨类是一种分形,类似于蕨类中的黑色脾苔种。它是通过在(x,y)平面上绘制从(0,0)开始的一系列点来构建的,这些点由以下的仿射变换f1, f2, f3和f4生成,其中每个变换应用于前一个点,并随机选择概率p1=0.01, p2=0.85, p3=0.07和p4=0.07。.



import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nf1 = lambda x,y: (0., 0.16*y)\nf2 = lambda x,y: (0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6)\nf3 = lambda x,y: (0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6)\nf4 = lambda x,y: (-0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44)\nfs = [f1, f2, f3, f4]\n\nnpts = 50000\n# Canvas size (pixels)\nwidth, height = 300, 300\naimg = np.zeros((width, height))\n\nx, y = 0, 0\nfor i in range(npts):\n # Pick a random transformation and apply it\n f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07])\n x, y = f(x,y)\n # Map (x,y) to pixel coordinates.\n # NB we "know" that -2.2 < x < 2.7 and 0 <= y < 10\n\n ix, iy = int(width / 2 + x * width / 10), int(y * height / 12)\n # Set this point of the array to 1 to mark a point in the fern\n aimg[iy, ix] = 1\n\nplt.imshow(aimg[::-1,:], cmap=cm.Greens)\nplt.show()\n


三维图——螺旋线

import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nn = 1000\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# Plot a helix along the x-axis\ntheta_max = 8 * np.pi\ntheta = np.linspace(0, theta_max, n)\nx = theta\nz = np.sin(theta)\ny = np.cos(theta)\nax.plot(x, y, z, 'b', lw=2)\n\n# An line through the centre of the helix\nax.plot((-theta_max*0.2, theta_max * 1.2), (0,0), (0,0), color='k', lw=2)\n# sin/cos components of the helix (e.g. electric and magnetic field\n# components of a circularly-polarized electromagnetic wave\nax.plot(x, y, 0, color='r', lw=1, alpha=0.5)\nax.plot(x, [0]*n, z, color='m', lw=1, alpha=0.5)\n\n# Remove axis planes, ticks and labels\nax.set_axis_off()\nplt.show()\n


简单曲面图

import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.cm as cm\n\nL, n = 2, 400\nx = np.linspace(-L, L, n)\ny = x.copy()\nX, Y = np.meshgrid(x, y)\nZ = np.exp(-(X**2 + Y**2))\n\nfig, ax = plt.subplots(nrows=2, ncols=2, subplot_kw={'projection': '3d'})\nax[0,0].plot_wireframe(X, Y, Z, rstride=40, cstride=40)\nax[0,1].plot_surface(X, Y, Z, rstride=40, cstride=40, color='m')\nax[1,0].plot_surface(X, Y, Z, rstride=12, cstride=12, color='m')\nax[1,1].plot_surface(X, Y, Z, rstride=20, cstride=20, cmap=cm.hot)\nfor axes in ax.flatten():\n axes.set_xticks([-2, -1, 0, 1, 2])\n axes.set_yticks([-2, -1, 0, 1, 2])\n axes.set_zticks([0, 0.5, 1])\nfig.tight_layout()\nplt.show()\n


动画

弹跳球动画

import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# Acceleration due to gravity, m.s-2.\ng = 9.81\n# The maximum x-range of ball's trajectory to plot.\nXMAX = 5\n# The coefficient of restitution for bounces (-v_up/v_down).\ncor = 0.65\n# The time step for the animation.\ndt = 0.005\n\n# Initial position and velocity vectors.\nx0, y0 = 0, 4\nvx0, vy0 = 1, 0\n\ndef get_pos(t=0):\n """A generator yielding the ball's position at time t."""\n x, y, vx, vy = x0, y0, vx0, vy0\n while x < XMAX:\n t += dt\n x += vx0 * dt\n y += vy * dt\n vy -= g * dt\n if y < 0:\n # bounce!\n y = 0\n vy = -vy * cor \n yield x, y\n\ndef init():\n """Initialize the animation figure."""\n ax.set_xlim(0, XMAX)\n ax.set_ylim(0, y0)\n ax.set_xlabel('$x$ /m')\n ax.set_ylabel('$y$ /m')\n line.set_data(xdata, ydata)\n ball.set_center((x0, y0))\n height_text.set_text(f'Height: {y0:.1f} m')\n return line, ball, height_text\n\ndef animate(pos):\n """For each frame, advance the animation to the new position, pos."""\n x, y = pos\n xdata.append(x)\n ydata.append(y)\n line.set_data(xdata, ydata)\n ball.set_center((x, y))\n height_text.set_text(f'Height: {y:.1f} m')\n return line, ball, height_text\n\n# Set up a new Figure, with equal aspect ratio so the ball appears round.\nfig, ax = plt.subplots()\nax.set_aspect('equal')\n\n# These are the objects we need to keep track of.\nline, = ax.plot([], [], lw=2)\nball = plt.Circle((x0, y0), 0.08)\nheight_text = ax.text(XMAX*0.5, y0*0.8, f'Height: {y0:.1f} m')\nax.add_patch(ball)\nxdata, ydata = [], []\n\ninterval = 1000*dt\nani = animation.FuncAnimation(fig, animate, get_pos, blit=True,\n interval=interval, repeat=False, init_func=init)\nplt.show()


衰减正弦曲线

import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# Time step for the animation (s), max time to animate for (s).\ndt, tmax = 0.01, 5\n# Signal frequency (s-1), decay constant (s-1).\nf, alpha = 2.5, 1\n# These lists will hold the data to plot.\nt, M = [], []\n\n# Draw an empty plot, but preset the plot x- and y-limits.\nfig, ax = plt.subplots()\nline, = ax.plot([], [])\nax.set_xlim(0, tmax)\nax.set_ylim(-1, 1)\nax.set_xlabel('t /s')\nax.set_ylabel('M (arb. units)')\n\ndef init():\n return line,\n\ndef animate(i, t, M):\n """Draw the frame i of the animation."""\n\n # Append this time point and its data and set the plotted line data.\n _t = i*dt\n t.append(_t)\n M.append(np.sin(2*np.pi*f*_t) * np.exp(-alpha*_t))\n line.set_data(t, M)\n return line,\n\n# Interval between frames in ms, total number of frames to use.\ninterval, nframes = 1000 * dt, int(tmax / dt)\n# Animate once (set repeat=False so the animation doesn't loop).\nani = animation.FuncAnimation(fig, animate, frames=nframes, init_func=init,\n fargs=(t, M), repeat=False, interval=interval, blit=True)\nplt.show()\n

注意:分配给fargs参数的任何对象FuncAnimation都将传递给动画函数。


热力图

import numpy as np\nimport matplotlib.pyplot as plt\n\n# Read in the relevant data from our input file.\ndt = np.dtype([('month', np.int), ('day', np.int), ('T', np.float)])\ndata = np.genfromtxt('boston2019.dat', dtype=dt, usecols=(1, 2, 3),\n delimiter=(4, 2, 2, 6))\n\n# In our heatmap, nan will mean "no such date", e.g. 31 June.\nheatmap = np.empty((12, 31))\nheatmap[:] = np.nan\n\nfor month, day, T in data:\n # NumPy arrays are zero-indexed; days and months are not!\n heatmap[month-1, day-1] = T\n\n# Plot the heatmap, customize and label the ticks.\nfig = plt.figure()\nax = fig.add_subplot()\nim = ax.imshow(heatmap, interpolation='nearest')\nax.set_yticks(range(12))\nax.set_yticklabels(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\ndays = np.array(range(0, 31, 2))\nax.set_xticks(days)\nax.set_xticklabels(['{:d}'.format(day+1) for day in days])\nax.set_xlabel('Day of month')\nax.set_title('Maximum daily temperatures in Boston, 2019')\n\n# Add a colorbar along the bottom and label it.\ncbar = fig.colorbar(ax=ax, mappable=im, orientation='horizontal')\ncbar.set_label('Temperature, $^\\circ\\mathrm{C}$')\n\nplt.show()\n

传递给的“可映射”对象fig.colorbar是由AxesImage返回的对象ax.imshow。