Skip to content

Instantly share code, notes, and snippets.

@msund
Created April 3, 2014 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msund/9964782 to your computer and use it in GitHub Desktop.
Save msund/9964782 to your computer and use it in GitHub Desktop.
MPL to Plotly Examples
{
"metadata": {
"name": "mpl double examples"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": "matplotlib to Plotly examples"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "The [Plotly Python API](https://plot.ly/api/python) allows you to write matplotlib syntax and make shareable D3 graphs. You can install [matplotlylib](https://pypi.python.org/pypi/matplotlylib/0.1.0) to get started. Below are examples borrowed from two wonderful IPython NBs: \"[A Crash Course in Python for Scientists](http://nbviewer.ipython.org/gist/rpmuller/5920182)\" by [Rick Muller](http://www.cs.sandia.gov/~rmuller/) and a quite useful tutorial: \"[matplotlib - 2D and 3D plotting in Python](http://nbviewer.ipython.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-4-Matplotlib.ipynb)\" by [J.R. Johansson](https://github.com/jrjohansson). Check out their NBs for the originals and a rich context. If you have feedback, questions, or suggestions, please let us know at feedback@plot.ly or [@plotlygraphs](https://twitter.com/plotlygraphs). Happy plotting!"
},
{
"cell_type": "code",
"collapsed": false,
"input": "%pylab inline\nimport matplotlib.pyplot as plt # so we don't have to look at mpl's backend\nimport matplotlib.gridspec as gridspec # for subplots\nimport matplotlib.cm as cm # for fun-with-colors\nimport numpy as np",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": "Populating the interactive namespace from numpy and matplotlib\n"
}
],
"prompt_number": 8
},
{
"cell_type": "code",
"collapsed": false,
"input": "from matplotlylib import fig_to_plotly\nusername = 'IPython.Demo'\napi_key = '1fw3zw2o13'",
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 9
},
{
"cell_type": "code",
"collapsed": false,
"input": "x = linspace(0, 5, 10)\ny = x ** 2",
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 10
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig1 = plt.figure()\nsubplot(1,2,1)\nplot(x, y, 'r--')\nsubplot(1,2,2)\nplot(y, x, 'g*-');\nfig_to_plotly(fig1, username, api_key, notebook= True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2478/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 11,
"text": "<IPython.core.display.HTML at 0x10bd8cf10>"
}
],
"prompt_number": 11
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig2 = plt.figure()\n\naxes1 = fig2.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes\naxes2 = fig2.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes\n\n# main figure\naxes1.plot(x, y, 'r')\naxes1.set_xlabel('x')\naxes1.set_ylabel('y')\naxes1.set_title('title')\n\n# insert\naxes2.plot(y, x, 'g')\naxes2.set_xlabel('y')\naxes2.set_ylabel('x')\naxes2.set_title('insert title');\nfig_to_plotly(fig2, username, api_key, notebook= True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2480/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 13,
"text": "<IPython.core.display.HTML at 0x10c2cad10>"
}
],
"prompt_number": 13
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig4 = plt.figure()\nfig4, ax = plt.subplots()\n\nax.plot(x, x**2, label=r\"$y = \\alpha^2$\")\nax.plot(x, x**3, label=r\"$y = \\alpha^3$\")\nax.legend(loc=2) # upper left corner\nax.set_xlabel(r'$\\alpha$', fontsize=18)\nax.set_ylabel(r'$y$', fontsize=18)\nax.set_title('title');\nfig_to_plotly(fig4, username, api_key, notebook= True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2481/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 14,
"text": "<IPython.core.display.HTML at 0x10bda6750>"
},
{
"metadata": {},
"output_type": "display_data",
"text": "<matplotlib.figure.Figure at 0x10bb87f50>"
}
],
"prompt_number": 14
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig6 = plt.figure()\nfig6, ax = plt.subplots()\n\nax.plot(x, x+1, color=\"red\", alpha=0.5) # half-transparant red\nax.plot(x, x+2, color=\"#1155dd\") # RGB hex code for a bluish color\nax.plot(x, x+3, color=\"#15cc55\") # RGB hex code for a greenish color\nfig_to_plotly(fig6, username, api_key, notebook= True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2482/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 15,
"text": "<IPython.core.display.HTML at 0x10c2af950>"
},
{
"metadata": {},
"output_type": "display_data",
"text": "<matplotlib.figure.Figure at 0x10bd98390>"
}
],
"prompt_number": 15
},
{
"cell_type": "code",
"collapsed": false,
"input": "# MATLAB style line color and style \nax.plot(x, x**2, 'b.-') # blue line with dots\nax.plot(x, x**3, 'g--') # green dashed line",
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 21,
"text": "[<matplotlib.lines.Line2D at 0x10c4c9b90>]"
}
],
"prompt_number": 21
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig7 = plt.figure()\nfig7, ax = plt.subplots()\nxx = np.linspace(-0.75, 1., 100)\n\nax.plot(xx, xx**2, xx, xx**3)\n\nax.text(0.15, 0.2, r\"$y=x^2$\", fontsize=20, color=\"blue\")\nax.text(0.65, 0.1, r\"$y=x^3$\", fontsize=20, color=\"green\");\nfig_to_plotly(fig7, username, api_key, notebook= True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2483/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 29,
"text": "<IPython.core.display.HTML at 0x10c96f5d0>"
},
{
"metadata": {},
"output_type": "display_data",
"text": "<matplotlib.figure.Figure at 0x10c90d3d0>"
}
],
"prompt_number": 29
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig8 = plt.figure()\nnpts = 5000\nxs = 2*rand(npts)-1\nys = 2*rand(npts)-1\nr = xs**2+ys**2\nninside = (r<1).sum()\nfigsize(6,6) # make the figure square\ntitle(\"Approximation to pi = %f\" % (4*ninside/float(npts)))\nplot(xs[r<1],ys[r<1],'b.')\nplot(xs[r>1],ys[r>1],'r.')\nfigsize(8,6) # change the figsize back to 4x3 for the rest of the notebook\nfig_to_plotly(fig8, username, api_key, notebook= True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2484/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 30,
"text": "<IPython.core.display.HTML at 0x10cbd3650>"
}
],
"prompt_number": 30
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig9 = plt.figure()\nfrom scipy.fftpack import fft,fftfreq\n\nnpts = 4000\nnplot = npts/10\nt = linspace(0,120,npts)\ndef acc(t): return 10*sin(2*pi*2.0*t) + 5*sin(2*pi*8.0*t) + 2*rand(npts)\n\nsignal = acc(t)\n\nFFT = abs(fft(signal))\nfreqs = fftfreq(npts, t[1]-t[0])\n\nsubplot(211)\nplot(t[:nplot], signal[:nplot])\nsubplot(212)\nplot(freqs,20*log10(FFT),',')\nfig_to_plotly(fig9, username, api_key, notebook = True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2486/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 32,
"text": "<IPython.core.display.HTML at 0x10d1b8c10>"
}
],
"prompt_number": 32
},
{
"cell_type": "code",
"collapsed": false,
"input": "class Schrod1d:\n \"\"\"\\\n Schrod1d: Solver for the one-dimensional Schrodinger equation.\n \"\"\"\n def __init__(self,V,start=0,end=1,npts=50,**kwargs):\n m = kwargs.get('m',1.0)\n self.x = linspace(start,end,npts)\n self.Vx = V(self.x)\n self.H = (-0.5/m)*self.laplacian() + diag(self.Vx)\n return\n \n def plot(self,*args,**kwargs):\n titlestring = kwargs.get('titlestring',\"Eigenfunctions of the 1d Potential\")\n xstring = kwargs.get('xstring',\"Displacement (bohr)\")\n ystring = kwargs.get('ystring',\"Energy (hartree)\")\n if not args:\n args = [3]\n x = self.x\n E,U = eigh(self.H)\n h = x[1]-x[0]\n\n # Plot the Potential\n plot(x,self.Vx,color='k')\n\n for i in range(*args):\n # For each of the first few solutions, plot the energy level:\n axhline(y=E[i],color='k',ls=\":\")\n # as well as the eigenfunction, displaced by the energy level so they don't\n # all pile up on each other:\n plot(x,U[:,i]/sqrt(h)+E[i])\n title(titlestring)\n xlabel(xstring)\n ylabel(ystring) \n return\n \n def laplacian(self):\n x = self.x\n h = x[1]-x[0] # assume uniformly spaced points\n n = len(x)\n M = -2*identity(n,'d')\n for i in range(1,n):\n M[i,i-1] = M[i-1,i] = 1\n return M/h**2",
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 33
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig10 = plt.figure()\nsquare_well = Schrod1d(lambda x: 0*x,m=10)\nsquare_well.plot(4,titlestring=\"Square Well Potential\")\nfig_to_plotly(fig10, username, api_key, notebook = True)",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stderr",
"text": "/Users/matthewsundquist/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlylib/renderer.py:363: UserWarning: Bummer! Plotly can currently only draw Line2D objects from matplotlib that are in 'data' coordinates!\n warnings.warn(\"Bummer! Plotly can currently only draw Line2D \"\n"
},
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2487/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 34,
"text": "<IPython.core.display.HTML at 0x10cb9e610>"
}
],
"prompt_number": 34
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig11 = plt.figure()\nho = Schrod1d(lambda x: x**2,start=-3,end=3)\nho.plot(6,titlestring=\"Harmonic Oscillator\")\nfig_to_plotly(fig11, username, api_key, notebook = True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2488/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 35,
"text": "<IPython.core.display.HTML at 0x10d6bfcd0>"
}
],
"prompt_number": 35
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig12 = plt.figure()\ndef finite_well(x,V_left=1,V_well=0,V_right=1,d_left=10,d_well=10,d_right=10):\n V = zeros(x.size,'d')\n for i in range(x.size):\n if x[i] < d_left: \n V[i] = V_left\n elif x[i] > (d_left+d_well):\n V[i] = V_right\n else:\n V[i] = V_well\n return V\n \nfw = Schrod1d(finite_well,start=0,end=30,npts=100)\nfw.plot()\nfig_to_plotly(fig12, username, api_key, notebook = True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2489/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 36,
"text": "<IPython.core.display.HTML at 0x10d6b8a50>"
}
],
"prompt_number": 36
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig13 = plt.figure()\ndef triangular(x,F=30): return F*x\n\ntw = Schrod1d(triangular,m=10)\ntw.plot()\nfig_to_plotly(fig13, username, api_key, notebook = True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2490/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 37,
"text": "<IPython.core.display.HTML at 0x10e651cd0>"
}
],
"prompt_number": 37
},
{
"cell_type": "code",
"collapsed": false,
"input": "fig14 = plt.figure()\ndef tri_finite(x): return finite_well(x)+triangular(x,F=0.025)\n\ntfw = Schrod1d(tri_finite,start=0,end=30,npts=100)\ntfw.plot()\nfig_to_plotly(fig14, username, api_key, notebook = True)",
"language": "python",
"metadata": {},
"outputs": [
{
"html": "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/2491/600/450\" width=\"650\"></iframe>",
"metadata": {},
"output_type": "pyout",
"prompt_number": 38,
"text": "<IPython.core.display.HTML at 0x10cf2dd10>"
}
],
"prompt_number": 38
},
{
"cell_type": "code",
"collapsed": false,
"input": "",
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment