PK HL4 animation/dynamic_image2.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# An animated image using a list of images\n\n\nAnimate an image from a list of images (or Artists).\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfig = plt.figure()\n\n\ndef f(x, y):\n return np.sin(x) + np.cos(y)\n\nx = np.linspace(0, 2 * np.pi, 120)\ny = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)\n# ims is a list of lists, each row is a list of artists to draw in the\n# current frame; here we are just animating one artist, the image, in\n# each frame\nims = []\nfor i in range(60):\n x += np.pi / 15.\n y += np.pi / 20.\n im = plt.imshow(f(x, y), animated=True)\n ims.append([im])\n\nani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,\n repeat_delay=1000)\n\n# ani.save('dynamic_images.mp4')\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL%8 8 + animation/basic_example_writer_sgskip.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Saving an animation\n\n\nThis example showcases the same animations as `basic_example.py`, but instead\nof displaying the animation to the user, it writes to files using a\nMovieWriter instance.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef update_line(num, data, line):\n line.set_data(data[..., :num])\n return line,\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\n# Set up formatting for the movie files\nWriter = animation.writers['ffmpeg']\nwriter = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)\n\n\nfig1 = plt.figure()\n\ndata = np.random.rand(2, 25)\nl, = plt.plot([], [], 'r-')\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel('x')\nplt.title('test')\nline_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),\n interval=50, blit=True)\nline_ani.save('lines.mp4', writer=writer)\n\nfig2 = plt.figure()\n\nx = np.arange(-9, 10)\ny = np.arange(-9, 10).reshape(-1, 1)\nbase = np.hypot(x, y)\nims = []\nfor add in np.arange(15):\n ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))\n\nim_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,\n blit=True)\nim_ani.save('im.mp4', writer=writer)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLhC4 animation/unchained.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n========================\nMATPLOTLIB **UNCHAINED**\n========================\n\nComparative path demonstration of frequency from a fake signal of a pulsar.\n(mostly known because of the cover for Joy Division's Unknown Pleasures)\n\nAuthor: Nicolas P. Rougier\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\n# Create new Figure with black background\nfig = plt.figure(figsize=(8, 8), facecolor='black')\n\n# Add a subplot with no frame\nax = plt.subplot(111, frameon=False)\n\n# Generate random data\ndata = np.random.uniform(0, 1, (64, 75))\nX = np.linspace(-1, 1, data.shape[-1])\nG = 1.5 * np.exp(-4 * X ** 2)\n\n# Generate line plots\nlines = []\nfor i in range(len(data)):\n # Small reduction of the X extents to get a cheap perspective effect\n xscale = 1 - i / 200.\n # Same for linewidth (thicker strokes on bottom)\n lw = 1.5 - i / 100.0\n line, = ax.plot(xscale * X, i + G * data[i], color=\"w\", lw=lw)\n lines.append(line)\n\n# Set y limit (or first line is cropped because of thickness)\nax.set_ylim(-1, 70)\n\n# No ticks\nax.set_xticks([])\nax.set_yticks([])\n\n# 2 part titles to get different font weights\nax.text(0.5, 1.0, \"MATPLOTLIB \", transform=ax.transAxes,\n ha=\"right\", va=\"bottom\", color=\"w\",\n family=\"sans-serif\", fontweight=\"light\", fontsize=16)\nax.text(0.5, 1.0, \"UNCHAINED\", transform=ax.transAxes,\n ha=\"left\", va=\"bottom\", color=\"w\",\n family=\"sans-serif\", fontweight=\"bold\", fontsize=16)\n\n\ndef update(*args):\n # Shift all data to the right\n data[:, 1:] = data[:, :-1]\n\n # Fill-in new values\n data[:, 0] = np.random.uniform(0, 1, len(data))\n\n # Update data\n for i in range(len(data)):\n lines[i].set_ydata(i + G * data[i])\n\n # Return modified artists\n return lines\n\n# Construct the animation, using the update function as the animation\n# director.\nanim = animation.FuncAnimation(fig, update, interval=10)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLxmb " animation/moviewriter_sgskip.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# MovieWriter\n\n\nUse a MovieWriter directly to grab individual frames and write\nthem to a file. This avoids any event loop integration, but has the advantage\nof working with even the Agg backend. This is not recommended for use in an\ninteractive setting.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as manimation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nFFMpegWriter = manimation.writers['ffmpeg']\nmetadata = dict(title='Movie Test', artist='Matplotlib',\n comment='Movie support!')\nwriter = FFMpegWriter(fps=15, metadata=metadata)\n\nfig = plt.figure()\nl, = plt.plot([], [], 'k-o')\n\nplt.xlim(-5, 5)\nplt.ylim(-5, 5)\n\nx0, y0 = 0, 0\n\nwith writer.saving(fig, \"writer_test.mp4\", 100):\n for i in range(100):\n x0 += 0.1 * np.random.randn()\n y0 += 0.1 * np.random.randn()\n l.set_data(x0, y0)\n writer.grab_frame()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL'Qc c animation/simple_3danim.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# 3D animation\n\n\nAn animated plot in 3D.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as p3\nimport matplotlib.animation as animation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\ndef Gen_RandLine(length, dims=2):\n \"\"\"\n Create a line using a random walk algorithm\n\n length is the number of points for the line.\n dims is the number of dimensions the line has.\n \"\"\"\n lineData = np.empty((dims, length))\n lineData[:, 0] = np.random.rand(dims)\n for index in range(1, length):\n # scaling the random numbers by 0.1 so\n # movement is small compared to position.\n # subtraction by 0.5 is to change the range to [-0.5, 0.5]\n # to allow a line to move backwards.\n step = ((np.random.rand(dims) - 0.5) * 0.1)\n lineData[:, index] = lineData[:, index - 1] + step\n\n return lineData\n\n\ndef update_lines(num, dataLines, lines):\n for line, data in zip(lines, dataLines):\n # NOTE: there is no .set_data() for 3 dim data...\n line.set_data(data[0:2, :num])\n line.set_3d_properties(data[2, :num])\n return lines\n\n# Attaching 3D axis to the figure\nfig = plt.figure()\nax = p3.Axes3D(fig)\n\n# Fifty lines of random 3-D lines\ndata = [Gen_RandLine(25, 3) for index in range(50)]\n\n# Creating fifty line objects.\n# NOTE: Can't pass empty arrays into 3d version of plot()\nlines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]\n\n# Setting the axes properties\nax.set_xlim3d([0.0, 1.0])\nax.set_xlabel('X')\n\nax.set_ylim3d([0.0, 1.0])\nax.set_ylabel('Y')\n\nax.set_zlim3d([0.0, 1.0])\nax.set_zlabel('Z')\n\nax.set_title('3D Test')\n\n# Creating the Animation object\nline_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),\n interval=50, blit=False)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLWy animation/dynamic_image.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# An animated image\n\n\nAnimation of an image.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfig = plt.figure()\n\n\ndef f(x, y):\n return np.sin(x) + np.cos(y)\n\nx = np.linspace(0, 2 * np.pi, 120)\ny = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)\n\nim = plt.imshow(f(x, y), animated=True)\n\n\ndef updatefig(*args):\n global x, y\n x += np.pi / 15.\n y += np.pi / 20.\n im.set_array(f(x, y))\n return im,\n\nani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL8l animation/histogram.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Animated histogram\n\n\nUse a path patch to draw a bunch of rectangles for an animated histogram.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.path as path\nimport matplotlib.animation as animation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n# histogram our data with numpy\ndata = np.random.randn(1000)\nn, bins = np.histogram(data, 100)\n\n# get the corners of the rectangles for the histogram\nleft = np.array(bins[:-1])\nright = np.array(bins[1:])\nbottom = np.zeros(len(left))\ntop = bottom + n\nnrects = len(left)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here comes the tricky part -- we have to set up the vertex and path codes\narrays using ``plt.Path.MOVETO``, ``plt.Path.LINETO`` and\n``plt.Path.CLOSEPOLY`` for each rect.\n\n* We need 1 ``MOVETO`` per rectangle, which sets the initial point.\n* We need 3 ``LINETO``'s, which tell Matplotlib to draw lines from\n vertex 1 to vertex 2, v2 to v3, and v3 to v4.\n* We then need one ``CLOSEPOLY`` which tells Matplotlib to draw a line from\n the v4 to our initial vertex (the ``MOVETO`` vertex), in order to close the\n polygon.\n\n
Note
The vertex for ``CLOSEPOLY`` is ignored, but we still need a placeholder\n in the ``verts`` array to keep the codes aligned with the vertices.
\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"nverts = nrects * (1 + 3 + 1)\nverts = np.zeros((nverts, 2))\ncodes = np.ones(nverts, int) * path.Path.LINETO\ncodes[0::5] = path.Path.MOVETO\ncodes[4::5] = path.Path.CLOSEPOLY\nverts[0::5, 0] = left\nverts[0::5, 1] = bottom\nverts[1::5, 0] = left\nverts[1::5, 1] = top\nverts[2::5, 0] = right\nverts[2::5, 1] = top\nverts[3::5, 0] = right\nverts[3::5, 1] = bottom"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To animate the histogram, we need an ``animate`` function, which generates\na random set of numbers and updates the locations of the vertices for the\nhistogram (in this case, only the heights of each rectangle). ``patch`` will\neventually be a ``Patch`` object.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"patch = None\n\n\ndef animate(i):\n # simulate new data coming in\n data = np.random.randn(1000)\n n, bins = np.histogram(data, 100)\n top = bottom + n\n verts[1::5, 1] = top\n verts[2::5, 1] = top\n return [patch, ]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And now we build the `Path` and `Patch` instances for the histogram using\nour vertices and codes. We add the patch to the `Axes` instance, and setup\nthe `FuncAnimation` with our animate function.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\nbarpath = path.Path(verts, codes)\npatch = patches.PathPatch(\n barpath, facecolor='green', edgecolor='yellow', alpha=0.5)\nax.add_patch(patch)\n\nax.set_xlim(left[0], right[-1])\nax.set_ylim(bottom.min(), top.max())\n\nani = animation.FuncAnimation(fig, animate, 100, repeat=False, blit=True)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLa/ animation/subplots.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Animated subplots\n\n\nThis example uses subclassing, but there is no reason that the proper function\ncouldn't be set up and then use FuncAnimation. The code is long, but not\nreally complex. The length is due solely to the fact that there are a total of\n9 lines that need to be changed for the animation as well as 3 subplots that\nneed initial set up.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport matplotlib.animation as animation\n\n\nclass SubplotAnimation(animation.TimedAnimation):\n def __init__(self):\n fig = plt.figure()\n ax1 = fig.add_subplot(1, 2, 1)\n ax2 = fig.add_subplot(2, 2, 2)\n ax3 = fig.add_subplot(2, 2, 4)\n\n self.t = np.linspace(0, 80, 400)\n self.x = np.cos(2 * np.pi * self.t / 10.)\n self.y = np.sin(2 * np.pi * self.t / 10.)\n self.z = 10 * self.t\n\n ax1.set_xlabel('x')\n ax1.set_ylabel('y')\n self.line1 = Line2D([], [], color='black')\n self.line1a = Line2D([], [], color='red', linewidth=2)\n self.line1e = Line2D(\n [], [], color='red', marker='o', markeredgecolor='r')\n ax1.add_line(self.line1)\n ax1.add_line(self.line1a)\n ax1.add_line(self.line1e)\n ax1.set_xlim(-1, 1)\n ax1.set_ylim(-2, 2)\n ax1.set_aspect('equal', 'datalim')\n\n ax2.set_xlabel('y')\n ax2.set_ylabel('z')\n self.line2 = Line2D([], [], color='black')\n self.line2a = Line2D([], [], color='red', linewidth=2)\n self.line2e = Line2D(\n [], [], color='red', marker='o', markeredgecolor='r')\n ax2.add_line(self.line2)\n ax2.add_line(self.line2a)\n ax2.add_line(self.line2e)\n ax2.set_xlim(-1, 1)\n ax2.set_ylim(0, 800)\n\n ax3.set_xlabel('x')\n ax3.set_ylabel('z')\n self.line3 = Line2D([], [], color='black')\n self.line3a = Line2D([], [], color='red', linewidth=2)\n self.line3e = Line2D(\n [], [], color='red', marker='o', markeredgecolor='r')\n ax3.add_line(self.line3)\n ax3.add_line(self.line3a)\n ax3.add_line(self.line3e)\n ax3.set_xlim(-1, 1)\n ax3.set_ylim(0, 800)\n\n animation.TimedAnimation.__init__(self, fig, interval=50, blit=True)\n\n def _draw_frame(self, framedata):\n i = framedata\n head = i - 1\n head_slice = (self.t > self.t[i] - 1.0) & (self.t < self.t[i])\n\n self.line1.set_data(self.x[:i], self.y[:i])\n self.line1a.set_data(self.x[head_slice], self.y[head_slice])\n self.line1e.set_data(self.x[head], self.y[head])\n\n self.line2.set_data(self.y[:i], self.z[:i])\n self.line2a.set_data(self.y[head_slice], self.z[head_slice])\n self.line2e.set_data(self.y[head], self.z[head])\n\n self.line3.set_data(self.x[:i], self.z[:i])\n self.line3a.set_data(self.x[head_slice], self.z[head_slice])\n self.line3e.set_data(self.x[head], self.z[head])\n\n self._drawn_artists = [self.line1, self.line1a, self.line1e,\n self.line2, self.line2a, self.line2e,\n self.line3, self.line3a, self.line3e]\n\n def new_frame_seq(self):\n return iter(range(self.t.size))\n\n def _init_draw(self):\n lines = [self.line1, self.line1a, self.line1e,\n self.line2, self.line2a, self.line2e,\n self.line3, self.line3a, self.line3e]\n for l in lines:\n l.set_data([], [])\n\nani = SubplotAnimation()\n# ani.save('test_sub.mp4')\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL animation/random_data.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Random data\n\n\nAn animation of random data.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nfig, ax = plt.subplots()\nline, = ax.plot(np.random.rand(10))\nax.set_ylim(0, 1)\n\n\ndef update(data):\n line.set_ydata(data)\n return line,\n\n\ndef data_gen():\n while True:\n yield np.random.rand(10)\n\nani = animation.FuncAnimation(fig, update, data_gen, interval=100)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL?Ah
h
animation/rain.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Rain simulation\n\n\nSimulates rain drops on a surface by animating the scale and opacity\nof 50 scatter points.\n\nAuthor: Nicolas P. Rougier\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\n# Create new Figure and an Axes which fills it.\nfig = plt.figure(figsize=(7, 7))\nax = fig.add_axes([0, 0, 1, 1], frameon=False)\nax.set_xlim(0, 1), ax.set_xticks([])\nax.set_ylim(0, 1), ax.set_yticks([])\n\n# Create rain data\nn_drops = 50\nrain_drops = np.zeros(n_drops, dtype=[('position', float, 2),\n ('size', float, 1),\n ('growth', float, 1),\n ('color', float, 4)])\n\n# Initialize the raindrops in random positions and with\n# random growth rates.\nrain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))\nrain_drops['growth'] = np.random.uniform(50, 200, n_drops)\n\n# Construct the scatter which we will update during animation\n# as the raindrops develop.\nscat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],\n s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],\n facecolors='none')\n\n\ndef update(frame_number):\n # Get an index which we can use to re-spawn the oldest raindrop.\n current_index = frame_number % n_drops\n\n # Make all colors more transparent as time progresses.\n rain_drops['color'][:, 3] -= 1.0/len(rain_drops)\n rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)\n\n # Make all circles bigger.\n rain_drops['size'] += rain_drops['growth']\n\n # Pick a new position for oldest rain drop, resetting its size,\n # color and growth factor.\n rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)\n rain_drops['size'][current_index] = 5\n rain_drops['color'][current_index] = (0, 0, 0, 1)\n rain_drops['growth'][current_index] = np.random.uniform(50, 200)\n\n # Update the scatter collection, with the new colors, sizes and positions.\n scat.set_edgecolors(rain_drops['color'])\n scat.set_sizes(rain_drops['size'])\n scat.set_offsets(rain_drops['position'])\n\n\n# Construct the animation, using the update function as the animation\n# director.\nanimation = FuncAnimation(fig, update, interval=10)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL ! animation/movie_demo_sgskip.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Movie Demo\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import print_function\n\nimport os\nimport subprocess\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nfiles = []\n\nfig, ax = plt.subplots(figsize=(5, 5))\nfor i in range(50): # 50 frames\n plt.cla()\n plt.imshow(np.random.rand(5, 5), interpolation='nearest')\n fname = '_tmp%03d.png' % i\n print('Saving frame', fname)\n plt.savefig(fname)\n files.append(fname)\n\nprint('Making movie animation.mpg - this may take a while')\nsubprocess.call(\"mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc \"\n \"-lavcopts vcodec=wmv2 -oac copy -o animation.mpg\", shell=True)\n\n# cleanup\nfor fname in files:\n os.remove(fname)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLކ( ( # animation/image_slices_viewer.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Image Slices Viewer\n\n\nScroll through 2D image slices of a 3D array.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import print_function\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass IndexTracker(object):\n def __init__(self, ax, X):\n self.ax = ax\n ax.set_title('use scroll wheel to navigate images')\n\n self.X = X\n rows, cols, self.slices = X.shape\n self.ind = self.slices//2\n\n self.im = ax.imshow(self.X[:, :, self.ind])\n self.update()\n\n def onscroll(self, event):\n print(\"%s %s\" % (event.button, event.step))\n if event.button == 'up':\n self.ind = (self.ind + 1) % self.slices\n else:\n self.ind = (self.ind - 1) % self.slices\n self.update()\n\n def update(self):\n self.im.set_data(self.X[:, :, self.ind])\n ax.set_ylabel('slice %s' % self.ind)\n self.im.axes.figure.canvas.draw()\n\n\nfig, ax = plt.subplots(1, 1)\n\nX = np.random.rand(20, 20, 40)\n\ntracker = IndexTracker(ax, X)\n\n\nfig.canvas.mpl_connect('scroll_event', tracker.onscroll)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL^!
!
animation/basic_example.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Simple animation examples\n\n\nTwo animations where the first is a random walk plot and\nthe second is an image animation.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef update_line(num, data, line):\n line.set_data(data[..., :num])\n return line,"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig1 = plt.figure()\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\ndata = np.random.rand(2, 25)\nl, = plt.plot([], [], 'r-')\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel('x')\nplt.title('test')\nline_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),\n interval=50, blit=True)\n\n# To save the animation, use the command: line_ani.save('lines.mp4')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig2 = plt.figure()\n\nx = np.arange(-9, 10)\ny = np.arange(-9, 10).reshape(-1, 1)\nbase = np.hypot(x, y)\nims = []\nfor add in np.arange(15):\n ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))\n\nim_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,\n blit=True)\n# To save this second animation with some metadata, use the following command:\n# im_ani.save('im.mp4', metadata={'artist':'Guido'})\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLK,W
animation/strip_chart_demo.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Oscilloscope\n\n\nEmulates an oscilloscope.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nfrom matplotlib.lines import Line2D\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\nclass Scope(object):\n def __init__(self, ax, maxt=2, dt=0.02):\n self.ax = ax\n self.dt = dt\n self.maxt = maxt\n self.tdata = [0]\n self.ydata = [0]\n self.line = Line2D(self.tdata, self.ydata)\n self.ax.add_line(self.line)\n self.ax.set_ylim(-.1, 1.1)\n self.ax.set_xlim(0, self.maxt)\n\n def update(self, y):\n lastt = self.tdata[-1]\n if lastt > self.tdata[0] + self.maxt: # reset the arrays\n self.tdata = [self.tdata[-1]]\n self.ydata = [self.ydata[-1]]\n self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)\n self.ax.figure.canvas.draw()\n\n t = self.tdata[-1] + self.dt\n self.tdata.append(t)\n self.ydata.append(y)\n self.line.set_data(self.tdata, self.ydata)\n return self.line,\n\n\ndef emitter(p=0.03):\n 'return a random value with probability p, else 0'\n while True:\n v = np.random.rand(1)\n if v > p:\n yield 0.\n else:\n yield np.random.rand(1)\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nfig, ax = plt.subplots()\nscope = Scope(ax)\n\n# pass a generator in \"emitter\" to produce data for the update func\nani = animation.FuncAnimation(fig, scope.update, emitter, interval=10,\n blit=True)\n\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL47+
/ animation/double_pendulum_animated_sgskip.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# The double pendulum problem\n\n\nThis animation illustrates the double pendulum problem.\n\nDouble pendulum formula translated from the C code at\nhttp://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from numpy import sin, cos\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate as integrate\nimport matplotlib.animation as animation\n\nG = 9.8 # acceleration due to gravity, in m/s^2\nL1 = 1.0 # length of pendulum 1 in m\nL2 = 1.0 # length of pendulum 2 in m\nM1 = 1.0 # mass of pendulum 1 in kg\nM2 = 1.0 # mass of pendulum 2 in kg\n\n\ndef derivs(state, t):\n\n dydx = np.zeros_like(state)\n dydx[0] = state[1]\n\n del_ = state[2] - state[0]\n den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_)\n dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_) +\n M2*G*sin(state[2])*cos(del_) +\n M2*L2*state[3]*state[3]*sin(del_) -\n (M1 + M2)*G*sin(state[0]))/den1\n\n dydx[2] = state[3]\n\n den2 = (L2/L1)*den1\n dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*cos(del_) +\n (M1 + M2)*G*sin(state[0])*cos(del_) -\n (M1 + M2)*L1*state[1]*state[1]*sin(del_) -\n (M1 + M2)*G*sin(state[2]))/den2\n\n return dydx\n\n# create a time array from 0..100 sampled at 0.05 second steps\ndt = 0.05\nt = np.arange(0.0, 20, dt)\n\n# th1 and th2 are the initial angles (degrees)\n# w10 and w20 are the initial angular velocities (degrees per second)\nth1 = 120.0\nw1 = 0.0\nth2 = -10.0\nw2 = 0.0\n\n# initial state\nstate = np.radians([th1, w1, th2, w2])\n\n# integrate your ODE using scipy.integrate.\ny = integrate.odeint(derivs, state, t)\n\nx1 = L1*sin(y[:, 0])\ny1 = -L1*cos(y[:, 0])\n\nx2 = L2*sin(y[:, 2]) + x1\ny2 = -L2*cos(y[:, 2]) + y1\n\nfig = plt.figure()\nax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2))\nax.set_aspect('equal')\nax.grid()\n\nline, = ax.plot([], [], 'o-', lw=2)\ntime_template = 'time = %.1fs'\ntime_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)\n\n\ndef init():\n line.set_data([], [])\n time_text.set_text('')\n return line, time_text\n\n\ndef animate(i):\n thisx = [0, x1[i], x2[i]]\n thisy = [0, y1[i], y2[i]]\n\n line.set_data(thisx, thisy)\n time_text.set_text(time_template % (i*dt))\n return line, time_text\n\nani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)),\n interval=25, blit=True, init_func=init)\n\n# ani.save('double_pendulum.mp4', fps=15)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLH2s> > animation/animation_demo.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Animation Demo\n\n\nPyplot animation example.\n\nThe method shown here is only for very simple, low-performance\nuse. For more demanding applications, look at the animation\nmodule and the examples that use it.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(6)\ny = np.arange(5)\nz = x * y[:, np.newaxis]\n\nfor i in range(5):\n if i == 0:\n p = plt.imshow(z)\n fig = plt.gcf()\n plt.clim() # clamp the color limits\n plt.title(\"Boring slide show\")\n else:\n z = z + 2\n p.set_data(z)\n\n print(\"step\", i)\n plt.pause(0.5)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLb&U U animation/simple_anim.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Simple Anim\n\n\nA simple example of an animated plot\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfig, ax = plt.subplots()\n\nx = np.arange(0, 2*np.pi, 0.01)\nline, = ax.plot(x, np.sin(x))\n\n\ndef animate(i):\n line.set_ydata(np.sin(x + i/10.0)) # update the data\n return line,\n\n\n# Init only required for blitting to give a clean slate.\ndef init():\n line.set_ydata(np.ma.array(x, mask=True))\n return line,\n\nani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,\n interval=25, blit=True)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL
# animation/bayes_update_sgskip.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# The Bayes update\n\n\nThis animation displays the posterior estimate updates as it is refitted when\nnew data arrives.\nThe vertical line represents the theoretical value to which the plotted\ndistribution should converge.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# update a distribution based on new data.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as ss\nfrom matplotlib.animation import FuncAnimation\n\n\nclass UpdateDist(object):\n def __init__(self, ax, prob=0.5):\n self.success = 0\n self.prob = prob\n self.line, = ax.plot([], [], 'k-')\n self.x = np.linspace(0, 1, 200)\n self.ax = ax\n\n # Set up plot parameters\n self.ax.set_xlim(0, 1)\n self.ax.set_ylim(0, 15)\n self.ax.grid(True)\n\n # This vertical line represents the theoretical value, to\n # which the plotted distribution should converge.\n self.ax.axvline(prob, linestyle='--', color='black')\n\n def init(self):\n self.success = 0\n self.line.set_data([], [])\n return self.line,\n\n def __call__(self, i):\n # This way the plot can continuously run and we just keep\n # watching new realizations of the process\n if i == 0:\n return self.init()\n\n # Choose success based on exceed a threshold with a uniform pick\n if np.random.rand(1,) < self.prob:\n self.success += 1\n y = ss.beta.pdf(self.x, self.success + 1, (i - self.success) + 1)\n self.line.set_data(self.x, y)\n return self.line,\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nfig, ax = plt.subplots()\nud = UpdateDist(ax, prob=0.7)\nanim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,\n interval=100, blit=True)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLy<| animation/animate_decay.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Decay\n\n\nA sinusoidal decay animation.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef data_gen(t=0):\n cnt = 0\n while cnt < 1000:\n cnt += 1\n t += 0.1\n yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)\n\n\ndef init():\n ax.set_ylim(-1.1, 1.1)\n ax.set_xlim(0, 10)\n del xdata[:]\n del ydata[:]\n line.set_data(xdata, ydata)\n return line,\n\nfig, ax = plt.subplots()\nline, = ax.plot([], [], lw=2)\nax.grid()\nxdata, ydata = [], []\n\n\ndef run(data):\n # update the data\n t, y = data\n xdata.append(t)\n ydata.append(y)\n xmin, xmax = ax.get_xlim()\n\n if t >= xmax:\n ax.set_xlim(xmin, 2*xmax)\n ax.figure.canvas.draw()\n line.set_data(xdata, ydata)\n\n return line,\n\nani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,\n repeat=False, init_func=init)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLǖr r api/logos2.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Matplotlib Logos\n\n\nDisplays some matplotlib logos.\n\nThanks to Tony Yu for the logo design\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nmpl.rcParams['xtick.labelsize'] = 10\nmpl.rcParams['ytick.labelsize'] = 12\nmpl.rcParams['axes.edgecolor'] = 'gray'\n\n\naxalpha = 0.05\nfigcolor = 'white'\ndpi = 80\nfig = plt.figure(figsize=(6, 1.1), dpi=dpi)\nfig.patch.set_edgecolor(figcolor)\nfig.patch.set_facecolor(figcolor)\n\n\ndef add_math_background():\n ax = fig.add_axes([0., 0., 1., 1.])\n\n text = []\n text.append(\n (r\"$W^{3\\beta}_{\\delta_1 \\rho_1 \\sigma_2} = \"\n r\"U^{3\\beta}_{\\delta_1 \\rho_1} + \\frac{1}{8 \\pi 2}\"\n r\"\\int^{\\alpha_2}_{\\alpha_2} d \\alpha^\\prime_2 \"\n r\"\\left[\\frac{ U^{2\\beta}_{\\delta_1 \\rho_1} - \"\n r\"\\alpha^\\prime_2U^{1\\beta}_{\\rho_1 \\sigma_2} \"\n r\"}{U^{0\\beta}_{\\rho_1 \\sigma_2}}\\right]$\", (0.7, 0.2), 20))\n text.append((r\"$\\frac{d\\rho}{d t} + \\rho \\vec{v}\\cdot\\nabla\\vec{v} \"\n r\"= -\\nabla p + \\mu\\nabla^2 \\vec{v} + \\rho \\vec{g}$\",\n (0.35, 0.9), 20))\n text.append((r\"$\\int_{-\\infty}^\\infty e^{-x^2}dx=\\sqrt{\\pi}$\",\n (0.15, 0.3), 25))\n text.append((r\"$F_G = G\\frac{m_1m_2}{r^2}$\",\n (0.85, 0.7), 30))\n for eq, (x, y), size in text:\n ax.text(x, y, eq, ha='center', va='center', color=\"#11557c\",\n alpha=0.25, transform=ax.transAxes, fontsize=size)\n ax.set_axis_off()\n return ax\n\n\ndef add_matplotlib_text(ax):\n ax.text(0.95, 0.5, 'matplotlib', color='#11557c', fontsize=65,\n ha='right', va='center', alpha=1.0, transform=ax.transAxes)\n\n\ndef add_polar_bar():\n ax = fig.add_axes([0.025, 0.075, 0.2, 0.85], projection='polar')\n\n ax.patch.set_alpha(axalpha)\n ax.set_axisbelow(True)\n N = 7\n arc = 2. * np.pi\n theta = np.arange(0.0, arc, arc/N)\n radii = 10 * np.array([0.2, 0.6, 0.8, 0.7, 0.4, 0.5, 0.8])\n width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3])\n bars = ax.bar(theta, radii, width=width, bottom=0.0)\n for r, bar in zip(radii, bars):\n bar.set_facecolor(cm.jet(r/10.))\n bar.set_alpha(0.6)\n\n ax.tick_params(labelbottom=False, labeltop=False,\n labelleft=False, labelright=False)\n\n ax.grid(lw=0.8, alpha=0.9, ls='-', color='0.5')\n\n ax.set_yticks(np.arange(1, 9, 2))\n ax.set_rmax(9)\n\n\nif __name__ == '__main__':\n main_axes = add_math_background()\n add_polar_bar()\n add_matplotlib_text(main_axes)\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL\g"a a api/bbox_intersect.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Changing colors of lines intersecting a box\n\n\nThe lines intersecting the rectangle are colored in red, while the others\nare left as blue lines. This example showcases the `intersect_bbox` function.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.transforms import Bbox\nfrom matplotlib.path import Path\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nleft, bottom, width, height = (-1, -1, 2, 2)\nrect = plt.Rectangle((left, bottom), width, height, facecolor=\"#aaaaaa\")\n\nfig, ax = plt.subplots()\nax.add_patch(rect)\n\nbbox = Bbox.from_bounds(left, bottom, width, height)\n\nfor i in range(12):\n vertices = (np.random.random((2, 2)) - 0.5) * 6.0\n path = Path(vertices)\n if path.intersects_bbox(bbox):\n color = 'r'\n else:\n color = 'b'\n ax.plot(vertices[:, 0], vertices[:, 1], color=color)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL/:} api/filled_step.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Hatch-filled histograms\n\n\nHatching capabilities for plotting histograms.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import itertools\nfrom collections import OrderedDict\nfrom functools import partial\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nfrom cycler import cycler\nfrom six.moves import zip\n\n\ndef filled_hist(ax, edges, values, bottoms=None, orientation='v',\n **kwargs):\n \"\"\"\n Draw a histogram as a stepped patch.\n\n Extra kwargs are passed through to `fill_between`\n\n Parameters\n ----------\n ax : Axes\n The axes to plot to\n\n edges : array\n A length n+1 array giving the left edges of each bin and the\n right edge of the last bin.\n\n values : array\n A length n array of bin counts or values\n\n bottoms : scalar or array, optional\n A length n array of the bottom of the bars. If None, zero is used.\n\n orientation : {'v', 'h'}\n Orientation of the histogram. 'v' (default) has\n the bars increasing in the positive y-direction.\n\n Returns\n -------\n ret : PolyCollection\n Artist added to the Axes\n \"\"\"\n print(orientation)\n if orientation not in set('hv'):\n raise ValueError(\"orientation must be in {{'h', 'v'}} \"\n \"not {o}\".format(o=orientation))\n\n kwargs.setdefault('step', 'post')\n edges = np.asarray(edges)\n values = np.asarray(values)\n if len(edges) - 1 != len(values):\n raise ValueError('Must provide one more bin edge than value not: '\n 'len(edges): {lb} len(values): {lv}'.format(\n lb=len(edges), lv=len(values)))\n\n if bottoms is None:\n bottoms = np.zeros_like(values)\n if np.isscalar(bottoms):\n bottoms = np.ones_like(values) * bottoms\n\n values = np.r_[values, values[-1]]\n bottoms = np.r_[bottoms, bottoms[-1]]\n if orientation == 'h':\n return ax.fill_betweenx(edges, values, bottoms,\n **kwargs)\n elif orientation == 'v':\n return ax.fill_between(edges, values, bottoms,\n **kwargs)\n else:\n raise AssertionError(\"you should never be here\")\n\n\ndef stack_hist(ax, stacked_data, sty_cycle, bottoms=None,\n hist_func=None, labels=None,\n plot_func=None, plot_kwargs=None):\n \"\"\"\n ax : axes.Axes\n The axes to add artists too\n\n stacked_data : array or Mapping\n A (N, M) shaped array. The first dimension will be iterated over to\n compute histograms row-wise\n\n sty_cycle : Cycler or operable of dict\n Style to apply to each set\n\n bottoms : array, optional\n The initial positions of the bottoms, defaults to 0\n\n hist_func : callable, optional\n Must have signature `bin_vals, bin_edges = f(data)`.\n `bin_edges` expected to be one longer than `bin_vals`\n\n labels : list of str, optional\n The label for each set.\n\n If not given and stacked data is an array defaults to 'default set {n}'\n\n If stacked_data is a mapping, and labels is None, default to the keys\n (which may come out in a random order).\n\n If stacked_data is a mapping and labels is given then only\n the columns listed by be plotted.\n\n plot_func : callable, optional\n Function to call to draw the histogram must have signature:\n\n ret = plot_func(ax, edges, top, bottoms=bottoms,\n label=label, **kwargs)\n\n plot_kwargs : dict, optional\n Any extra kwargs to pass through to the plotting function. This\n will be the same for all calls to the plotting function and will\n over-ride the values in cycle.\n\n Returns\n -------\n arts : dict\n Dictionary of artists keyed on their labels\n \"\"\"\n # deal with default binning function\n if hist_func is None:\n hist_func = np.histogram\n\n # deal with default plotting function\n if plot_func is None:\n plot_func = filled_hist\n\n # deal with default\n if plot_kwargs is None:\n plot_kwargs = {}\n print(plot_kwargs)\n try:\n l_keys = stacked_data.keys()\n label_data = True\n if labels is None:\n labels = l_keys\n\n except AttributeError:\n label_data = False\n if labels is None:\n labels = itertools.repeat(None)\n\n if label_data:\n loop_iter = enumerate((stacked_data[lab], lab, s) for lab, s in\n zip(labels, sty_cycle))\n else:\n loop_iter = enumerate(zip(stacked_data, labels, sty_cycle))\n\n arts = {}\n for j, (data, label, sty) in loop_iter:\n if label is None:\n label = 'dflt set {n}'.format(n=j)\n label = sty.pop('label', label)\n vals, edges = hist_func(data)\n if bottoms is None:\n bottoms = np.zeros_like(vals)\n top = bottoms + vals\n print(sty)\n sty.update(plot_kwargs)\n print(sty)\n ret = plot_func(ax, edges, top, bottoms=bottoms,\n label=label, **sty)\n bottoms = top\n arts[label] = ret\n ax.legend(fontsize=10)\n return arts\n\n\n# set up histogram function to fixed bins\nedges = np.linspace(-3, 3, 20, endpoint=True)\nhist_func = partial(np.histogram, bins=edges)\n\n# set up style cycles\ncolor_cycle = cycler(facecolor=plt.rcParams['axes.prop_cycle'][:4])\nlabel_cycle = cycler('label', ['set {n}'.format(n=n) for n in range(4)])\nhatch_cycle = cycler('hatch', ['/', '*', '+', '|'])\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\nstack_data = np.random.randn(4, 12250)\ndict_data = OrderedDict(zip((c['label'] for c in label_cycle), stack_data))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Work with plain arrays\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5), tight_layout=True)\narts = stack_hist(ax1, stack_data, color_cycle + label_cycle + hatch_cycle,\n hist_func=hist_func)\n\narts = stack_hist(ax2, stack_data, color_cycle,\n hist_func=hist_func,\n plot_kwargs=dict(edgecolor='w', orientation='h'))\nax1.set_ylabel('counts')\nax1.set_xlabel('x')\nax2.set_xlabel('counts')\nax2.set_ylabel('x')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Work with labeled data\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5),\n tight_layout=True, sharey=True)\n\narts = stack_hist(ax1, dict_data, color_cycle + hatch_cycle,\n hist_func=hist_func)\n\narts = stack_hist(ax2, dict_data, color_cycle + hatch_cycle,\n hist_func=hist_func, labels=['set 0', 'set 3'])\nax1.xaxis.set_major_locator(mticker.MaxNLocator(5))\nax1.set_xlabel('counts')\nax1.set_ylabel('x')\nax2.set_ylabel('x')\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLi
api/date_index_formatter.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Custom tick formatter for time series\n\n\nWhen plotting time series, e.g., financial time series, one often wants\nto leave out days on which there is no data, i.e. weekends. The example\nbelow shows how to use an 'index formatter' to achieve the desired plot\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cbook as cbook\nimport matplotlib.ticker as ticker\n\n# Load a numpy record array from yahoo csv data with fields date, open, close,\n# volume, adj_close from the mpl-data/example directory. The record array\n# stores the date as an np.datetime64 with a day unit ('D') in the date column.\nwith cbook.get_sample_data('goog.npz') as datafile:\n r = np.load(datafile)['price_data'].view(np.recarray)\nr = r[-30:] # get the last 30 days\n# Matplotlib works better with datetime.datetime than np.datetime64, but the\n# latter is more portable.\ndate = r.date.astype('O')\n\n# first we'll do it the default way, with gaps on weekends\nfig, axes = plt.subplots(ncols=2, figsize=(8, 4))\nax = axes[0]\nax.plot(date, r.adj_close, 'o-')\nax.set_title(\"Default\")\nfig.autofmt_xdate()\n\n# next we'll write a custom formatter\nN = len(r)\nind = np.arange(N) # the evenly spaced plot indices\n\n\ndef format_date(x, pos=None):\n thisind = np.clip(int(x + 0.5), 0, N - 1)\n return date[thisind].strftime('%Y-%m-%d')\n\nax = axes[1]\nax.plot(ind, r.adj_close, 'o-')\nax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))\nax.set_title(\"Custom tick formatter\")\nfig.autofmt_xdate()\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLe|{ api/power_norm.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Exploring normalizations\n\n\nVarious normalization on a multivariate normal distribution.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from matplotlib import pyplot as plt\nimport matplotlib.colors as mcolors\nimport numpy as np\nfrom numpy.random import multivariate_normal\n\ndata = np.vstack([\n multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),\n multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)\n])\n\ngammas = [0.8, 0.5, 0.3]\n\nfig, axes = plt.subplots(nrows=2, ncols=2)\n\naxes[0, 0].set_title('Linear normalization')\naxes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)\n\nfor ax, gamma in zip(axes.flat[1:], gammas):\n ax.set_title('Power law $(\\gamma=%1.1f)$' % gamma)\n ax.hist2d(data[:, 0], data[:, 1],\n bins=100, norm=mcolors.PowerNorm(gamma))\n\nfig.tight_layout()\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLVE api/histogram_path.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Building histograms using Rectangles and PolyCollections\n\n\nUsing a path patch to draw rectangles.\nThe technique of using lots of Rectangle instances, or\nthe faster method of using PolyCollections, were implemented before we\nhad proper paths with moveto/lineto, closepoly etc in mpl. Now that\nwe have them, we can draw collections of regularly shaped objects with\nhomogeneous properties more efficiently with a PathCollection. This\nexample makes a histogram -- its more work to set up the vertex arrays\nat the outset, but it should be much faster for large numbers of\nobjects\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.path as path\n\nfig, ax = plt.subplots()\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\n# histogram our data with numpy\n\ndata = np.random.randn(1000)\nn, bins = np.histogram(data, 50)\n\n# get the corners of the rectangles for the histogram\nleft = np.array(bins[:-1])\nright = np.array(bins[1:])\nbottom = np.zeros(len(left))\ntop = bottom + n\n\n\n# we need a (numrects x numsides x 2) numpy array for the path helper\n# function to build a compound path\nXY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T\n\n# get the Path object\nbarpath = path.Path.make_compound_path_from_polys(XY)\n\n# make a patch out of it\npatch = patches.PathPatch(barpath)\nax.add_patch(patch)\n\n# update the view limits\nax.set_xlim(left[0], right[-1])\nax.set_ylim(bottom.min(), top.max())\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLq q api/barchart.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Barchart\n\n\nA bar plot with errorbars and height labels on individual bars\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\n\nN = 5\nmen_means = (20, 35, 30, 35, 27)\nmen_std = (2, 3, 4, 1, 2)\n\nind = np.arange(N) # the x locations for the groups\nwidth = 0.35 # the width of the bars\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std)\n\nwomen_means = (25, 32, 34, 20, 25)\nwomen_std = (3, 5, 2, 3, 3)\nrects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std)\n\n# add some text for labels, title and axes ticks\nax.set_ylabel('Scores')\nax.set_title('Scores by group and gender')\nax.set_xticks(ind + width / 2)\nax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))\n\nax.legend((rects1[0], rects2[0]), ('Men', 'Women'))\n\n\ndef autolabel(rects):\n \"\"\"\n Attach a text label above each bar displaying its height\n \"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,\n '%d' % int(height),\n ha='center', va='bottom')\n\nautolabel(rects1)\nautolabel(rects2)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL2 2 api/date.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Date tick labels\n\n\nShow how to make date plots in matplotlib using date tick locators and\nformatters. See major_minor_demo1.py for more information on\ncontrolling major and minor ticks\n\nAll matplotlib date plotting is done by converting date instances into\ndays since the 0001-01-01 UTC. The conversion, tick locating and\nformatting is done behind the scenes so this is most transparent to\nyou. The dates module provides several converter functions date2num\nand num2date\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport matplotlib.cbook as cbook\n\nyears = mdates.YearLocator() # every year\nmonths = mdates.MonthLocator() # every month\nyearsFmt = mdates.DateFormatter('%Y')\n\n# Load a numpy record array from yahoo csv data with fields date, open, close,\n# volume, adj_close from the mpl-data/example directory. The record array\n# stores the date as an np.datetime64 with a day unit ('D') in the date column.\nwith cbook.get_sample_data('goog.npz') as datafile:\n r = np.load(datafile)['price_data'].view(np.recarray)\n# Matplotlib works better with datetime.datetime than np.datetime64, but the\n# latter is more portable.\ndate = r.date.astype('O')\n\nfig, ax = plt.subplots()\nax.plot(date, r.adj_close)\n\n\n# format the ticks\nax.xaxis.set_major_locator(years)\nax.xaxis.set_major_formatter(yearsFmt)\nax.xaxis.set_minor_locator(months)\n\ndatemin = datetime.date(date.min().year, 1, 1)\ndatemax = datetime.date(date.max().year + 1, 1, 1)\nax.set_xlim(datemin, datemax)\n\n\n# format the coords message box\ndef price(x):\n return '$%1.2f' % x\nax.format_xdata = mdates.DateFormatter('%Y-%m-%d')\nax.format_ydata = price\nax.grid(True)\n\n# rotates and right aligns the x labels, and moves the bottom of the\n# axes up to make room for them\nfig.autofmt_xdate()\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLr api/colorbar_basics.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Colorbar\n\n\nUse colorbar by specifying the mappable object (here\nthe imshow returned object) and the axes to attach the colorbar to.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\n\n# setup some generic data\nN = 37\nx, y = np.mgrid[:N, :N]\nZ = (np.cos(x*0.2) + np.sin(y*0.3))\n\n# mask out the negative and positve values, respectively\nZpos = np.ma.masked_less(Z, 0)\nZneg = np.ma.masked_greater(Z, 0)\n\nfig, (ax1, ax2) = plt.subplots(figsize=(8, 3), ncols=2)\n\n# plot just the positive data and save the\n# color \"mappable\" object returned by ax1.imshow\npos = ax1.imshow(Zpos, cmap='Blues', interpolation='none')\n\n# add the colorbar using the figure's method,\n# telling which mappable we're talking about and\n# which axes object it should be near\nfig.colorbar(pos, ax=ax1)\n\n# repeat everything above for the negative data\nneg = ax2.imshow(Zneg, cmap='Reds_r', interpolation='none')\nfig.colorbar(neg, ax=ax2)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLc< api/mathtext_asarray.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# A mathtext image as numpy array\n\n\nMake images from LaTeX strings.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.mathtext as mathtext\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.rc('image', origin='upper')\n\nparser = mathtext.MathTextParser(\"Bitmap\")\nparser.to_png('test2.png',\n r'$\\left[\\left\\lfloor\\frac{5}{\\frac{\\left(3\\right)}{4}} '\n r'y\\right)\\right]$', color='green', fontsize=14, dpi=100)\n\nrgba1, depth1 = parser.to_rgba(\n r'IQ: $\\sigma_i=15$', color='blue', fontsize=20, dpi=200)\nrgba2, depth2 = parser.to_rgba(\n r'some other string', color='red', fontsize=20, dpi=200)\n\nfig = plt.figure()\nfig.figimage(rgba1.astype(float)/255., 100, 100)\nfig.figimage(rgba2.astype(float)/255., 100, 300)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL&]8H H # api/custom_projection_example.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Custom projection\n\n\nShowcase Hammer projection by alleviating many features of\nmatplotlib.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import unicode_literals\n\nimport matplotlib\nfrom matplotlib.axes import Axes\nfrom matplotlib.patches import Circle\nfrom matplotlib.path import Path\nfrom matplotlib.ticker import NullLocator, Formatter, FixedLocator\nfrom matplotlib.transforms import Affine2D, BboxTransformTo, Transform\nfrom matplotlib.projections import register_projection\nimport matplotlib.spines as mspines\nimport matplotlib.axis as maxis\nimport numpy as np\n\nrcParams = matplotlib.rcParams\n\n# This example projection class is rather long, but it is designed to\n# illustrate many features, not all of which will be used every time.\n# It is also common to factor out a lot of these methods into common\n# code used by a number of projections with similar characteristics\n# (see geo.py).\n\n\nclass GeoAxes(Axes):\n \"\"\"\n An abstract base class for geographic projections\n \"\"\"\n class ThetaFormatter(Formatter):\n \"\"\"\n Used to format the theta tick labels. Converts the native\n unit of radians into degrees and adds a degree symbol.\n \"\"\"\n def __init__(self, round_to=1.0):\n self._round_to = round_to\n\n def __call__(self, x, pos=None):\n degrees = np.round(np.rad2deg(x) / self._round_to) * self._round_to\n if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:\n return r\"$%0.0f^\\circ$\" % degrees\n else:\n return \"%0.0f\\N{DEGREE SIGN}\" % degrees\n\n RESOLUTION = 75\n\n def _init_axis(self):\n self.xaxis = maxis.XAxis(self)\n self.yaxis = maxis.YAxis(self)\n # Do not register xaxis or yaxis with spines -- as done in\n # Axes._init_axis() -- until GeoAxes.xaxis.cla() works.\n # self.spines['geo'].register_axis(self.yaxis)\n self._update_transScale()\n\n def cla(self):\n Axes.cla(self)\n\n self.set_longitude_grid(30)\n self.set_latitude_grid(15)\n self.set_longitude_grid_ends(75)\n self.xaxis.set_minor_locator(NullLocator())\n self.yaxis.set_minor_locator(NullLocator())\n self.xaxis.set_ticks_position('none')\n self.yaxis.set_ticks_position('none')\n self.yaxis.set_tick_params(label1On=True)\n # Why do we need to turn on yaxis tick labels, but\n # xaxis tick labels are already on?\n\n self.grid(rcParams['axes.grid'])\n\n Axes.set_xlim(self, -np.pi, np.pi)\n Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)\n\n def _set_lim_and_transforms(self):\n # A (possibly non-linear) projection on the (already scaled) data\n\n # There are three important coordinate spaces going on here:\n #\n # 1. Data space: The space of the data itself\n #\n # 2. Axes space: The unit rectangle (0, 0) to (1, 1)\n # covering the entire plot area.\n #\n # 3. Display space: The coordinates of the resulting image,\n # often in pixels or dpi/inch.\n\n # This function makes heavy use of the Transform classes in\n # ``lib/matplotlib/transforms.py.`` For more information, see\n # the inline documentation there.\n\n # The goal of the first two transformations is to get from the\n # data space (in this case longitude and latitude) to axes\n # space. It is separated into a non-affine and affine part so\n # that the non-affine part does not have to be recomputed when\n # a simple affine change to the figure has been made (such as\n # resizing the window or changing the dpi).\n\n # 1) The core transformation from data space into\n # rectilinear space defined in the HammerTransform class.\n self.transProjection = self._get_core_transform(self.RESOLUTION)\n\n # 2) The above has an output range that is not in the unit\n # rectangle, so scale and translate it so it fits correctly\n # within the axes. The peculiar calculations of xscale and\n # yscale are specific to a Aitoff-Hammer projection, so don't\n # worry about them too much.\n self.transAffine = self._get_affine_transform()\n\n # 3) This is the transformation from axes space to display\n # space.\n self.transAxes = BboxTransformTo(self.bbox)\n\n # Now put these 3 transforms together -- from data all the way\n # to display coordinates. Using the '+' operator, these\n # transforms will be applied \"in order\". The transforms are\n # automatically simplified, if possible, by the underlying\n # transformation framework.\n self.transData = \\\n self.transProjection + \\\n self.transAffine + \\\n self.transAxes\n\n # The main data transformation is set up. Now deal with\n # gridlines and tick labels.\n\n # Longitude gridlines and ticklabels. The input to these\n # transforms are in display space in x and axes space in y.\n # Therefore, the input values will be in range (-xmin, 0),\n # (xmax, 1). The goal of these transforms is to go from that\n # space to display space. The tick labels will be offset 4\n # pixels from the equator.\n self._xaxis_pretransform = \\\n Affine2D() \\\n .scale(1.0, self._longitude_cap * 2.0) \\\n .translate(0.0, -self._longitude_cap)\n self._xaxis_transform = \\\n self._xaxis_pretransform + \\\n self.transData\n self._xaxis_text1_transform = \\\n Affine2D().scale(1.0, 0.0) + \\\n self.transData + \\\n Affine2D().translate(0.0, 4.0)\n self._xaxis_text2_transform = \\\n Affine2D().scale(1.0, 0.0) + \\\n self.transData + \\\n Affine2D().translate(0.0, -4.0)\n\n # Now set up the transforms for the latitude ticks. The input to\n # these transforms are in axes space in x and display space in\n # y. Therefore, the input values will be in range (0, -ymin),\n # (1, ymax). The goal of these transforms is to go from that\n # space to display space. The tick labels will be offset 4\n # pixels from the edge of the axes ellipse.\n yaxis_stretch = Affine2D().scale(np.pi*2, 1).translate(-np.pi, 0)\n yaxis_space = Affine2D().scale(1.0, 1.1)\n self._yaxis_transform = \\\n yaxis_stretch + \\\n self.transData\n yaxis_text_base = \\\n yaxis_stretch + \\\n self.transProjection + \\\n (yaxis_space +\n self.transAffine +\n self.transAxes)\n self._yaxis_text1_transform = \\\n yaxis_text_base + \\\n Affine2D().translate(-8.0, 0.0)\n self._yaxis_text2_transform = \\\n yaxis_text_base + \\\n Affine2D().translate(8.0, 0.0)\n\n def _get_affine_transform(self):\n transform = self._get_core_transform(1)\n xscale, _ = transform.transform_point((np.pi, 0))\n _, yscale = transform.transform_point((0, np.pi / 2.0))\n return Affine2D() \\\n .scale(0.5 / xscale, 0.5 / yscale) \\\n .translate(0.5, 0.5)\n\n def get_xaxis_transform(self, which='grid'):\n \"\"\"\n Override this method to provide a transformation for the\n x-axis tick labels.\n\n Returns a tuple of the form (transform, valign, halign)\n \"\"\"\n if which not in ['tick1', 'tick2', 'grid']:\n msg = \"'which' must be on of [ 'tick1' | 'tick2' | 'grid' ]\"\n raise ValueError(msg)\n return self._xaxis_transform\n\n def get_xaxis_text1_transform(self, pad):\n return self._xaxis_text1_transform, 'bottom', 'center'\n\n def get_xaxis_text2_transform(self, pad):\n \"\"\"\n Override this method to provide a transformation for the\n secondary x-axis tick labels.\n\n Returns a tuple of the form (transform, valign, halign)\n \"\"\"\n return self._xaxis_text2_transform, 'top', 'center'\n\n def get_yaxis_transform(self, which='grid'):\n \"\"\"\n Override this method to provide a transformation for the\n y-axis grid and ticks.\n \"\"\"\n if which not in ['tick1', 'tick2', 'grid']:\n msg = \"'which' must be one of [ 'tick1' | 'tick2' | 'grid' ]\"\n raise ValueError(msg)\n return self._yaxis_transform\n\n def get_yaxis_text1_transform(self, pad):\n \"\"\"\n Override this method to provide a transformation for the\n y-axis tick labels.\n\n Returns a tuple of the form (transform, valign, halign)\n \"\"\"\n return self._yaxis_text1_transform, 'center', 'right'\n\n def get_yaxis_text2_transform(self, pad):\n \"\"\"\n Override this method to provide a transformation for the\n secondary y-axis tick labels.\n\n Returns a tuple of the form (transform, valign, halign)\n \"\"\"\n return self._yaxis_text2_transform, 'center', 'left'\n\n def _gen_axes_patch(self):\n \"\"\"\n Override this method to define the shape that is used for the\n background of the plot. It should be a subclass of Patch.\n\n In this case, it is a Circle (that may be warped by the axes\n transform into an ellipse). Any data and gridlines will be\n clipped to this shape.\n \"\"\"\n return Circle((0.5, 0.5), 0.5)\n\n def _gen_axes_spines(self):\n return {'geo': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)}\n\n def set_yscale(self, *args, **kwargs):\n if args[0] != 'linear':\n raise NotImplementedError\n\n # Prevent the user from applying scales to one or both of the\n # axes. In this particular case, scaling the axes wouldn't make\n # sense, so we don't allow it.\n set_xscale = set_yscale\n\n # Prevent the user from changing the axes limits. In our case, we\n # want to display the whole sphere all the time, so we override\n # set_xlim and set_ylim to ignore any input. This also applies to\n # interactive panning and zooming in the GUI interfaces.\n def set_xlim(self, *args, **kwargs):\n raise TypeError(\"It is not possible to change axes limits \"\n \"for geographic projections. Please consider \"\n \"using Basemap or Cartopy.\")\n\n set_ylim = set_xlim\n\n def format_coord(self, lon, lat):\n \"\"\"\n Override this method to change how the values are displayed in\n the status bar.\n\n In this case, we want them to be displayed in degrees N/S/E/W.\n \"\"\"\n lon, lat = np.rad2deg([lon, lat])\n if lat >= 0.0:\n ns = 'N'\n else:\n ns = 'S'\n if lon >= 0.0:\n ew = 'E'\n else:\n ew = 'W'\n return ('%f\\N{DEGREE SIGN}%s, %f\\N{DEGREE SIGN}%s'\n % (abs(lat), ns, abs(lon), ew))\n\n def set_longitude_grid(self, degrees):\n \"\"\"\n Set the number of degrees between each longitude grid.\n\n This is an example method that is specific to this projection\n class -- it provides a more convenient interface to set the\n ticking than set_xticks would.\n \"\"\"\n # Skip -180 and 180, which are the fixed limits.\n grid = np.arange(-180 + degrees, 180, degrees)\n self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))\n self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))\n\n def set_latitude_grid(self, degrees):\n \"\"\"\n Set the number of degrees between each longitude grid.\n\n This is an example method that is specific to this projection\n class -- it provides a more convenient interface than\n set_yticks would.\n \"\"\"\n # Skip -90 and 90, which are the fixed limits.\n grid = np.arange(-90 + degrees, 90, degrees)\n self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))\n self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))\n\n def set_longitude_grid_ends(self, degrees):\n \"\"\"\n Set the latitude(s) at which to stop drawing the longitude grids.\n\n Often, in geographic projections, you wouldn't want to draw\n longitude gridlines near the poles. This allows the user to\n specify the degree at which to stop drawing longitude grids.\n\n This is an example method that is specific to this projection\n class -- it provides an interface to something that has no\n analogy in the base Axes class.\n \"\"\"\n self._longitude_cap = np.deg2rad(degrees)\n self._xaxis_pretransform \\\n .clear() \\\n .scale(1.0, self._longitude_cap * 2.0) \\\n .translate(0.0, -self._longitude_cap)\n\n def get_data_ratio(self):\n \"\"\"\n Return the aspect ratio of the data itself.\n\n This method should be overridden by any Axes that have a\n fixed data ratio.\n \"\"\"\n return 1.0\n\n # Interactive panning and zooming is not supported with this projection,\n # so we override all of the following methods to disable it.\n def can_zoom(self):\n \"\"\"\n Return *True* if this axes supports the zoom box button functionality.\n This axes object does not support interactive zoom box.\n \"\"\"\n return False\n\n def can_pan(self):\n \"\"\"\n Return *True* if this axes supports the pan/zoom button functionality.\n This axes object does not support interactive pan/zoom.\n \"\"\"\n return False\n\n def start_pan(self, x, y, button):\n pass\n\n def end_pan(self):\n pass\n\n def drag_pan(self, button, key, x, y):\n pass\n\n\nclass HammerAxes(GeoAxes):\n \"\"\"\n A custom class for the Aitoff-Hammer projection, an equal-area map\n projection.\n\n https://en.wikipedia.org/wiki/Hammer_projection\n \"\"\"\n\n # The projection must specify a name. This will be used by the\n # user to select the projection,\n # i.e. ``subplot(111, projection='custom_hammer')``.\n name = 'custom_hammer'\n\n class HammerTransform(Transform):\n \"\"\"\n The base Hammer transform.\n \"\"\"\n input_dims = 2\n output_dims = 2\n is_separable = False\n\n def __init__(self, resolution):\n \"\"\"\n Create a new Hammer transform. Resolution is the number of steps\n to interpolate between each input line segment to approximate its\n path in curved Hammer space.\n \"\"\"\n Transform.__init__(self)\n self._resolution = resolution\n\n def transform_non_affine(self, ll):\n longitude = ll[:, 0:1]\n latitude = ll[:, 1:2]\n\n # Pre-compute some values\n half_long = longitude / 2.0\n cos_latitude = np.cos(latitude)\n sqrt2 = np.sqrt(2.0)\n\n alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long))\n x = (2.0 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha\n y = (sqrt2 * np.sin(latitude)) / alpha\n return np.concatenate((x, y), 1)\n transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__\n\n def transform_path_non_affine(self, path):\n # vertices = path.vertices\n ipath = path.interpolated(self._resolution)\n return Path(self.transform(ipath.vertices), ipath.codes)\n transform_path_non_affine.__doc__ = \\\n Transform.transform_path_non_affine.__doc__\n\n def inverted(self):\n return HammerAxes.InvertedHammerTransform(self._resolution)\n inverted.__doc__ = Transform.inverted.__doc__\n\n class InvertedHammerTransform(Transform):\n input_dims = 2\n output_dims = 2\n is_separable = False\n\n def __init__(self, resolution):\n Transform.__init__(self)\n self._resolution = resolution\n\n def transform_non_affine(self, xy):\n x, y = xy.T\n z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2)\n longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1)))\n latitude = np.arcsin(y*z)\n return np.column_stack([longitude, latitude])\n transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__\n\n def inverted(self):\n return HammerAxes.HammerTransform(self._resolution)\n inverted.__doc__ = Transform.inverted.__doc__\n\n def __init__(self, *args, **kwargs):\n self._longitude_cap = np.pi / 2.0\n GeoAxes.__init__(self, *args, **kwargs)\n self.set_aspect(0.5, adjustable='box', anchor='C')\n self.cla()\n\n def _get_core_transform(self, resolution):\n return self.HammerTransform(resolution)\n\n\n# Now register the projection with matplotlib so the user can select\n# it.\nregister_projection(HammerAxes)\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n # Now make a simple example using the custom projection.\n plt.subplot(111, projection=\"custom_hammer\")\n p = plt.plot([-1, 1, 1], [-1, -1, 1], \"o-\")\n plt.grid(True)\n\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLB4
api/line_with_text.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Artist within an artist\n\n\nOverride basic methods so an artist can contain another\nartist. In this case, the line contains a Text instance to label it.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as lines\nimport matplotlib.transforms as mtransforms\nimport matplotlib.text as mtext\n\n\nclass MyLine(lines.Line2D):\n def __init__(self, *args, **kwargs):\n # we'll update the position when the line data is set\n self.text = mtext.Text(0, 0, '')\n lines.Line2D.__init__(self, *args, **kwargs)\n\n # we can't access the label attr until *after* the line is\n # inited\n self.text.set_text(self.get_label())\n\n def set_figure(self, figure):\n self.text.set_figure(figure)\n lines.Line2D.set_figure(self, figure)\n\n def set_axes(self, axes):\n self.text.set_axes(axes)\n lines.Line2D.set_axes(self, axes)\n\n def set_transform(self, transform):\n # 2 pixel offset\n texttrans = transform + mtransforms.Affine2D().translate(2, 2)\n self.text.set_transform(texttrans)\n lines.Line2D.set_transform(self, transform)\n\n def set_data(self, x, y):\n if len(x):\n self.text.set_position((x[-1], y[-1]))\n\n lines.Line2D.set_data(self, x, y)\n\n def draw(self, renderer):\n # draw my label at the end of the line with 2 pixel offset\n lines.Line2D.draw(self, renderer)\n self.text.draw(renderer)\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nfig, ax = plt.subplots()\nx, y = np.random.rand(2, 20)\nline = MyLine(x, y, mfc='red', ms=12, label='line label')\n#line.text.set_text('line label')\nline.text.set_color('red')\nline.text.set_fontsize(16)\n\n\nax.add_line(line)\n\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL#k api/image_zcoord.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Modifying the coordinate formatter\n\n\nModify the coordinate formatter to report the image \"z\"\nvalue of the nearest pixel given x and y\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nX = 10*np.random.rand(5, 3)\n\nfig, ax = plt.subplots()\nax.imshow(X, interpolation='nearest')\n\nnumrows, numcols = X.shape\n\n\ndef format_coord(x, y):\n col = int(x + 0.5)\n row = int(y + 0.5)\n if col >= 0 and col < numcols and row >= 0 and row < numrows:\n z = X[row, col]\n return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x, y, z)\n else:\n return 'x=%1.4f, y=%1.4f' % (x, y)\n\nax.format_coord = format_coord\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL9k(
(
api/affine_image.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Affine transform of an image\n\n\nFor the backends that support draw_image with optional affine\ntransform (e.g., agg, ps backend), the image of the output should\nhave its boundary match the dashed yellow rectangle.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as mtransforms\n\n\ndef get_image():\n delta = 0.25\n x = y = np.arange(-3.0, 3.0, delta)\n X, Y = np.meshgrid(x, y)\n Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)\n Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)\n Z = Z2 - Z1 # difference of Gaussians\n return Z\n\n\ndef do_plot(ax, Z, transform):\n im = ax.imshow(Z, interpolation='none',\n origin='lower',\n extent=[-2, 4, -3, 2], clip_on=True)\n\n trans_data = transform + ax.transData\n im.set_transform(trans_data)\n\n # display intended extent of the image\n x1, x2, y1, y2 = im.get_extent()\n ax.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], \"y--\",\n transform=trans_data)\n ax.set_xlim(-5, 5)\n ax.set_ylim(-4, 4)\n\n\n# prepare image and figure\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)\nZ = get_image()\n\n# image rotation\ndo_plot(ax1, Z, mtransforms.Affine2D().rotate_deg(30))\n\n# image skew\ndo_plot(ax2, Z, mtransforms.Affine2D().skew_deg(30, 15))\n\n# scale and reflection\ndo_plot(ax3, Z, mtransforms.Affine2D().scale(-1, .5))\n\n# everything and a translation\ndo_plot(ax4, Z, mtransforms.Affine2D().\n rotate_deg(30).skew_deg(30, 15).scale(-1, .5).translate(.5, -1))\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLs*x
api/sankey_links.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Long chain of connections using Sankey\n\n\nDemonstrate/test the Sankey class by producing a long chain of connections.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from itertools import cycle\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.sankey import Sankey\n\nlinks_per_side = 6\n\n\ndef side(sankey, n=1):\n \"\"\"Generate a side chain.\"\"\"\n prior = len(sankey.diagrams)\n for i in range(0, 2*n, 2):\n sankey.add(flows=[1, -1], orientations=[-1, -1],\n patchlabel=str(prior + i),\n prior=prior + i - 1, connect=(1, 0), alpha=0.5)\n sankey.add(flows=[1, -1], orientations=[1, 1],\n patchlabel=str(prior + i + 1),\n prior=prior + i, connect=(1, 0), alpha=0.5)\n\n\ndef corner(sankey):\n \"\"\"Generate a corner link.\"\"\"\n prior = len(sankey.diagrams)\n sankey.add(flows=[1, -1], orientations=[0, 1],\n patchlabel=str(prior), facecolor='k',\n prior=prior - 1, connect=(1, 0), alpha=0.5)\n\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],\n title=\"Why would you want to do this?\\n(But you could.)\")\nsankey = Sankey(ax=ax, unit=None)\nsankey.add(flows=[1, -1], orientations=[0, 1],\n patchlabel=\"0\", facecolor='k',\n rotation=45)\nside(sankey, n=links_per_side)\ncorner(sankey)\nside(sankey, n=links_per_side)\ncorner(sankey)\nside(sankey, n=links_per_side)\ncorner(sankey)\nside(sankey, n=links_per_side)\nsankey.finish()\n# Notice:\n# 1. The alignment doesn't drift significantly (if at all; with 16007\n# subdiagrams there is still closure).\n# 2. The first diagram is rotated 45 deg, so all other diagrams are rotated\n# accordingly.\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLl_" " api/sankey_basics.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# The Sankey class\n\n\nDemonstrate the Sankey class by producing three basic diagrams.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.sankey import Sankey"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Example 1 -- Mostly defaults\n\nThis demonstrates how to create a simple diagram by implicitly calling the\nSankey.add() method and by appending finish() to the call to the class.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10],\n labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'],\n orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish()\nplt.title(\"The default settings produce a diagram like this.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice:\n\n1. Axes weren't provided when Sankey() was instantiated, so they were\n created automatically.\n2. The scale argument wasn't necessary since the data was already\n normalized.\n3. By default, the lengths of the paths are justified.\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Example 2\n\nThis demonstrates:\n\n1. Setting one path longer than the others\n2. Placing a label in the middle of the diagram\n3. Using the scale argument to normalize the flows\n4. Implicitly passing keyword arguments to PathPatch()\n5. Changing the angle of the arrow heads\n6. Changing the offset between the tips of the paths and their labels\n7. Formatting the numbers in the path labels and the associated unit\n8. Changing the appearance of the patch and the labels after the figure is\n created\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig = plt.figure()\nax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],\n title=\"Flow Diagram of a Widget\")\nsankey = Sankey(ax=ax, scale=0.01, offset=0.2, head_angle=180,\n format='%.0f', unit='%')\nsankey.add(flows=[25, 0, 60, -10, -20, -5, -15, -10, -40],\n labels=['', '', '', 'First', 'Second', 'Third', 'Fourth',\n 'Fifth', 'Hurray!'],\n orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0],\n pathlengths=[0.25, 0.25, 0.25, 0.25, 0.25, 0.6, 0.25, 0.25,\n 0.25],\n patchlabel=\"Widget\\nA\") # Arguments to matplotlib.patches.PathPatch()\ndiagrams = sankey.finish()\ndiagrams[0].texts[-1].set_color('r')\ndiagrams[0].text.set_fontweight('bold')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice:\n\n1. Since the sum of the flows is nonzero, the width of the trunk isn't\n uniform. If verbose.level is helpful (in matplotlibrc), a message is\n given in the terminal window.\n2. The second flow doesn't appear because its value is zero. Again, if\n verbose.level is helpful, a message is given in the terminal window.\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Example 3\n\nThis demonstrates:\n\n1. Connecting two systems\n2. Turning off the labels of the quantities\n3. Adding a legend\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig = plt.figure()\nax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title=\"Two Systems\")\nflows = [0.25, 0.15, 0.60, -0.10, -0.05, -0.25, -0.15, -0.10, -0.35]\nsankey = Sankey(ax=ax, unit=None)\nsankey.add(flows=flows, label='one',\n orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0])\nsankey.add(flows=[-0.25, 0.15, 0.1], label='two',\n orientations=[-1, -1, -1], prior=0, connect=(0, 0))\ndiagrams = sankey.finish()\ndiagrams[-1].patch.set_hatch('/')\nplt.legend(loc='best')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that only one connection is specified, but the systems form a\ncircuit since: (1) the lengths of the paths are justified and (2) the\norientation and ordering of the flows is mirrored.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLL$ $ api/radar_chart.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n======================================\nRadar chart (aka spider or star chart)\n======================================\n\nThis example creates a radar chart, also known as a spider or star chart [1]_.\n\nAlthough this example allows a frame of either 'circle' or 'polygon', polygon\nframes don't have proper gridlines (the lines are circles instead of polygons).\nIt's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in\nmatplotlib.axis to the desired number of vertices, but the orientation of the\npolygon is not aligned with the radial axes.\n\n.. [1] http://en.wikipedia.org/wiki/Radar_chart\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nfrom matplotlib.spines import Spine\nfrom matplotlib.projections.polar import PolarAxes\nfrom matplotlib.projections import register_projection\n\n\ndef radar_factory(num_vars, frame='circle'):\n \"\"\"Create a radar chart with `num_vars` axes.\n\n This function creates a RadarAxes projection and registers it.\n\n Parameters\n ----------\n num_vars : int\n Number of variables for radar chart.\n frame : {'circle' | 'polygon'}\n Shape of frame surrounding axes.\n\n \"\"\"\n # calculate evenly-spaced axis angles\n theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)\n\n def draw_poly_patch(self):\n # rotate theta such that the first axis is at the top\n verts = unit_poly_verts(theta + np.pi / 2)\n return plt.Polygon(verts, closed=True, edgecolor='k')\n\n def draw_circle_patch(self):\n # unit circle centered on (0.5, 0.5)\n return plt.Circle((0.5, 0.5), 0.5)\n\n patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch}\n if frame not in patch_dict:\n raise ValueError('unknown value for `frame`: %s' % frame)\n\n class RadarAxes(PolarAxes):\n\n name = 'radar'\n # use 1 line segment to connect specified points\n RESOLUTION = 1\n # define draw_frame method\n draw_patch = patch_dict[frame]\n\n def __init__(self, *args, **kwargs):\n super(RadarAxes, self).__init__(*args, **kwargs)\n # rotate plot such that the first axis is at the top\n self.set_theta_zero_location('N')\n\n def fill(self, *args, **kwargs):\n \"\"\"Override fill so that line is closed by default\"\"\"\n closed = kwargs.pop('closed', True)\n return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)\n\n def plot(self, *args, **kwargs):\n \"\"\"Override plot so that line is closed by default\"\"\"\n lines = super(RadarAxes, self).plot(*args, **kwargs)\n for line in lines:\n self._close_line(line)\n\n def _close_line(self, line):\n x, y = line.get_data()\n # FIXME: markers at x[0], y[0] get doubled-up\n if x[0] != x[-1]:\n x = np.concatenate((x, [x[0]]))\n y = np.concatenate((y, [y[0]]))\n line.set_data(x, y)\n\n def set_varlabels(self, labels):\n self.set_thetagrids(np.degrees(theta), labels)\n\n def _gen_axes_patch(self):\n return self.draw_patch()\n\n def _gen_axes_spines(self):\n if frame == 'circle':\n return PolarAxes._gen_axes_spines(self)\n # The following is a hack to get the spines (i.e. the axes frame)\n # to draw correctly for a polygon frame.\n\n # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`.\n spine_type = 'circle'\n verts = unit_poly_verts(theta + np.pi / 2)\n # close off polygon by repeating first vertex\n verts.append(verts[0])\n path = Path(verts)\n\n spine = Spine(self, spine_type, path)\n spine.set_transform(self.transAxes)\n return {'polar': spine}\n\n register_projection(RadarAxes)\n return theta\n\n\ndef unit_poly_verts(theta):\n \"\"\"Return vertices of polygon for subplot axes.\n\n This polygon is circumscribed by a unit circle centered at (0.5, 0.5)\n \"\"\"\n x0, y0, r = [0.5] * 3\n verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]\n return verts\n\n\ndef example_data():\n # The following data is from the Denver Aerosol Sources and Health study.\n # See doi:10.1016/j.atmosenv.2008.12.017\n #\n # The data are pollution source profile estimates for five modeled\n # pollution sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical\n # species. The radar charts are experimented with here to see if we can\n # nicely visualize how the modeled source profiles change across four\n # scenarios:\n # 1) No gas-phase species present, just seven particulate counts on\n # Sulfate\n # Nitrate\n # Elemental Carbon (EC)\n # Organic Carbon fraction 1 (OC)\n # Organic Carbon fraction 2 (OC2)\n # Organic Carbon fraction 3 (OC3)\n # Pyrolized Organic Carbon (OP)\n # 2)Inclusion of gas-phase specie carbon monoxide (CO)\n # 3)Inclusion of gas-phase specie ozone (O3).\n # 4)Inclusion of both gas-phase species is present...\n data = [\n ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],\n ('Basecase', [\n [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],\n [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],\n [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],\n [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],\n [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]),\n ('With CO', [\n [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],\n [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],\n [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],\n [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],\n [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]),\n ('With O3', [\n [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],\n [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],\n [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],\n [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],\n [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]),\n ('CO & O3', [\n [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],\n [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],\n [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],\n [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],\n [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]])\n ]\n return data\n\n\nif __name__ == '__main__':\n N = 9\n theta = radar_factory(N, frame='polygon')\n\n data = example_data()\n spoke_labels = data.pop(0)\n\n fig, axes = plt.subplots(figsize=(9, 9), nrows=2, ncols=2,\n subplot_kw=dict(projection='radar'))\n fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)\n\n colors = ['b', 'r', 'g', 'm', 'y']\n # Plot the four cases from the example data on separate axes\n for ax, (title, case_data) in zip(axes.flatten(), data):\n ax.set_rgrids([0.2, 0.4, 0.6, 0.8])\n ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),\n horizontalalignment='center', verticalalignment='center')\n for d, color in zip(case_data, colors):\n ax.plot(theta, d, color=color)\n ax.fill(theta, d, facecolor=color, alpha=0.25)\n ax.set_varlabels(spoke_labels)\n\n # add legend relative to top-left plot\n ax = axes[0, 0]\n labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')\n legend = ax.legend(labels, loc=(0.9, .95),\n labelspacing=0.1, fontsize='small')\n\n fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',\n horizontalalignment='center', color='black', weight='bold',\n size='large')\n\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLn9 n9 api/skewt.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n===========================================================\nSkewT-logP diagram: using transforms and custom projections\n===========================================================\n\nThis serves as an intensive exercise of matplotlib's transforms and custom\nprojection API. This example produces a so-called SkewT-logP diagram, which is\na common plot in meteorology for displaying vertical profiles of temperature.\nAs far as matplotlib is concerned, the complexity comes from having X and Y\naxes that are not orthogonal. This is handled by including a skew component to\nthe basic Axes transforms. Additional complexity comes in handling the fact\nthat the upper and lower X-axes have different data ranges, which necessitates\na bunch of custom classes for ticks,spines, and the axis to handle this.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from matplotlib.axes import Axes\nimport matplotlib.transforms as transforms\nimport matplotlib.axis as maxis\nimport matplotlib.spines as mspines\nfrom matplotlib.projections import register_projection\n\n\n# The sole purpose of this class is to look at the upper, lower, or total\n# interval as appropriate and see what parts of the tick to draw, if any.\nclass SkewXTick(maxis.XTick):\n def update_position(self, loc):\n # This ensures that the new value of the location is set before\n # any other updates take place\n self._loc = loc\n super(SkewXTick, self).update_position(loc)\n\n def _has_default_loc(self):\n return self.get_loc() is None\n\n def _need_lower(self):\n return (self._has_default_loc() or\n transforms.interval_contains(self.axes.lower_xlim,\n self.get_loc()))\n\n def _need_upper(self):\n return (self._has_default_loc() or\n transforms.interval_contains(self.axes.upper_xlim,\n self.get_loc()))\n\n @property\n def gridOn(self):\n return (self._gridOn and (self._has_default_loc() or\n transforms.interval_contains(self.get_view_interval(),\n self.get_loc())))\n\n @gridOn.setter\n def gridOn(self, value):\n self._gridOn = value\n\n @property\n def tick1On(self):\n return self._tick1On and self._need_lower()\n\n @tick1On.setter\n def tick1On(self, value):\n self._tick1On = value\n\n @property\n def label1On(self):\n return self._label1On and self._need_lower()\n\n @label1On.setter\n def label1On(self, value):\n self._label1On = value\n\n @property\n def tick2On(self):\n return self._tick2On and self._need_upper()\n\n @tick2On.setter\n def tick2On(self, value):\n self._tick2On = value\n\n @property\n def label2On(self):\n return self._label2On and self._need_upper()\n\n @label2On.setter\n def label2On(self, value):\n self._label2On = value\n\n def get_view_interval(self):\n return self.axes.xaxis.get_view_interval()\n\n\n# This class exists to provide two separate sets of intervals to the tick,\n# as well as create instances of the custom tick\nclass SkewXAxis(maxis.XAxis):\n def _get_tick(self, major):\n return SkewXTick(self.axes, None, '', major=major)\n\n def get_view_interval(self):\n return self.axes.upper_xlim[0], self.axes.lower_xlim[1]\n\n\n# This class exists to calculate the separate data range of the\n# upper X-axis and draw the spine there. It also provides this range\n# to the X-axis artist for ticking and gridlines\nclass SkewSpine(mspines.Spine):\n def _adjust_location(self):\n pts = self._path.vertices\n if self.spine_type == 'top':\n pts[:, 0] = self.axes.upper_xlim\n else:\n pts[:, 0] = self.axes.lower_xlim\n\n\n# This class handles registration of the skew-xaxes as a projection as well\n# as setting up the appropriate transformations. It also overrides standard\n# spines and axes instances as appropriate.\nclass SkewXAxes(Axes):\n # The projection must specify a name. This will be used be the\n # user to select the projection, i.e. ``subplot(111,\n # projection='skewx')``.\n name = 'skewx'\n\n def _init_axis(self):\n # Taken from Axes and modified to use our modified X-axis\n self.xaxis = SkewXAxis(self)\n self.spines['top'].register_axis(self.xaxis)\n self.spines['bottom'].register_axis(self.xaxis)\n self.yaxis = maxis.YAxis(self)\n self.spines['left'].register_axis(self.yaxis)\n self.spines['right'].register_axis(self.yaxis)\n\n def _gen_axes_spines(self):\n spines = {'top': SkewSpine.linear_spine(self, 'top'),\n 'bottom': mspines.Spine.linear_spine(self, 'bottom'),\n 'left': mspines.Spine.linear_spine(self, 'left'),\n 'right': mspines.Spine.linear_spine(self, 'right')}\n return spines\n\n def _set_lim_and_transforms(self):\n \"\"\"\n This is called once when the plot is created to set up all the\n transforms for the data, text and grids.\n \"\"\"\n rot = 30\n\n # Get the standard transform setup from the Axes base class\n Axes._set_lim_and_transforms(self)\n\n # Need to put the skew in the middle, after the scale and limits,\n # but before the transAxes. This way, the skew is done in Axes\n # coordinates thus performing the transform around the proper origin\n # We keep the pre-transAxes transform around for other users, like the\n # spines for finding bounds\n self.transDataToAxes = self.transScale + \\\n self.transLimits + transforms.Affine2D().skew_deg(rot, 0)\n\n # Create the full transform from Data to Pixels\n self.transData = self.transDataToAxes + self.transAxes\n\n # Blended transforms like this need to have the skewing applied using\n # both axes, in axes coords like before.\n self._xaxis_transform = (transforms.blended_transform_factory(\n self.transScale + self.transLimits,\n transforms.IdentityTransform()) +\n transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes\n\n @property\n def lower_xlim(self):\n return self.axes.viewLim.intervalx\n\n @property\n def upper_xlim(self):\n pts = [[0., 1.], [1., 1.]]\n return self.transDataToAxes.inverted().transform(pts)[:, 0]\n\n\n# Now register the projection with matplotlib so the user can select\n# it.\nregister_projection(SkewXAxes)\n\nif __name__ == '__main__':\n # Now make a simple example using the custom projection.\n from matplotlib.ticker import (MultipleLocator, NullFormatter,\n ScalarFormatter)\n import matplotlib.pyplot as plt\n from six import StringIO\n import numpy as np\n\n # Some examples data\n data_txt = '''\n 978.0 345 7.8 0.8 61 4.16 325 14 282.7 294.6 283.4\n 971.0 404 7.2 0.2 61 4.01 327 17 282.7 294.2 283.4\n 946.7 610 5.2 -1.8 61 3.56 335 26 282.8 293.0 283.4\n 944.0 634 5.0 -2.0 61 3.51 336 27 282.8 292.9 283.4\n 925.0 798 3.4 -2.6 65 3.43 340 32 282.8 292.7 283.4\n 911.8 914 2.4 -2.7 69 3.46 345 37 282.9 292.9 283.5\n 906.0 966 2.0 -2.7 71 3.47 348 39 283.0 293.0 283.6\n 877.9 1219 0.4 -3.2 77 3.46 0 48 283.9 293.9 284.5\n 850.0 1478 -1.3 -3.7 84 3.44 0 47 284.8 294.8 285.4\n 841.0 1563 -1.9 -3.8 87 3.45 358 45 285.0 295.0 285.6\n 823.0 1736 1.4 -0.7 86 4.44 353 42 290.3 303.3 291.0\n 813.6 1829 4.5 1.2 80 5.17 350 40 294.5 309.8 295.4\n 809.0 1875 6.0 2.2 77 5.57 347 39 296.6 313.2 297.6\n 798.0 1988 7.4 -0.6 57 4.61 340 35 299.2 313.3 300.1\n 791.0 2061 7.6 -1.4 53 4.39 335 33 300.2 313.6 301.0\n 783.9 2134 7.0 -1.7 54 4.32 330 31 300.4 313.6 301.2\n 755.1 2438 4.8 -3.1 57 4.06 300 24 301.2 313.7 301.9\n 727.3 2743 2.5 -4.4 60 3.81 285 29 301.9 313.8 302.6\n 700.5 3048 0.2 -5.8 64 3.57 275 31 302.7 313.8 303.3\n 700.0 3054 0.2 -5.8 64 3.56 280 31 302.7 313.8 303.3\n 698.0 3077 0.0 -6.0 64 3.52 280 31 302.7 313.7 303.4\n 687.0 3204 -0.1 -7.1 59 3.28 281 31 304.0 314.3 304.6\n 648.9 3658 -3.2 -10.9 55 2.59 285 30 305.5 313.8 305.9\n 631.0 3881 -4.7 -12.7 54 2.29 289 33 306.2 313.6 306.6\n 600.7 4267 -6.4 -16.7 44 1.73 295 39 308.6 314.3 308.9\n 592.0 4381 -6.9 -17.9 41 1.59 297 41 309.3 314.6 309.6\n 577.6 4572 -8.1 -19.6 39 1.41 300 44 310.1 314.9 310.3\n 555.3 4877 -10.0 -22.3 36 1.16 295 39 311.3 315.3 311.5\n 536.0 5151 -11.7 -24.7 33 0.97 304 39 312.4 315.8 312.6\n 533.8 5182 -11.9 -25.0 33 0.95 305 39 312.5 315.8 312.7\n 500.0 5680 -15.9 -29.9 29 0.64 290 44 313.6 315.9 313.7\n 472.3 6096 -19.7 -33.4 28 0.49 285 46 314.1 315.8 314.1\n 453.0 6401 -22.4 -36.0 28 0.39 300 50 314.4 315.8 314.4\n 400.0 7310 -30.7 -43.7 27 0.20 285 44 315.0 315.8 315.0\n 399.7 7315 -30.8 -43.8 27 0.20 285 44 315.0 315.8 315.0\n 387.0 7543 -33.1 -46.1 26 0.16 281 47 314.9 315.5 314.9\n 382.7 7620 -33.8 -46.8 26 0.15 280 48 315.0 315.6 315.0\n 342.0 8398 -40.5 -53.5 23 0.08 293 52 316.1 316.4 316.1\n 320.4 8839 -43.7 -56.7 22 0.06 300 54 317.6 317.8 317.6\n 318.0 8890 -44.1 -57.1 22 0.05 301 55 317.8 318.0 317.8\n 310.0 9060 -44.7 -58.7 19 0.04 304 61 319.2 319.4 319.2\n 306.1 9144 -43.9 -57.9 20 0.05 305 63 321.5 321.7 321.5\n 305.0 9169 -43.7 -57.7 20 0.05 303 63 322.1 322.4 322.1\n 300.0 9280 -43.5 -57.5 20 0.05 295 64 323.9 324.2 323.9\n 292.0 9462 -43.7 -58.7 17 0.05 293 67 326.2 326.4 326.2\n 276.0 9838 -47.1 -62.1 16 0.03 290 74 326.6 326.7 326.6\n 264.0 10132 -47.5 -62.5 16 0.03 288 79 330.1 330.3 330.1\n 251.0 10464 -49.7 -64.7 16 0.03 285 85 331.7 331.8 331.7\n 250.0 10490 -49.7 -64.7 16 0.03 285 85 332.1 332.2 332.1\n 247.0 10569 -48.7 -63.7 16 0.03 283 88 334.7 334.8 334.7\n 244.0 10649 -48.9 -63.9 16 0.03 280 91 335.6 335.7 335.6\n 243.3 10668 -48.9 -63.9 16 0.03 280 91 335.8 335.9 335.8\n 220.0 11327 -50.3 -65.3 15 0.03 280 85 343.5 343.6 343.5\n 212.0 11569 -50.5 -65.5 15 0.03 280 83 346.8 346.9 346.8\n 210.0 11631 -49.7 -64.7 16 0.03 280 83 349.0 349.1 349.0\n 200.0 11950 -49.9 -64.9 15 0.03 280 80 353.6 353.7 353.6\n 194.0 12149 -49.9 -64.9 15 0.03 279 78 356.7 356.8 356.7\n 183.0 12529 -51.3 -66.3 15 0.03 278 75 360.4 360.5 360.4\n 164.0 13233 -55.3 -68.3 18 0.02 277 69 365.2 365.3 365.2\n 152.0 13716 -56.5 -69.5 18 0.02 275 65 371.1 371.2 371.1\n 150.0 13800 -57.1 -70.1 18 0.02 275 64 371.5 371.6 371.5\n 136.0 14414 -60.5 -72.5 19 0.02 268 54 376.0 376.1 376.0\n 132.0 14600 -60.1 -72.1 19 0.02 265 51 380.0 380.1 380.0\n 131.4 14630 -60.2 -72.2 19 0.02 265 51 380.3 380.4 380.3\n 128.0 14792 -60.9 -72.9 19 0.02 266 50 381.9 382.0 381.9\n 125.0 14939 -60.1 -72.1 19 0.02 268 49 385.9 386.0 385.9\n 119.0 15240 -62.2 -73.8 20 0.01 270 48 387.4 387.5 387.4\n 112.0 15616 -64.9 -75.9 21 0.01 265 53 389.3 389.3 389.3\n 108.0 15838 -64.1 -75.1 21 0.01 265 58 394.8 394.9 394.8\n 107.8 15850 -64.1 -75.1 21 0.01 265 58 395.0 395.1 395.0\n 105.0 16010 -64.7 -75.7 21 0.01 272 50 396.9 396.9 396.9\n 103.0 16128 -62.9 -73.9 21 0.02 277 45 402.5 402.6 402.5\n 100.0 16310 -62.5 -73.5 21 0.02 285 36 406.7 406.8 406.7\n '''\n\n # Parse the data\n sound_data = StringIO(data_txt)\n p, h, T, Td = np.loadtxt(sound_data, usecols=range(0, 4), unpack=True)\n\n # Create a new figure. The dimensions here give a good aspect ratio\n fig = plt.figure(figsize=(6.5875, 6.2125))\n ax = fig.add_subplot(111, projection='skewx')\n\n plt.grid(True)\n\n # Plot the data using normal plotting functions, in this case using\n # log scaling in Y, as dictated by the typical meteorological plot\n ax.semilogy(T, p, color='C3')\n ax.semilogy(Td, p, color='C2')\n\n # An example of a slanted line at constant X\n l = ax.axvline(0, color='C0')\n\n # Disables the log-formatting that comes with semilogy\n ax.yaxis.set_major_formatter(ScalarFormatter())\n ax.yaxis.set_minor_formatter(NullFormatter())\n ax.set_yticks(np.linspace(100, 1000, 10))\n ax.set_ylim(1050, 100)\n\n ax.xaxis.set_major_locator(MultipleLocator(10))\n ax.set_xlim(-50, 50)\n\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLX8r
r
api/donut.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n=============\nMmh Donuts!!!\n=============\n\nDraw donuts (miam!) using Path and Patches.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.path as mpath\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\n\n\ndef wise(v):\n if v == 1:\n return \"CCW\"\n else:\n return \"CW\"\n\n\ndef make_circle(r):\n t = np.arange(0, np.pi * 2.0, 0.01)\n t = t.reshape((len(t), 1))\n x = r * np.cos(t)\n y = r * np.sin(t)\n return np.hstack((x, y))\n\nPath = mpath.Path\n\nfig, ax = plt.subplots()\n\ninside_vertices = make_circle(0.5)\noutside_vertices = make_circle(1.0)\ncodes = np.ones(\n len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO\ncodes[0] = mpath.Path.MOVETO\n\nfor i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):\n # Concatenate the inside and outside subpaths together, changing their\n # order as needed\n vertices = np.concatenate((outside_vertices[::outside],\n inside_vertices[::inside]))\n # Shift the path\n vertices[:, 0] += i * 2.5\n # The codes will be all \"LINETO\" commands, except for \"MOVETO\"s at the\n # beginning of each subpath\n all_codes = np.concatenate((codes, codes))\n # Create the Path object\n path = mpath.Path(vertices, all_codes)\n # Add plot it\n patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black')\n ax.add_patch(patch)\n\n ax.annotate(\"Outside %s,\\nInside %s\" % (wise(outside), wise(inside)),\n (i * 2.5, -1.5), va=\"top\", ha=\"center\")\n\nax.set_xlim(-2, 10)\nax.set_ylim(-3, 2)\nax.set_title('Mmm, donuts!')\nax.set_aspect(1.0)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLTW api/watermark_text.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Text watermark\n\n\nUse a Text as a watermark\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n#import matplotlib\n#matplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nfig, ax = plt.subplots()\nax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')\nax.grid()\n\n# position bottom right\nfig.text(0.95, 0.05, 'Property of MPL',\n fontsize=50, color='gray',\n ha='right', va='bottom', alpha=0.5)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLN api/span_regions.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Using span_where\n\n\nIllustrate some helper functions for shading regions where a logical\nmask is True\n\nSee :meth:`matplotlib.collections.BrokenBarHCollection.span_where`\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.collections as collections\n\n\nt = np.arange(0.0, 2, 0.01)\ns1 = np.sin(2*np.pi*t)\ns2 = 1.2*np.sin(4*np.pi*t)\n\n\nfig, ax = plt.subplots()\nax.set_title('using span_where')\nax.plot(t, s1, color='black')\nax.axhline(0, color='black', lw=2)\n\ncollection = collections.BrokenBarHCollection.span_where(\n t, ymin=0, ymax=1, where=s1 > 0, facecolor='green', alpha=0.5)\nax.add_collection(collection)\n\ncollection = collections.BrokenBarHCollection.span_where(\n t, ymin=-1, ymax=0, where=s1 < 0, facecolor='red', alpha=0.5)\nax.add_collection(collection)\n\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLy api/patch_collection.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n============================\nCircles, Wedges and Polygons\n============================\n\nThis example demonstrates how to use patch collections.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib\nfrom matplotlib.patches import Circle, Wedge, Polygon\nfrom matplotlib.collections import PatchCollection\nimport matplotlib.pyplot as plt\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nfig, ax = plt.subplots()\n\nresolution = 50 # the number of vertices\nN = 3\nx = np.random.rand(N)\ny = np.random.rand(N)\nradii = 0.1*np.random.rand(N)\npatches = []\nfor x1, y1, r in zip(x, y, radii):\n circle = Circle((x1, y1), r)\n patches.append(circle)\n\nx = np.random.rand(N)\ny = np.random.rand(N)\nradii = 0.1*np.random.rand(N)\ntheta1 = 360.0*np.random.rand(N)\ntheta2 = 360.0*np.random.rand(N)\nfor x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2):\n wedge = Wedge((x1, y1), r, t1, t2)\n patches.append(wedge)\n\n# Some limiting conditions on Wedge\npatches += [\n Wedge((.3, .7), .1, 0, 360), # Full circle\n Wedge((.7, .8), .2, 0, 360, width=0.05), # Full ring\n Wedge((.8, .3), .2, 0, 45), # Full sector\n Wedge((.8, .3), .2, 45, 90, width=0.10), # Ring sector\n]\n\nfor i in range(N):\n polygon = Polygon(np.random.rand(N, 2), True)\n patches.append(polygon)\n\ncolors = 100*np.random.rand(len(patches))\np = PatchCollection(patches, alpha=0.4)\np.set_array(np.array(colors))\nax.add_collection(p)\nfig.colorbar(p, ax=ax)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL;7 7 api/scatter_piecharts.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Scatter plot with pie chart markers\n\n\nThis example makes custom 'pie charts' as the markers for a scatter plot.\n\nThanks to Manuel Metz for the example\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\n\n# first define the ratios\nr1 = 0.2 # 20%\nr2 = r1 + 0.4 # 40%\n\n# define some sizes of the scatter marker\nsizes = np.array([60, 80, 120])\n\n# calculate the points of the first pie marker\n#\n# these are just the origin (0,0) +\n# some points on a circle cos,sin\nx = [0] + np.cos(np.linspace(0, 2 * np.pi * r1, 10)).tolist()\ny = [0] + np.sin(np.linspace(0, 2 * np.pi * r1, 10)).tolist()\nxy1 = list(zip(x, y))\ns1 = np.max(xy1)\n\nx = [0] + np.cos(np.linspace(2 * np.pi * r1, 2 * np.pi * r2, 10)).tolist()\ny = [0] + np.sin(np.linspace(2 * np.pi * r1, 2 * np.pi * r2, 10)).tolist()\nxy2 = list(zip(x, y))\ns2 = np.max(xy2)\n\nx = [0] + np.cos(np.linspace(2 * np.pi * r2, 2 * np.pi, 10)).tolist()\ny = [0] + np.sin(np.linspace(2 * np.pi * r2, 2 * np.pi, 10)).tolist()\nxy3 = list(zip(x, y))\ns3 = np.max(xy3)\n\nfig, ax = plt.subplots()\nax.scatter(range(3), range(3), marker=(xy1, 0),\n s=s1 ** 2 * sizes, facecolor='blue')\nax.scatter(range(3), range(3), marker=(xy2, 0),\n s=s2 ** 2 * sizes, facecolor='green')\nax.scatter(range(3), range(3), marker=(xy3, 0),\n s=s3 ** 2 * sizes, facecolor='red')\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL¦CA api/collections.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n=========================================================\nLine, Poly and RegularPoly Collection with autoscaling\n=========================================================\n\nFor the first two subplots, we will use spirals. Their\nsize will be set in plot units, not data units. Their positions\nwill be set in data units by using the \"offsets\" and \"transOffset\"\nkwargs of the LineCollection and PolyCollection.\n\nThe third subplot will make regular polygons, with the same\ntype of scaling and positioning as in the first two.\n\nThe last subplot illustrates the use of \"offsets=(xo,yo)\",\nthat is, a single tuple instead of a list of tuples, to generate\nsuccessively offset curves, with the offset given in data\nunits. This behavior is available only for the LineCollection.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nfrom matplotlib import collections, colors, transforms\nimport numpy as np\n\nnverts = 50\nnpts = 100\n\n# Make some spirals\nr = np.arange(nverts)\ntheta = np.linspace(0, 2*np.pi, nverts)\nxx = r * np.sin(theta)\nyy = r * np.cos(theta)\nspiral = list(zip(xx, yy))\n\n# Make some offsets\n# Fixing random state for reproducibility\nrs = np.random.RandomState(19680801)\n\n\nxo = rs.randn(npts)\nyo = rs.randn(npts)\nxyo = list(zip(xo, yo))\n\n# Make a list of colors cycling through the default series.\ncolors = [colors.to_rgba(c)\n for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]\n\nfig, axes = plt.subplots(2, 2)\nfig.subplots_adjust(top=0.92, left=0.07, right=0.97,\n hspace=0.3, wspace=0.3)\n((ax1, ax2), (ax3, ax4)) = axes # unpack the axes\n\n\ncol = collections.LineCollection([spiral], offsets=xyo,\n transOffset=ax1.transData)\ntrans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0)\ncol.set_transform(trans) # the points to pixels transform\n# Note: the first argument to the collection initializer\n# must be a list of sequences of x,y tuples; we have only\n# one sequence, but we still have to put it in a list.\nax1.add_collection(col, autolim=True)\n# autolim=True enables autoscaling. For collections with\n# offsets like this, it is neither efficient nor accurate,\n# but it is good enough to generate a plot that you can use\n# as a starting point. If you know beforehand the range of\n# x and y that you want to show, it is better to set them\n# explicitly, leave out the autolim kwarg (or set it to False),\n# and omit the 'ax1.autoscale_view()' call below.\n\n# Make a transform for the line segments such that their size is\n# given in points:\ncol.set_color(colors)\n\nax1.autoscale_view() # See comment above, after ax1.add_collection.\nax1.set_title('LineCollection using offsets')\n\n\n# The same data as above, but fill the curves.\ncol = collections.PolyCollection([spiral], offsets=xyo,\n transOffset=ax2.transData)\ntrans = transforms.Affine2D().scale(fig.dpi/72.0)\ncol.set_transform(trans) # the points to pixels transform\nax2.add_collection(col, autolim=True)\ncol.set_color(colors)\n\n\nax2.autoscale_view()\nax2.set_title('PolyCollection using offsets')\n\n# 7-sided regular polygons\n\ncol = collections.RegularPolyCollection(\n 7, sizes=np.abs(xx) * 10.0, offsets=xyo, transOffset=ax3.transData)\ntrans = transforms.Affine2D().scale(fig.dpi / 72.0)\ncol.set_transform(trans) # the points to pixels transform\nax3.add_collection(col, autolim=True)\ncol.set_color(colors)\nax3.autoscale_view()\nax3.set_title('RegularPolyCollection using offsets')\n\n\n# Simulate a series of ocean current profiles, successively\n# offset by 0.1 m/s so that they form what is sometimes called\n# a \"waterfall\" plot or a \"stagger\" plot.\n\nnverts = 60\nncurves = 20\noffs = (0.1, 0.0)\n\nyy = np.linspace(0, 2*np.pi, nverts)\nym = np.max(yy)\nxx = (0.2 + (ym - yy)/ym)**2 * np.cos(yy - 0.4)*0.5\nsegs = []\nfor i in range(ncurves):\n xxx = xx + 0.02*rs.randn(nverts)\n curve = list(zip(xxx, yy*100))\n segs.append(curve)\n\ncol = collections.LineCollection(segs, offsets=offs)\nax4.add_collection(col, autolim=True)\ncol.set_color(colors)\nax4.autoscale_view()\nax4.set_title('Successive data offsets')\nax4.set_xlabel('Zonal velocity component (m/s)')\nax4.set_ylabel('Depth (m)')\n# Reverse the y-axis so depth increases downward\nax4.set_ylim(ax4.get_ylim()[::-1])\n\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLy api/quad_bezier.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Bezier Curve\n\n\nThis example showcases the PathPatch object to create a Bezier polycurve path\npatch.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.path as mpath\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\n\nPath = mpath.Path\n\nfig, ax = plt.subplots()\npp1 = mpatches.PathPatch(\n Path([(0, 0), (1, 0), (1, 1), (0, 0)],\n [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]),\n fc=\"none\", transform=ax.transData)\n\nax.add_patch(pp1)\nax.plot([0.75], [0.25], \"ro\")\nax.set_title('The red point should be on the path')\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL api/font_family_rc_sgskip.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Configuring the font family\n\n\nYou can explicitly set which font family is picked up for a given font\nstyle (e.g., 'serif', 'sans-serif', or 'monospace').\n\nIn the example below, we only allow one font family (Tahoma) for the\nsans-serif font style. You the default family with the font.family rc\nparam, e.g.,::\n\n rcParams['font.family'] = 'sans-serif'\n\nand for the font.family you set a list of font styles to try to find\nin order::\n\n rcParams['font.sans-serif'] = ['Tahoma', 'DejaVu Sans',\n 'Lucida Grande', 'Verdana']\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from matplotlib import rcParams\nrcParams['font.family'] = 'sans-serif'\nrcParams['font.sans-serif'] = ['Tahoma']\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.plot([1, 2, 3], label='test')\n\nax.legend()\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL@9 9 api/sankey_rankine.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Rankine power cycle\n\n\nDemonstrate the Sankey class with a practical example of a Rankine power\ncycle.\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n\nfrom matplotlib.sankey import Sankey\n\nfig = plt.figure(figsize=(8, 9))\nax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],\n title=\"Rankine Power Cycle: Example 8.6 from Moran and \"\n \"Shapiro\\n\\x22Fundamentals of Engineering Thermodynamics \"\n \"\\x22, 6th ed., 2008\")\nHdot = [260.431, 35.078, 180.794, 221.115, 22.700,\n 142.361, 10.193, 10.210, 43.670, 44.312,\n 68.631, 10.758, 10.758, 0.017, 0.642,\n 232.121, 44.559, 100.613, 132.168] # MW\nsankey = Sankey(ax=ax, format='%.3G', unit=' MW', gap=0.5, scale=1.0/Hdot[0])\nsankey.add(patchlabel='\\n\\nPump 1', rotation=90, facecolor='#37c959',\n flows=[Hdot[13], Hdot[6], -Hdot[7]],\n labels=['Shaft power', '', None],\n pathlengths=[0.4, 0.883, 0.25],\n orientations=[1, -1, 0])\nsankey.add(patchlabel='\\n\\nOpen\\nheater', facecolor='#37c959',\n flows=[Hdot[11], Hdot[7], Hdot[4], -Hdot[8]],\n labels=[None, '', None, None],\n pathlengths=[0.25, 0.25, 1.93, 0.25],\n orientations=[1, 0, -1, 0], prior=0, connect=(2, 1))\nsankey.add(patchlabel='\\n\\nPump 2', facecolor='#37c959',\n flows=[Hdot[14], Hdot[8], -Hdot[9]],\n labels=['Shaft power', '', None],\n pathlengths=[0.4, 0.25, 0.25],\n orientations=[1, 0, 0], prior=1, connect=(3, 1))\nsankey.add(patchlabel='Closed\\nheater', trunklength=2.914, fc='#37c959',\n flows=[Hdot[9], Hdot[1], -Hdot[11], -Hdot[10]],\n pathlengths=[0.25, 1.543, 0.25, 0.25],\n labels=['', '', None, None],\n orientations=[0, -1, 1, -1], prior=2, connect=(2, 0))\nsankey.add(patchlabel='Trap', facecolor='#37c959', trunklength=5.102,\n flows=[Hdot[11], -Hdot[12]],\n labels=['\\n', None],\n pathlengths=[1.0, 1.01],\n orientations=[1, 1], prior=3, connect=(2, 0))\nsankey.add(patchlabel='Steam\\ngenerator', facecolor='#ff5555',\n flows=[Hdot[15], Hdot[10], Hdot[2], -Hdot[3], -Hdot[0]],\n labels=['Heat rate', '', '', None, None],\n pathlengths=0.25,\n orientations=[1, 0, -1, -1, -1], prior=3, connect=(3, 1))\nsankey.add(patchlabel='\\n\\n\\nTurbine 1', facecolor='#37c959',\n flows=[Hdot[0], -Hdot[16], -Hdot[1], -Hdot[2]],\n labels=['', None, None, None],\n pathlengths=[0.25, 0.153, 1.543, 0.25],\n orientations=[0, 1, -1, -1], prior=5, connect=(4, 0))\nsankey.add(patchlabel='\\n\\n\\nReheat', facecolor='#37c959',\n flows=[Hdot[2], -Hdot[2]],\n labels=[None, None],\n pathlengths=[0.725, 0.25],\n orientations=[-1, 0], prior=6, connect=(3, 0))\nsankey.add(patchlabel='Turbine 2', trunklength=3.212, facecolor='#37c959',\n flows=[Hdot[3], Hdot[16], -Hdot[5], -Hdot[4], -Hdot[17]],\n labels=[None, 'Shaft power', None, '', 'Shaft power'],\n pathlengths=[0.751, 0.15, 0.25, 1.93, 0.25],\n orientations=[0, -1, 0, -1, 1], prior=6, connect=(1, 1))\nsankey.add(patchlabel='Condenser', facecolor='#58b1fa', trunklength=1.764,\n flows=[Hdot[5], -Hdot[18], -Hdot[6]],\n labels=['', 'Heat rate', None],\n pathlengths=[0.45, 0.25, 0.883],\n orientations=[-1, 1, 0], prior=8, connect=(2, 0))\ndiagrams = sankey.finish()\nfor diagram in diagrams:\n diagram.text.set_fontweight('bold')\n diagram.text.set_fontsize('10')\n for text in diagram.texts:\n text.set_fontsize('10')\n# Notice that the explicit connections are handled automatically, but the\n# implicit ones currently are not. The lengths of the paths and the trunks\n# must be adjusted manually, and that is a bit tricky.\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLٹ9
api/two_scales.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Plots with different scales\n\n\nDemonstrate how to do two plots on the same axes with different left and\nright scales.\n\nThe trick is to use *two different axes* that share the same *x* axis.\nYou can use separate `matplotlib.ticker` formatters and locators as\ndesired since the two axes are independent.\n\nSuch axes are generated by calling the `Axes.twinx` method. Likewise,\n`Axes.twiny` is available to generate axes that share a *y* axis but\nhave different top and bottom scales.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef two_scales(ax1, time, data1, data2, c1, c2):\n \"\"\"\n\n Parameters\n ----------\n ax : axis\n Axis to put two scales on\n\n time : array-like\n x-axis values for both datasets\n\n data1: array-like\n Data for left hand scale\n\n data2 : array-like\n Data for right hand scale\n\n c1 : color\n Color for line 1\n\n c2 : color\n Color for line 2\n\n Returns\n -------\n ax : axis\n Original axis\n ax2 : axis\n New twin axis\n \"\"\"\n ax2 = ax1.twinx()\n\n ax1.plot(time, data1, color=c1)\n ax1.set_xlabel('time (s)')\n ax1.set_ylabel('exp')\n\n ax2.plot(time, data2, color=c2)\n ax2.set_ylabel('sin')\n return ax1, ax2\n\n\n# Create some mock data\nt = np.arange(0.01, 10.0, 0.01)\ns1 = np.exp(t)\ns2 = np.sin(2 * np.pi * t)\n\n# Create axes\nfig, ax = plt.subplots()\nax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')\n\n\n# Change color of each axis\ndef color_y_axis(ax, color):\n \"\"\"Color your axes.\"\"\"\n for t in ax.get_yticklabels():\n t.set_color(color)\n return None\ncolor_y_axis(ax1, 'r')\ncolor_y_axis(ax2, 'b')\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL api/agg_oo_sgskip.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# The object-oriented interface\n\n\nA pure OO (look Ma, no pyplot!) example using the agg backend.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nfig = Figure()\n# A canvas must be manually attached to the figure (pyplot would automatically\n# do it). This is done by instantiating the canvas with the figure as\n# argument.\nFigureCanvas(fig)\nax = fig.add_subplot(111)\nax.plot([1, 2, 3])\nax.set_title('hi mom')\nax.grid(True)\nax.set_xlabel('time')\nax.set_ylabel('volts')\nfig.savefig('test')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL8B B api/compound_path.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Compound path\n\n\nMake a compound path -- in this case two simple polygons, a rectangle\nand a triangle. Use CLOSEPOLY and MOVETO for the different parts of\nthe compound path\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nfrom matplotlib.path import Path\nfrom matplotlib.patches import PathPatch\nimport matplotlib.pyplot as plt\n\n\nvertices = []\ncodes = []\n\ncodes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY]\nvertices = [(1, 1), (1, 2), (2, 2), (2, 1), (0, 0)]\n\ncodes += [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]\nvertices += [(4, 4), (5, 5), (5, 4), (0, 0)]\n\nvertices = np.array(vertices, float)\npath = Path(vertices, codes)\n\npathpatch = PathPatch(path, facecolor='None', edgecolor='green')\n\nfig, ax = plt.subplots()\nax.add_patch(pathpatch)\nax.set_title('A compound path')\n\nax.dataLim.update_from_data_xy(vertices)\nax.autoscale_view()\n\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL< api/joinstyle.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Join styles\n\n\nIllustrate the three different join styles.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef plot_angle(ax, x, y, angle, style):\n phi = np.radians(angle)\n xx = [x + .5, x, x + .5*np.cos(phi)]\n yy = [y, y, y + .5*np.sin(phi)]\n ax.plot(xx, yy, lw=8, color='blue', solid_joinstyle=style)\n ax.plot(xx[1:], yy[1:], lw=1, color='black')\n ax.plot(xx[1::-1], yy[1::-1], lw=1, color='black')\n ax.plot(xx[1:2], yy[1:2], 'o', color='red', markersize=3)\n ax.text(x, y + .2, '%.0f degrees' % angle)\n\nfig, ax = plt.subplots()\nax.set_title('Join style')\n\nfor x, style in enumerate((('miter', 'round', 'bevel'))):\n ax.text(x, 5, style)\n for i in range(5):\n plot_angle(ax, x, i, pow(2.0, 3 + i), style)\n\nax.set_xlim(-.5, 2.75)\nax.set_ylim(-.5, 5.5)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL-rK K api/watermark_image.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Watermark image\n\n\nUse a PNG file as a watermark\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import print_function\nimport numpy as np\nimport matplotlib.cbook as cbook\nimport matplotlib.image as image\nimport matplotlib.pyplot as plt\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\ndatafile = cbook.get_sample_data('logo2.png', asfileobj=False)\nprint('loading %s' % datafile)\nim = image.imread(datafile)\nim[:, :, -1] = 0.5 # set the alpha channel\n\nfig, ax = plt.subplots()\n\nax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')\nax.grid()\nfig.figimage(im, 10, 10, zorder=3)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL5 api/font_file.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Using a ttf font file in Matplotlib\n\n\nAlthough it is usually not a good idea to explicitly point to a single ttf file\nfor a font instance, you can do so using the `font_manager.FontProperties`\n*fname* argument.\n\nHere, we use the Computer Modern roman font (``cmr10``) shipped with\nMatplotlib.\n\nFor a more flexible solution, see :doc:`/gallery/api/font_family_rc_sgskip` and\n:doc:`/gallery/text_labels_and_annotations/fonts_demo`.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import os\nfrom matplotlib import font_manager as fm, pyplot as plt, rcParams\n\nfig, ax = plt.subplots()\n\nfpath = os.path.join(rcParams[\"datapath\"], \"fonts/ttf/cmr10.ttf\")\nprop = fm.FontProperties(fname=fpath)\nfname = os.path.split(fpath)[1]\nax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)\nax.set_xlabel('This is the default font')\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL>E< < api/engineering_formatter.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Labeling ticks using engineering notation\n\n\nUse of the engineering Formatter.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.ticker import EngFormatter\n\n# Fixing random state for reproducibility\nprng = np.random.RandomState(19680801)\n\n# Create artificial data to plot.\n# The x data span over several decades to demonstrate several SI prefixes.\nxs = np.logspace(1, 9, 100)\nys = (0.8 + 0.4 * prng.uniform(size=100)) * np.log10(xs)**2\n\n# Figure width is doubled (2*6.4) to display nicely 2 subplots side by side.\nfig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(7, 9.6))\nfor ax in (ax0, ax1):\n ax.set_xscale('log')\n\n# Demo of the default settings, with a user-defined unit label.\nax0.set_title('Full unit ticklabels, w/ default precision & space separator')\nformatter0 = EngFormatter(unit='Hz')\nax0.xaxis.set_major_formatter(formatter0)\nax0.plot(xs, ys)\nax0.set_xlabel('Frequency')\n\n# Demo of the options `places` (number of digit after decimal point) and\n# `sep` (separator between the number and the prefix/unit).\nax1.set_title('SI-prefix only ticklabels, 1-digit precision & '\n 'thin space separator')\nformatter1 = EngFormatter(places=1, sep=u\"\\N{THIN SPACE}\") # U+2009\nax1.xaxis.set_major_formatter(formatter1)\nax1.plot(xs, ys)\nax1.set_xlabel('Frequency [Hz]')\n\nplt.tight_layout()\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL'-8 8 api/legend.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Legend using pre-defined labels\n\n\nDefining legend labels with plots.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Make some fake data.\na = b = np.arange(0, 3, .02)\nc = np.exp(a)\nd = c[::-1]\n\n# Create plots with pre-defined labels.\nfig, ax = plt.subplots()\nax.plot(a, c, 'k--', label='Model length')\nax.plot(a, d, 'k:', label='Data length')\nax.plot(a, c + d, 'k', label='Total message length')\n\nlegend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')\n\n# Put a nicer background color on the legend.\nlegend.get_frame().set_facecolor('#00FFCC')\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL *` api/custom_scale_example.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Custom scale\n\n\nCreate a custom scale, by implementing the\nscaling use for latitude data in a Mercator Projection.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import unicode_literals\n\nimport numpy as np\nfrom numpy import ma\nfrom matplotlib import scale as mscale\nfrom matplotlib import transforms as mtransforms\nfrom matplotlib.ticker import Formatter, FixedLocator\nfrom matplotlib import rcParams\n\n\n# BUG: this example fails with any other setting of axisbelow\nrcParams['axes.axisbelow'] = False\n\n\nclass MercatorLatitudeScale(mscale.ScaleBase):\n \"\"\"\n Scales data in range -pi/2 to pi/2 (-90 to 90 degrees) using\n the system used to scale latitudes in a Mercator projection.\n\n The scale function:\n ln(tan(y) + sec(y))\n\n The inverse scale function:\n atan(sinh(y))\n\n Since the Mercator scale tends to infinity at +/- 90 degrees,\n there is user-defined threshold, above and below which nothing\n will be plotted. This defaults to +/- 85 degrees.\n\n source:\n http://en.wikipedia.org/wiki/Mercator_projection\n \"\"\"\n\n # The scale class must have a member ``name`` that defines the\n # string used to select the scale. For example,\n # ``gca().set_yscale(\"mercator\")`` would be used to select this\n # scale.\n name = 'mercator'\n\n def __init__(self, axis, **kwargs):\n \"\"\"\n Any keyword arguments passed to ``set_xscale`` and\n ``set_yscale`` will be passed along to the scale's\n constructor.\n\n thresh: The degree above which to crop the data.\n \"\"\"\n mscale.ScaleBase.__init__(self)\n thresh = kwargs.pop(\"thresh\", np.radians(85))\n if thresh >= np.pi / 2.0:\n raise ValueError(\"thresh must be less than pi/2\")\n self.thresh = thresh\n\n def get_transform(self):\n \"\"\"\n Override this method to return a new instance that does the\n actual transformation of the data.\n\n The MercatorLatitudeTransform class is defined below as a\n nested class of this one.\n \"\"\"\n return self.MercatorLatitudeTransform(self.thresh)\n\n def set_default_locators_and_formatters(self, axis):\n \"\"\"\n Override to set up the locators and formatters to use with the\n scale. This is only required if the scale requires custom\n locators and formatters. Writing custom locators and\n formatters is rather outside the scope of this example, but\n there are many helpful examples in ``ticker.py``.\n\n In our case, the Mercator example uses a fixed locator from\n -90 to 90 degrees and a custom formatter class to put convert\n the radians to degrees and put a degree symbol after the\n value::\n \"\"\"\n class DegreeFormatter(Formatter):\n def __call__(self, x, pos=None):\n return \"%d\\N{DEGREE SIGN}\" % np.degrees(x)\n\n axis.set_major_locator(FixedLocator(\n np.radians(np.arange(-90, 90, 10))))\n axis.set_major_formatter(DegreeFormatter())\n axis.set_minor_formatter(DegreeFormatter())\n\n def limit_range_for_scale(self, vmin, vmax, minpos):\n \"\"\"\n Override to limit the bounds of the axis to the domain of the\n transform. In the case of Mercator, the bounds should be\n limited to the threshold that was passed in. Unlike the\n autoscaling provided by the tick locators, this range limiting\n will always be adhered to, whether the axis range is set\n manually, determined automatically or changed through panning\n and zooming.\n \"\"\"\n return max(vmin, -self.thresh), min(vmax, self.thresh)\n\n class MercatorLatitudeTransform(mtransforms.Transform):\n # There are two value members that must be defined.\n # ``input_dims`` and ``output_dims`` specify number of input\n # dimensions and output dimensions to the transformation.\n # These are used by the transformation framework to do some\n # error checking and prevent incompatible transformations from\n # being connected together. When defining transforms for a\n # scale, which are, by definition, separable and have only one\n # dimension, these members should always be set to 1.\n input_dims = 1\n output_dims = 1\n is_separable = True\n has_inverse = True\n\n def __init__(self, thresh):\n mtransforms.Transform.__init__(self)\n self.thresh = thresh\n\n def transform_non_affine(self, a):\n \"\"\"\n This transform takes an Nx1 ``numpy`` array and returns a\n transformed copy. Since the range of the Mercator scale\n is limited by the user-specified threshold, the input\n array must be masked to contain only valid values.\n ``matplotlib`` will handle masked arrays and remove the\n out-of-range data from the plot. Importantly, the\n ``transform`` method *must* return an array that is the\n same shape as the input array, since these values need to\n remain synchronized with values in the other dimension.\n \"\"\"\n masked = ma.masked_where((a < -self.thresh) | (a > self.thresh), a)\n if masked.mask.any():\n return ma.log(np.abs(ma.tan(masked) + 1.0 / ma.cos(masked)))\n else:\n return np.log(np.abs(np.tan(a) + 1.0 / np.cos(a)))\n\n def inverted(self):\n \"\"\"\n Override this method so matplotlib knows how to get the\n inverse transform for this transform.\n \"\"\"\n return MercatorLatitudeScale.InvertedMercatorLatitudeTransform(\n self.thresh)\n\n class InvertedMercatorLatitudeTransform(mtransforms.Transform):\n input_dims = 1\n output_dims = 1\n is_separable = True\n has_inverse = True\n\n def __init__(self, thresh):\n mtransforms.Transform.__init__(self)\n self.thresh = thresh\n\n def transform_non_affine(self, a):\n return np.arctan(np.sinh(a))\n\n def inverted(self):\n return MercatorLatitudeScale.MercatorLatitudeTransform(self.thresh)\n\n# Now that the Scale class has been defined, it must be registered so\n# that ``matplotlib`` can find it.\nmscale.register_scale(MercatorLatitudeScale)\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n\n t = np.arange(-180.0, 180.0, 0.1)\n s = np.radians(t)/2.\n\n plt.plot(t, s, '-', lw=2)\n plt.gca().set_yscale('mercator')\n\n plt.xlabel('Longitude')\n plt.ylabel('Latitude')\n plt.title('Mercator: Projection of the Oppressor')\n plt.grid(True)\n\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLԬNp p api/unicode_minus.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Unicode minus\n\n\nYou can use the proper typesetting Unicode minus (see\nhttps://en.wikipedia.org/wiki/Plus_sign#Plus_sign) or the ASCII hyphen\nfor minus, which some people prefer. The matplotlibrc param\naxes.unicode_minus controls the default behavior.\n\nThe default is to use the Unicode minus.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nmatplotlib.rcParams['axes.unicode_minus'] = False\nfig, ax = plt.subplots()\nax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')\nax.set_title('Using hyphen instead of Unicode minus')\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL]pLh h axes_grid1/demo_axes_grid.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Demo Axes Grid\n\n\nGrid of 2x2 images with single or own colorbar.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\n\n\ndef get_demo_image():\n import numpy as np\n from matplotlib.cbook import get_sample_data\n f = get_sample_data(\"axes_grid/bivariate_normal.npy\", asfileobj=False)\n z = np.load(f)\n # z is a numpy array of 15x15\n return z, (-3, 4, -4, 3)\n\n\ndef demo_simple_grid(fig):\n \"\"\"\n A grid of 2x2 images with 0.05 inch pad between images and only\n the lower-left axes is labeled.\n \"\"\"\n grid = ImageGrid(fig, 141, # similar to subplot(141)\n nrows_ncols=(2, 2),\n axes_pad=0.05,\n label_mode=\"1\",\n )\n\n Z, extent = get_demo_image()\n for i in range(4):\n im = grid[i].imshow(Z, extent=extent, interpolation=\"nearest\")\n\n # This only affects axes in first column and second row as share_all =\n # False.\n grid.axes_llc.set_xticks([-2, 0, 2])\n grid.axes_llc.set_yticks([-2, 0, 2])\n\n\ndef demo_grid_with_single_cbar(fig):\n \"\"\"\n A grid of 2x2 images with a single colorbar\n \"\"\"\n grid = ImageGrid(fig, 142, # similar to subplot(142)\n nrows_ncols=(2, 2),\n axes_pad=0.0,\n share_all=True,\n label_mode=\"L\",\n cbar_location=\"top\",\n cbar_mode=\"single\",\n )\n\n Z, extent = get_demo_image()\n for i in range(4):\n im = grid[i].imshow(Z, extent=extent, interpolation=\"nearest\")\n grid.cbar_axes[0].colorbar(im)\n\n for cax in grid.cbar_axes:\n cax.toggle_label(False)\n\n # This affects all axes as share_all = True.\n grid.axes_llc.set_xticks([-2, 0, 2])\n grid.axes_llc.set_yticks([-2, 0, 2])\n\n\ndef demo_grid_with_each_cbar(fig):\n \"\"\"\n A grid of 2x2 images. Each image has its own colorbar.\n \"\"\"\n\n grid = ImageGrid(fig, 143, # similar to subplot(143)\n nrows_ncols=(2, 2),\n axes_pad=0.1,\n label_mode=\"1\",\n share_all=True,\n cbar_location=\"top\",\n cbar_mode=\"each\",\n cbar_size=\"7%\",\n cbar_pad=\"2%\",\n )\n Z, extent = get_demo_image()\n for i in range(4):\n im = grid[i].imshow(Z, extent=extent, interpolation=\"nearest\")\n grid.cbar_axes[i].colorbar(im)\n\n for cax in grid.cbar_axes:\n cax.toggle_label(False)\n\n # This affects all axes because we set share_all = True.\n grid.axes_llc.set_xticks([-2, 0, 2])\n grid.axes_llc.set_yticks([-2, 0, 2])\n\n\ndef demo_grid_with_each_cbar_labelled(fig):\n \"\"\"\n A grid of 2x2 images. Each image has its own colorbar.\n \"\"\"\n\n grid = ImageGrid(fig, 144, # similar to subplot(144)\n nrows_ncols=(2, 2),\n axes_pad=(0.45, 0.15),\n label_mode=\"1\",\n share_all=True,\n cbar_location=\"right\",\n cbar_mode=\"each\",\n cbar_size=\"7%\",\n cbar_pad=\"2%\",\n )\n Z, extent = get_demo_image()\n\n # Use a different colorbar range every time\n limits = ((0, 1), (-2, 2), (-1.7, 1.4), (-1.5, 1))\n for i in range(4):\n im = grid[i].imshow(Z, extent=extent, interpolation=\"nearest\",\n vmin=limits[i][0], vmax=limits[i][1])\n grid.cbar_axes[i].colorbar(im)\n\n for i, cax in enumerate(grid.cbar_axes):\n cax.set_yticks((limits[i][0], limits[i][1]))\n\n # This affects all axes because we set share_all = True.\n grid.axes_llc.set_xticks([-2, 0, 2])\n grid.axes_llc.set_yticks([-2, 0, 2])\n\n\nif 1:\n F = plt.figure(1, (10.5, 2.5))\n\n F.subplots_adjust(left=0.05, right=0.95)\n\n demo_simple_grid(F)\n demo_grid_with_single_cbar(F)\n demo_grid_with_each_cbar(F)\n demo_grid_with_each_cbar_labelled(F)\n\n plt.draw()\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLM % axes_grid1/simple_axes_divider2.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Simple Axes Divider 2\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import mpl_toolkits.axes_grid1.axes_size as Size\nfrom mpl_toolkits.axes_grid1 import Divider\nimport matplotlib.pyplot as plt\n\nfig1 = plt.figure(1, (5.5, 4.))\n\n# the rect parameter will be ignore as we will set axes_locator\nrect = (0.1, 0.1, 0.8, 0.8)\nax = [fig1.add_axes(rect, label=\"%d\" % i) for i in range(4)]\n\nhoriz = [Size.Scaled(1.5), Size.Fixed(.5), Size.Scaled(1.),\n Size.Scaled(.5)]\n\nvert = [Size.Scaled(1.), Size.Fixed(.5), Size.Scaled(1.5)]\n\n# divide the axes rectangle into grid whose size is specified by horiz * vert\ndivider = Divider(fig1, rect, horiz, vert, aspect=False)\n\nax[0].set_axes_locator(divider.new_locator(nx=0, ny=0))\nax[1].set_axes_locator(divider.new_locator(nx=0, ny=2))\nax[2].set_axes_locator(divider.new_locator(nx=2, ny=2))\nax[3].set_axes_locator(divider.new_locator(nx=2, nx1=4, ny=0))\n\nfor ax1 in ax:\n ax1.tick_params(labelbottom=False, labelleft=False)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLAOpo " axes_grid1/demo_axes_divider.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Demo Axes Divider\n\n\nAxes divider to calculate location of axes and\ncreate a divider for them using exisiting axes instances.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n\n\ndef get_demo_image():\n import numpy as np\n from matplotlib.cbook import get_sample_data\n f = get_sample_data(\"axes_grid/bivariate_normal.npy\", asfileobj=False)\n z = np.load(f)\n # z is a numpy array of 15x15\n return z, (-3, 4, -4, 3)\n\n\ndef demo_simple_image(ax):\n Z, extent = get_demo_image()\n\n im = ax.imshow(Z, extent=extent, interpolation=\"nearest\")\n cb = plt.colorbar(im)\n plt.setp(cb.ax.get_yticklabels(), visible=False)\n\n\ndef demo_locatable_axes_hard(fig1):\n\n from mpl_toolkits.axes_grid1 \\\n import SubplotDivider, LocatableAxes, Size\n\n divider = SubplotDivider(fig1, 2, 2, 2, aspect=True)\n\n # axes for image\n ax = LocatableAxes(fig1, divider.get_position())\n\n # axes for colorbar\n ax_cb = LocatableAxes(fig1, divider.get_position())\n\n h = [Size.AxesX(ax), # main axes\n Size.Fixed(0.05), # padding, 0.1 inch\n Size.Fixed(0.2), # colorbar, 0.3 inch\n ]\n\n v = [Size.AxesY(ax)]\n\n divider.set_horizontal(h)\n divider.set_vertical(v)\n\n ax.set_axes_locator(divider.new_locator(nx=0, ny=0))\n ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0))\n\n fig1.add_axes(ax)\n fig1.add_axes(ax_cb)\n\n ax_cb.axis[\"left\"].toggle(all=False)\n ax_cb.axis[\"right\"].toggle(ticks=True)\n\n Z, extent = get_demo_image()\n\n im = ax.imshow(Z, extent=extent, interpolation=\"nearest\")\n plt.colorbar(im, cax=ax_cb)\n plt.setp(ax_cb.get_yticklabels(), visible=False)\n\n\ndef demo_locatable_axes_easy(ax):\n from mpl_toolkits.axes_grid1 import make_axes_locatable\n\n divider = make_axes_locatable(ax)\n\n ax_cb = divider.new_horizontal(size=\"5%\", pad=0.05)\n fig1 = ax.get_figure()\n fig1.add_axes(ax_cb)\n\n Z, extent = get_demo_image()\n im = ax.imshow(Z, extent=extent, interpolation=\"nearest\")\n\n plt.colorbar(im, cax=ax_cb)\n ax_cb.yaxis.tick_right()\n ax_cb.yaxis.set_tick_params(labelright=False)\n\n\ndef demo_images_side_by_side(ax):\n from mpl_toolkits.axes_grid1 import make_axes_locatable\n\n divider = make_axes_locatable(ax)\n\n Z, extent = get_demo_image()\n ax2 = divider.new_horizontal(size=\"100%\", pad=0.05)\n fig1 = ax.get_figure()\n fig1.add_axes(ax2)\n\n ax.imshow(Z, extent=extent, interpolation=\"nearest\")\n ax2.imshow(Z, extent=extent, interpolation=\"nearest\")\n ax2.yaxis.set_tick_params(labelleft=False)\n\n\ndef demo():\n\n fig1 = plt.figure(1, (6, 6))\n fig1.clf()\n\n # PLOT 1\n # simple image & colorbar\n ax = fig1.add_subplot(2, 2, 1)\n demo_simple_image(ax)\n\n # PLOT 2\n # image and colorbar whose location is adjusted in the drawing time.\n # a hard way\n\n demo_locatable_axes_hard(fig1)\n\n # PLOT 3\n # image and colorbar whose location is adjusted in the drawing time.\n # a easy way\n\n ax = fig1.add_subplot(2, 2, 3)\n demo_locatable_axes_easy(ax)\n\n # PLOT 4\n # two images side by side with fixed padding.\n\n ax = fig1.add_subplot(2, 2, 4)\n demo_images_side_by_side(ax)\n\n plt.draw()\n plt.show()\n\n\ndemo()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLYT # axes_grid1/demo_edge_colorbar.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Demo Edge Colorbar\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import AxesGrid\n\n\ndef get_demo_image():\n import numpy as np\n from matplotlib.cbook import get_sample_data\n f = get_sample_data(\"axes_grid/bivariate_normal.npy\", asfileobj=False)\n z = np.load(f)\n # z is a numpy array of 15x15\n return z, (-3, 4, -4, 3)\n\n\ndef demo_bottom_cbar(fig):\n \"\"\"\n A grid of 2x2 images with a colorbar for each column.\n \"\"\"\n grid = AxesGrid(fig, 121, # similar to subplot(132)\n nrows_ncols=(2, 2),\n axes_pad=0.10,\n share_all=True,\n label_mode=\"1\",\n cbar_location=\"bottom\",\n cbar_mode=\"edge\",\n cbar_pad=0.25,\n cbar_size=\"15%\",\n direction=\"column\"\n )\n\n Z, extent = get_demo_image()\n cmaps = [plt.get_cmap(\"autumn\"), plt.get_cmap(\"summer\")]\n for i in range(4):\n im = grid[i].imshow(Z, extent=extent, interpolation=\"nearest\",\n cmap=cmaps[i//2])\n if i % 2:\n cbar = grid.cbar_axes[i//2].colorbar(im)\n\n for cax in grid.cbar_axes:\n cax.toggle_label(True)\n cax.axis[cax.orientation].set_label(\"Bar\")\n\n # This affects all axes as share_all = True.\n grid.axes_llc.set_xticks([-2, 0, 2])\n grid.axes_llc.set_yticks([-2, 0, 2])\n\n\ndef demo_right_cbar(fig):\n \"\"\"\n A grid of 2x2 images. Each row has its own colorbar.\n \"\"\"\n\n grid = AxesGrid(F, 122, # similar to subplot(122)\n nrows_ncols=(2, 2),\n axes_pad=0.10,\n label_mode=\"1\",\n share_all=True,\n cbar_location=\"right\",\n cbar_mode=\"edge\",\n cbar_size=\"7%\",\n cbar_pad=\"2%\",\n )\n Z, extent = get_demo_image()\n cmaps = [plt.get_cmap(\"spring\"), plt.get_cmap(\"winter\")]\n for i in range(4):\n im = grid[i].imshow(Z, extent=extent, interpolation=\"nearest\",\n cmap=cmaps[i//2])\n if i % 2:\n grid.cbar_axes[i//2].colorbar(im)\n\n for cax in grid.cbar_axes:\n cax.toggle_label(True)\n cax.axis[cax.orientation].set_label('Foo')\n\n # This affects all axes because we set share_all = True.\n grid.axes_llc.set_xticks([-2, 0, 2])\n grid.axes_llc.set_yticks([-2, 0, 2])\n\n\nif 1:\n F = plt.figure(1, (5.5, 2.5))\n\n F.subplots_adjust(left=0.05, right=0.93)\n\n demo_bottom_cbar(F)\n demo_right_cbar(F)\n\n plt.draw()\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL8:?i i axes_grid1/demo_axes_grid2.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Demo Axes Grid2\n\n\nGrid of images with shared xaxis and yaxis.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nimport numpy as np\n\n\ndef get_demo_image():\n from matplotlib.cbook import get_sample_data\n f = get_sample_data(\"axes_grid/bivariate_normal.npy\", asfileobj=False)\n z = np.load(f)\n # z is a numpy array of 15x15\n return z, (-3, 4, -4, 3)\n\n\ndef add_inner_title(ax, title, loc, size=None, **kwargs):\n from matplotlib.offsetbox import AnchoredText\n from matplotlib.patheffects import withStroke\n if size is None:\n size = dict(size=plt.rcParams['legend.fontsize'])\n at = AnchoredText(title, loc=loc, prop=size,\n pad=0., borderpad=0.5,\n frameon=False, **kwargs)\n ax.add_artist(at)\n at.txt._text.set_path_effects([withStroke(foreground=\"w\", linewidth=3)])\n return at\n\nif 1:\n F = plt.figure(1, (6, 6))\n F.clf()\n\n # prepare images\n Z, extent = get_demo_image()\n ZS = [Z[i::3, :] for i in range(3)]\n extent = extent[0], extent[1]/3., extent[2], extent[3]\n\n # demo 1 : colorbar at each axes\n\n grid = ImageGrid(F, 211, # similar to subplot(111)\n nrows_ncols=(1, 3),\n direction=\"row\",\n axes_pad=0.05,\n add_all=True,\n label_mode=\"1\",\n share_all=True,\n cbar_location=\"top\",\n cbar_mode=\"each\",\n cbar_size=\"7%\",\n cbar_pad=\"1%\",\n )\n\n for ax, z in zip(grid, ZS):\n im = ax.imshow(\n z, origin=\"lower\", extent=extent, interpolation=\"nearest\")\n ax.cax.colorbar(im)\n\n for ax, im_title in zip(grid, [\"Image 1\", \"Image 2\", \"Image 3\"]):\n t = add_inner_title(ax, im_title, loc=3)\n t.patch.set_alpha(0.5)\n\n for ax, z in zip(grid, ZS):\n ax.cax.toggle_label(True)\n #axis = ax.cax.axis[ax.cax.orientation]\n #axis.label.set_text(\"counts s$^{-1}$\")\n #axis.label.set_size(10)\n #axis.major_ticklabels.set_size(6)\n\n # changing the colorbar ticks\n grid[1].cax.set_xticks([-1, 0, 1])\n grid[2].cax.set_xticks([-1, 0, 1])\n\n grid[0].set_xticks([-2, 0])\n grid[0].set_yticks([-2, 0, 2])\n\n # demo 2 : shared colorbar\n\n grid2 = ImageGrid(F, 212,\n nrows_ncols=(1, 3),\n direction=\"row\",\n axes_pad=0.05,\n add_all=True,\n label_mode=\"1\",\n share_all=True,\n cbar_location=\"right\",\n cbar_mode=\"single\",\n cbar_size=\"10%\",\n cbar_pad=0.05,\n )\n\n grid2[0].set_xlabel(\"X\")\n grid2[0].set_ylabel(\"Y\")\n\n vmax, vmin = np.max(ZS), np.min(ZS)\n import matplotlib.colors\n norm = matplotlib.colors.Normalize(vmax=vmax, vmin=vmin)\n\n for ax, z in zip(grid2, ZS):\n im = ax.imshow(z, norm=norm,\n origin=\"lower\", extent=extent,\n interpolation=\"nearest\")\n\n # With cbar_mode=\"single\", cax attribute of all axes are identical.\n ax.cax.colorbar(im)\n ax.cax.toggle_label(True)\n\n for ax, im_title in zip(grid2, [\"(a)\", \"(b)\", \"(c)\"]):\n t = add_inner_title(ax, im_title, loc=2)\n t.patch.set_ec(\"none\")\n t.patch.set_alpha(0.5)\n\n grid2[0].set_xticks([-2, 0])\n grid2[0].set_yticks([-2, 0, 2])\n\n plt.draw()\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLaIe
e
' axes_grid1/demo_axes_hbox_divider.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Demo Axes Hbox Divider\n\n\nHbox Divider to arrange subplots.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.axes_divider import HBoxDivider\nimport mpl_toolkits.axes_grid1.axes_size as Size\n\n\ndef make_heights_equal(fig, rect, ax1, ax2, pad):\n # pad in inches\n\n h1, v1 = Size.AxesX(ax1), Size.AxesY(ax1)\n h2, v2 = Size.AxesX(ax2), Size.AxesY(ax2)\n\n pad_v = Size.Scaled(1)\n pad_h = Size.Fixed(pad)\n\n my_divider = HBoxDivider(fig, rect,\n horizontal=[h1, pad_h, h2],\n vertical=[v1, pad_v, v2])\n\n ax1.set_axes_locator(my_divider.new_locator(0))\n ax2.set_axes_locator(my_divider.new_locator(2))\n\n\nif __name__ == \"__main__\":\n\n arr1 = np.arange(20).reshape((4, 5))\n arr2 = np.arange(20).reshape((5, 4))\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n ax1.imshow(arr1, interpolation=\"nearest\")\n ax2.imshow(arr2, interpolation=\"nearest\")\n\n rect = 111 # subplot param for combined axes\n make_heights_equal(fig, rect, ax1, ax2, pad=0.5) # pad in inches\n\n for ax in [ax1, ax2]:\n ax.locator_params(nbins=4)\n\n # annotate\n ax3 = plt.axes([0.5, 0.5, 0.001, 0.001], frameon=False)\n ax3.xaxis.set_visible(False)\n ax3.yaxis.set_visible(False)\n ax3.annotate(\"Location of two axes are adjusted\\n\"\n \"so that they have equal heights\\n\"\n \"while maintaining their aspect ratios\", (0.5, 0.5),\n xycoords=\"axes fraction\", va=\"center\", ha=\"center\",\n bbox=dict(boxstyle=\"round, pad=1\", fc=\"w\"))\n\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLl % axes_grid1/simple_axes_divider3.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Simple Axes Divider 3\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import mpl_toolkits.axes_grid1.axes_size as Size\nfrom mpl_toolkits.axes_grid1 import Divider\nimport matplotlib.pyplot as plt\n\n\nfig1 = plt.figure(1, (5.5, 4))\n\n# the rect parameter will be ignore as we will set axes_locator\nrect = (0.1, 0.1, 0.8, 0.8)\nax = [fig1.add_axes(rect, label=\"%d\" % i) for i in range(4)]\n\n\nhoriz = [Size.AxesX(ax[0]), Size.Fixed(.5), Size.AxesX(ax[1])]\nvert = [Size.AxesY(ax[0]), Size.Fixed(.5), Size.AxesY(ax[2])]\n\n# divide the axes rectangle into grid whose size is specified by horiz * vert\ndivider = Divider(fig1, rect, horiz, vert, aspect=False)\n\n\nax[0].set_axes_locator(divider.new_locator(nx=0, ny=0))\nax[1].set_axes_locator(divider.new_locator(nx=2, ny=0))\nax[2].set_axes_locator(divider.new_locator(nx=0, ny=2))\nax[3].set_axes_locator(divider.new_locator(nx=2, ny=2))\n\nax[0].set_xlim(0, 2)\nax[1].set_xlim(0, 1)\n\nax[0].set_ylim(0, 1)\nax[2].set_ylim(0, 2)\n\ndivider.set_aspect(1.)\n\nfor ax1 in ax:\n ax1.tick_params(labelbottom=False, labelleft=False)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLZ " axes_grid1/demo_new_colorbar.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Demo New Colorbar\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.colorbar import colorbar\n\n\nplt.rcParams[\"text.usetex\"] = False\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3))\n\nim1 = ax1.imshow([[1, 2], [3, 4]])\ncb1 = fig.colorbar(im1, ax=ax1)\ncb1.ax.set_yticks([1, 3])\nax1.set_title(\"Original MPL's colorbar w/\\nset_yticks([1,3])\", size=10)\n\nim2 = ax2.imshow([[1, 2], [3, 4]])\ncb2 = colorbar(im2, ax=ax2)\ncb2.ax.set_yticks([1, 3])\nax2.set_title(\"AxesGrid's colorbar w/\\nset_yticks([1,3])\", size=10)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL岮 ! axes_grid1/parasite_simple2.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Parasite Simple2\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.transforms as mtransforms\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.parasite_axes import SubplotHost\n\nobs = [[\"01_S1\", 3.88, 0.14, 1970, 63],\n [\"01_S4\", 5.6, 0.82, 1622, 150],\n [\"02_S1\", 2.4, 0.54, 1570, 40],\n [\"03_S1\", 4.1, 0.62, 2380, 170]]\n\n\nfig = plt.figure()\n\nax_kms = SubplotHost(fig, 1, 1, 1, aspect=1.)\n\n# angular proper motion(\"/yr) to linear velocity(km/s) at distance=2.3kpc\npm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5\n\naux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.)\nax_pm = ax_kms.twin(aux_trans)\nax_pm.set_viewlim_mode(\"transform\")\n\nfig.add_subplot(ax_kms)\n\nfor n, ds, dse, w, we in obs:\n time = ((2007 + (10. + 4/30.)/12) - 1988.5)\n v = ds / time * pm_to_kms\n ve = dse / time * pm_to_kms\n ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color=\"k\")\n\n\nax_kms.axis[\"bottom\"].set_label(\"Linear velocity at 2.3 kpc [km/s]\")\nax_kms.axis[\"left\"].set_label(\"FWHM [km/s]\")\nax_pm.axis[\"top\"].set_label(r\"Proper Motion [$''$/yr]\")\nax_pm.axis[\"top\"].label.set_visible(True)\nax_pm.axis[\"right\"].major_ticklabels.set_visible(False)\n\nax_kms.set_xlim(950, 3700)\nax_kms.set_ylim(950, 3100)\n# xlim and ylim of ax_pms will be automatically adjusted.\n\nplt.draw()\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLHH 4 axes_grid1/make_room_for_ylabel_using_axesgrid.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Make Room For Ylabel Using Axesgrid\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable\n\n\nif __name__ == \"__main__\":\n\n import matplotlib.pyplot as plt\n\n def ex1():\n plt.figure(1)\n ax = plt.axes([0, 0, 1, 1])\n #ax = plt.subplot(111)\n\n ax.set_yticks([0.5])\n ax.set_yticklabels([\"very long label\"])\n\n make_axes_area_auto_adjustable(ax)\n\n def ex2():\n\n plt.figure(2)\n ax1 = plt.axes([0, 0, 1, 0.5])\n ax2 = plt.axes([0, 0.5, 1, 0.5])\n\n ax1.set_yticks([0.5])\n ax1.set_yticklabels([\"very long label\"])\n ax1.set_ylabel(\"Y label\")\n\n ax2.set_title(\"Title\")\n\n make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2])\n make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2])\n\n def ex3():\n\n fig = plt.figure(3)\n ax1 = plt.axes([0, 0, 1, 1])\n divider = make_axes_locatable(ax1)\n\n ax2 = divider.new_horizontal(\"100%\", pad=0.3, sharey=ax1)\n ax2.tick_params(labelleft=\"off\")\n fig.add_axes(ax2)\n\n divider.add_auto_adjustable_area(use_axes=[ax1], pad=0.1,\n adjust_dirs=[\"left\"])\n divider.add_auto_adjustable_area(use_axes=[ax2], pad=0.1,\n adjust_dirs=[\"right\"])\n divider.add_auto_adjustable_area(use_axes=[ax1, ax2], pad=0.1,\n adjust_dirs=[\"top\", \"bottom\"])\n\n ax1.set_yticks([0.5])\n ax1.set_yticklabels([\"very long label\"])\n\n ax2.set_title(\"Title\")\n ax2.set_xlabel(\"X - Label\")\n\n ex1()\n ex2()\n ex3()\n\n plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLp4G % axes_grid1/simple_axes_divider1.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Simple Axes Divider 1\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from mpl_toolkits.axes_grid1 import Size, Divider\nimport matplotlib.pyplot as plt\n\n\nfig1 = plt.figure(1, (6, 6))\n\n# fixed size in inch\nhoriz = [Size.Fixed(1.), Size.Fixed(.5), Size.Fixed(1.5),\n Size.Fixed(.5)]\nvert = [Size.Fixed(1.5), Size.Fixed(.5), Size.Fixed(1.)]\n\nrect = (0.1, 0.1, 0.8, 0.8)\n# divide the axes rectangle into grid whose size is specified by horiz * vert\ndivider = Divider(fig1, rect, horiz, vert, aspect=False)\n\n# the rect parameter will be ignore as we will set axes_locator\nax1 = fig1.add_axes(rect, label=\"1\")\nax2 = fig1.add_axes(rect, label=\"2\")\nax3 = fig1.add_axes(rect, label=\"3\")\nax4 = fig1.add_axes(rect, label=\"4\")\n\nax1.set_axes_locator(divider.new_locator(nx=0, ny=0))\nax2.set_axes_locator(divider.new_locator(nx=0, ny=2))\nax3.set_axes_locator(divider.new_locator(nx=2, ny=2))\nax4.set_axes_locator(divider.new_locator(nx=2, nx1=4, ny=0))\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL4, , axes_grid1/parasite_simple.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Parasite Simple\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from mpl_toolkits.axes_grid1 import host_subplot\nimport matplotlib.pyplot as plt\n\nhost = host_subplot(111)\n\npar = host.twinx()\n\nhost.set_xlabel(\"Distance\")\nhost.set_ylabel(\"Density\")\npar.set_ylabel(\"Temperature\")\n\np1, = host.plot([0, 1, 2], [0, 1, 2], label=\"Density\")\np2, = par.plot([0, 1, 2], [0, 3, 2], label=\"Temperature\")\n\nleg = plt.legend()\n\nhost.yaxis.get_label().set_color(p1.get_color())\nleg.texts[0].set_color(p1.get_color())\n\npar.yaxis.get_label().set_color(p2.get_color())\nleg.texts[1].set_color(p2.get_color())\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL@ axes_grid1/simple_rgb.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Simple RGB\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n\nfrom mpl_toolkits.axes_grid1.axes_rgb import RGBAxes\n\n\ndef get_demo_image():\n import numpy as np\n from matplotlib.cbook import get_sample_data\n f = get_sample_data(\"axes_grid/bivariate_normal.npy\", asfileobj=False)\n z = np.load(f)\n # z is a numpy array of 15x15\n return z, (-3, 4, -4, 3)\n\n\ndef get_rgb():\n Z, extent = get_demo_image()\n\n Z[Z < 0] = 0.\n Z = Z / Z.max()\n\n R = Z[:13, :13]\n G = Z[2:, 2:]\n B = Z[:13, 2:]\n\n return R, G, B\n\n\nfig = plt.figure(1)\nax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8])\n\nr, g, b = get_rgb()\nkwargs = dict(origin=\"lower\", interpolation=\"nearest\")\nax.imshow_rgb(r, g, b, **kwargs)\n\nax.RGB.set_xlim(0., 9.5)\nax.RGB.set_ylim(0.9, 10.6)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HLQ axes_grid1/simple_axesgrid.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Simple Axesgrid\n\n\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nimport numpy as np\n\nim = np.arange(100).reshape((10, 10))\n\nfig = plt.figure(1, (4., 4.))\ngrid = ImageGrid(fig, 111, # similar to subplot(111)\n nrows_ncols=(2, 2), # creates 2x2 grid of axes\n axes_pad=0.1, # pad between axes in inch.\n )\n\nfor i in range(4):\n grid[i].imshow(im) # The AxesGrid object work as a list of axes.\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK HL%ʜ &