diff --git a/doc/pyplots/tex_demo.py b/doc/pyplots/tex_demo.py index 3bdbb77a8168..a5288d749d86 100644 --- a/doc/pyplots/tex_demo.py +++ b/doc/pyplots/tex_demo.py @@ -1,5 +1,6 @@ -#!/usr/bin/env python """ +Demo of TeX rendering. + You can use TeX to render all of your matplotlib text if the rc parameter text.usetex is set. This works currently on the agg and ps backends, and requires that you have tex and the other dependencies @@ -10,26 +11,25 @@ ~/.tex.cache """ -from matplotlib import rc -from numpy import arange, cos, pi -from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, \ - grid, savefig, show +import numpy as np +import matplotlib.pyplot as plt -rc('text', usetex=True) -rc('font', family='serif') -figure(1, figsize=(6,4)) -ax = axes([0.1, 0.1, 0.8, 0.7]) -t = arange(0.0, 1.0+0.01, 0.01) -s = cos(2*2*pi*t)+2 -plot(t, s) +# Example data +t = np.arange(0.0, 1.0 + 0.01, 0.01) +s = np.cos(4 * np.pi * t) + 2 -xlabel(r'\textbf{time (s)}') -ylabel(r'\textit{voltage (mV)}',fontsize=16) -title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", - fontsize=16, color='r') -grid(True) -savefig('tex_demo') +plt.rc('text', usetex=True) +plt.rc('font', family='serif') +plt.plot(t, s) +plt.xlabel(r'\textbf{time} (s)') +plt.ylabel(r'\textit{voltage} (mV)',fontsize=16) +plt.title(r"\TeX\ is Number " + r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", + fontsize=16, color='gray') +# Make room for the ridiculously large title. +plt.subplots_adjust(top=0.8) -show() +plt.savefig('tex_demo') +plt.show() diff --git a/doc/users/screenshots.rst b/doc/users/screenshots.rst index e56f31d656ee..69adf7c861a1 100644 --- a/doc/users/screenshots.rst +++ b/doc/users/screenshots.rst @@ -4,13 +4,13 @@ Screenshots ********************** -Here you will find a host of example figures with the code that -generated them +Here you'll find a host of example plots with the code that +generated them. Simple Plot =========== -The most basic :func:`~matplotlib.pyplot.plot`, with text labels +Here's a very basic :func:`~matplotlib.pyplot.plot` with text labels: .. plot:: mpl_examples/pylab_examples/simple_plot.py @@ -19,8 +19,8 @@ The most basic :func:`~matplotlib.pyplot.plot`, with text labels Subplot demo ============ -Multiple regular axes (numrows by numcolumns) are created with the -:func:`~matplotlib.pyplot.subplot` command. +Multiple axes (i.e. subplots) are created with the +:func:`~matplotlib.pyplot.subplot` command: .. plot:: mpl_examples/subplots_axes_and_figures/subplot_demo.py @@ -30,7 +30,7 @@ Histograms ========== The :func:`~matplotlib.pyplot.hist` command automatically generates -histograms and will return the bin counts or probabilities +histograms and returns the bin counts or probabilities: .. plot:: mpl_examples/statistics/histogram_demo_features.py @@ -40,8 +40,8 @@ histograms and will return the bin counts or probabilities Path demo ========= -You can add arbitrary paths in matplotlib as of release 0.98. See -the :mod:`matplotlib.path`. +You can add arbitrary paths in matplotlib using the +:mod:`matplotlib.path` module: .. plot:: mpl_examples/shapes_and_collections/path_patch_demo.py @@ -52,27 +52,41 @@ mplot3d The mplot3d toolkit (see :ref:`toolkit_mplot3d-tutorial` and :ref:`mplot3d-examples-index`) has support for simple 3d graphs -including surface, wireframe, scatter, and bar charts (added in -matlpotlib-0.99). Thanks to John Porter, Jonathon Taylor and Reinier -Heeres for the mplot3d toolkit. The toolkit is included with all -standard matplotlib installs. +including surface, wireframe, scatter, and bar charts. .. plot:: mpl_examples/mplot3d/surface3d_demo.py +Thanks to John Porter, Jonathon Taylor, Reinier Heeres, and Ben Root for +the `mplot3d` toolkit. This toolkit is included with all standard matplotlib +installs. + .. _screenshots_ellipse_demo: +Streamplot +========== + +The :meth:`~matplotlib.pyplot.streamplot` function plots the streamlines of +a vector field. In addition to simply plotting the streamlines, it allows you +to map the colors and/or line widths of streamlines to a separate parameter, +such as the speed or local intensity of the vector field. + +.. plot:: mpl_examples/images_contours_and_fields/streamplot_demo_features.py + +This feature complements the :meth:`~matplotlib.pyplot.quiver` function for +plotting vector fields. Thanks to Tom Flannaghan and Tony Yu for adding the +streamplot function. + + Ellipses ======== In support of the `Phoenix `_ mission to -Mars, which used matplotlib in ground tracking of the spacecraft, -Michael Droettboom built on work by Charlie Moad to provide an -extremely accurate 8-spline approximation to elliptical arcs (see -:class:`~matplotlib.patches.Arc`) in the viewport. This -provides a scale free, accurate graph of the arc regardless of zoom -level +Mars (which used matplotlib to display ground tracking of spacecraft), +Michael Droettboom built on work by Charlie Moad to provide an extremely +accurate 8-spline approximation to elliptical arcs (see +:class:`~matplotlib.patches.Arc`), which are insensitive to zoom level. .. plot:: mpl_examples/pylab_examples/ellipse_demo.py @@ -81,27 +95,29 @@ level Bar charts ========== -The :func:`~matplotlib.pyplot.bar` -command takes error bars as an optional argument. You can also use up -and down bars, stacked bars, candlestick bars, etc, ... See -`bar_stacked.py `_ for another example. -You can make horizontal bar charts with the -:func:`~matplotlib.pyplot.barh` command. +Bar charts are simple to create using the :func:`~matplotlib.pyplot.bar` +command, which includes customizations such as error bars: .. plot:: mpl_examples/pylab_examples/barchart_demo.py +It's also simple to create stacked bars +(`bar_stacked.py `_), +candlestick bars +(`bar_stacked.py `_), +and horizontal bar charts +(`barh_demo.py `_). + .. _screenshots_pie_demo: Pie charts ========== -The :func:`~matplotlib.pyplot.pie` command -uses a MATLAB compatible syntax to produce pie charts. Optional -features include auto-labeling the percentage of area, exploding one -or more wedges out from the center of the pie, and a shadow effect. -Take a close look at the attached code that produced this figure; nine -lines of code. +The :func:`~matplotlib.pyplot.pie` command allows you to easily create pie +charts. Optional features include auto-labeling the percentage of area, +exploding one or more wedges from the center of the pie, and a shadow effect. +Take a close look at the attached code, which generates this figure in just +a few lines of code. .. plot:: mpl_examples/pie_and_polar_charts/pie_demo_features.py @@ -110,23 +126,23 @@ lines of code. Table demo ========== -The :func:`~matplotlib.pyplot.table` command will place a text table -on the axes +The :func:`~matplotlib.pyplot.table` command adds a text table +to an axes. .. plot:: mpl_examples/pylab_examples/table_demo.py .. _screenshots_scatter_demo: + Scatter demo ============ The :func:`~matplotlib.pyplot.scatter` command makes a scatter plot -with (optional) size and color arguments. This example plots changes -in Google stock price from one day to the next with the sizes coding -trading volume and the colors coding price change in day i. Here the -alpha attribute is used to make semitransparent circle markers with -the Agg backend (see :ref:`what-is-a-backend`) +with (optional) size and color arguments. This example plots changes +in Google's stock price, with marker sizes reflecting the +trading volume and colors varying with time. Here, the +alpha attribute is used to make semitransparent circle markers. .. plot:: mpl_examples/pylab_examples/scatter_demo2.py @@ -138,8 +154,8 @@ Slider demo Matplotlib has basic GUI widgets that are independent of the graphical user interface you are using, allowing you to write cross GUI figures -and widgets. See matplotlib.widgets and the widget `examples -` +and widgets. See :mod:`matplotlib.widgets` and the +`widget examples <../examples/widgets/index.html>`_. .. plot:: mpl_examples/widgets/slider_demo.py @@ -150,34 +166,33 @@ Fill demo ========= The :func:`~matplotlib.pyplot.fill` command lets you -plot filled polygons. Thanks to Andrew Straw for providing this -function +plot filled curves and polygons: .. plot:: mpl_examples/lines_bars_and_markers/fill_demo.py +Thanks to Andrew Straw for adding this function. .. _screenshots_date_demo: Date demo ========= -You can plot date data with major and minor ticks and custom tick -formatters for both the major and minor ticks; see matplotlib.ticker -and matplotlib.dates for details and usage. +You can plot date data with major and minor ticks and custom tick formatters +for both. .. plot:: mpl_examples/api/date_demo.py +See :mod:`matplotlib.ticker` and :mod:`matplotlib.dates` for details and usage. + .. _screenshots_jdh_demo: Financial charts ================ -You can make much more sophisticated financial plots. This example -emulates one of the `ChartDirector -`_ financial plots. -Some of the data in the plot, are real financial data, some are random -traces that I used since the goal was to illustrate plotting -techniques, not market analysis! +You can make sophisticated financial plots by combining the various +plot functions, layout commands, and labeling tools provided by matplotlib. +The following example emulates one of the financial plots in +`ChartDirector `_: .. plot:: mpl_examples/pylab_examples/finance_work2.py @@ -188,9 +203,7 @@ techniques, not market analysis! Basemap demo ============ -Jeff Whitaker's :ref:`toolkit_basemap` add-on toolkit makes it possible to plot data on many -different map projections. This example shows how to plot contours, markers and text -on an orthographic projection, with NASA's "blue marble" satellite image as a background. +Jeff Whitaker's :ref:`toolkit_basemap` add-on toolkit makes it possible to plot data on many different map projections. This example shows how to plot contours, markers and text on an orthographic projection, with NASA's "blue marble" satellite image as a background. .. plot:: pyplots/plotmap.py @@ -201,16 +214,14 @@ Log plots The :func:`~matplotlib.pyplot.semilogx`, :func:`~matplotlib.pyplot.semilogy` and -:func:`~matplotlib.pyplot.loglog` functions generate log scaling on the -respective axes. The lower subplot uses a base10 log on the xaxis and -a base 4 log on the yaxis. Thanks to Andrew Straw, Darren Dale and -Gregory Lielens for contributions to the log scaling -infrastructure. - - +:func:`~matplotlib.pyplot.loglog` functions simplify the creation of +logarithmic plots. .. plot:: mpl_examples/pylab_examples/log_demo.py +Thanks to Andrew Straw, Darren Dale and Gregory Lielens for contributions +log-scaling infrastructure. + .. _screenshots_polar_demo: Polar plots @@ -222,40 +233,43 @@ The :func:`~matplotlib.pyplot.polar` command generates polar plots. .. _screenshots_legend_demo: + Legends ======= The :func:`~matplotlib.pyplot.legend` command automatically -generates figure legends, with MATLAB compatible legend placement -commands. Thanks to Charles Twardy for input on the legend -command +generates figure legends, with MATLAB-compatible legend placement +commands. .. plot:: mpl_examples/pylab_examples/legend_demo.py +Thanks to Charles Twardy for input on the legend command. + .. _screenshots_mathtext_examples_demo: Mathtext_examples ================= -A sampling of the many TeX expressions now supported by matplotlib's -internal mathtext engine. The mathtext module provides TeX style -mathematical expressions using `freetype2 -`_ and the BaKoMa -computer modern or `STIX `_ fonts. See the -:mod:`matplotlib.mathtext` module for additional. matplotlib mathtext -is an independent implementation, and does not required TeX or any -external packages installed on your computer. See the tutorial at -:ref:`mathtext-tutorial`. +Below is a sampling of the many TeX expressions now supported by matplotlib's +internal mathtext engine. The mathtext module provides TeX style mathematical +expressions using `freetype2 `_ +and the BaKoMa computer modern or `STIX `_ fonts. +See the :mod:`matplotlib.mathtext` module for additional details. .. plot:: mpl_examples/pylab_examples/mathtext_examples.py +Matplotlib's mathtext infrastructure is an independent implementation and +does not require TeX or any external packages installed on your computer. See +the tutorial at :ref:`mathtext-tutorial`. + + .. _screenshots_tex_demo: Native TeX rendering ==================== Although matplotlib's internal math rendering engine is quite -powerful, sometimes you need TeX, and matplotlib supports external TeX +powerful, sometimes you need TeX. Matplotlib supports external TeX rendering of strings with the *usetex* option. .. plot:: pyplots/tex_demo.py @@ -265,17 +279,20 @@ rendering of strings with the *usetex* option. EEG demo ========= -You can embed matplotlib into pygtk, wxpython, Tk, FLTK or Qt -applications. Here is a screenshot of an eeg viewer called pbrain -which is part of the NeuroImaging in Python suite `NIPY -`_. Pbrain is written in pygtk using -matplotlib. The lower axes uses :func:`~matplotlib.pyplot.specgram` -to plot the spectrogram of one of the EEG channels. For an example of -how to use the navigation toolbar in your applications, see -:ref:`user_interfaces-embedding_in_gtk2`. If you want to use -matplotlib in a wx application, see -:ref:`user_interfaces-embedding_in_wx2`. If you want to work with -`glade `_, see -:ref:`user_interfaces-mpl_with_glade`. +You can embed matplotlib into pygtk, wx, Tk, FLTK, or Qt +applications. Here is a screenshot of an EEG viewer called pbrain, +which is part of the NeuroImaging in Python suite +`NIPY `_. .. image:: ../_static/eeg_small.png + +The lower axes uses :func:`~matplotlib.pyplot.specgram` +to plot the spectrogram of one of the EEG channels. + +For examples of how to embed matplotlib in different toolkits, see: + + * :ref:`user_interfaces-embedding_in_gtk2` + * :ref:`user_interfaces-embedding_in_wx2` + * :ref:`user_interfaces-mpl_with_glade` + * :ref:`user_interfaces-embedding_in_qt` + * :ref:`user_interfaces-embedding_in_tk` diff --git a/examples/api/legend_demo.py b/examples/api/legend_demo.py index 31d257f1e831..63f25a46bb26 100644 --- a/examples/api/legend_demo.py +++ b/examples/api/legend_demo.py @@ -1,41 +1,42 @@ +""" +Demo of the legend function with a few features. + +In addition to the basic legend, this demo shows a few optional features: + + * Custom legend placement. + * A keyword argument to a drop-shadow. + * Setting the background color. + * Setting the font size. + * Setting the line width. +""" import numpy as np import matplotlib.pyplot as plt -a = np.arange(0,3,.02) -b = np.arange(0,3,.02) + +# Example data +a = np.arange(0,3, .02) +b = np.arange(0,3, .02) c = np.exp(a) d = c[::-1] -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(a,c,'k--',a,d,'k:',a,c+d,'k') -leg = ax.legend(('Model length', 'Data length', 'Total message length'), - 'upper center', shadow=True) -ax.set_ylim([-1,20]) -ax.grid(False) -ax.set_xlabel('Model complexity --->') -ax.set_ylabel('Message length --->') -ax.set_title('Minimum Message Length') - -ax.set_yticklabels([]) -ax.set_xticklabels([]) - -# set some legend properties. All the code below is optional. The -# defaults are usually sensible but if you need more control, this -# shows you how - -# the matplotlib.patches.Rectangle instance surrounding the legend -frame = leg.get_frame() -frame.set_facecolor('0.80') # set the frame face color to light gray - -# matplotlib.text.Text instances -for t in leg.get_texts(): - t.set_fontsize('small') # the legend text fontsize - -# matplotlib.lines.Line2D instances -for l in leg.get_lines(): - l.set_linewidth(1.5) # the legend line width -plt.show() +# Create plots with pre-defined labels. +# Alternatively, you can pass labels explicitly when calling `legend`. +fig, ax = plt.subplots() +ax.plot(a, c, 'k--', label='Model length') +ax.plot(a, d, 'k:', label='Data length') +ax.plot(a, c+d, 'k', label='Total message length') + +# Now add the legend with some customizations. +legend = ax.legend(loc='upper center', shadow=True) +# The frame is matplotlib.patches.Rectangle instance surrounding the legend. +frame = legend.get_frame() +frame.set_facecolor('0.90') +# Set the fontsize +for label in legend.get_texts(): + label.set_fontsize('large') +for label in legend.get_lines(): + label.set_linewidth(1.5) # the legend line width +plt.show() diff --git a/examples/pylab_examples/barchart_demo.py b/examples/pylab_examples/barchart_demo.py index e5f86cf4d2c5..e71357d743e3 100644 --- a/examples/pylab_examples/barchart_demo.py +++ b/examples/pylab_examples/barchart_demo.py @@ -1,44 +1,43 @@ - -#!/usr/bin/env python +""" +Bar chart demo with pairs of bars grouped for easy comparison. +""" import numpy as np import matplotlib.pyplot as plt -N = 5 -menMeans = (20, 35, 30, 35, 27) -menStd = (2, 3, 4, 1, 2) -ind = np.arange(N) # the x locations for the groups -width = 0.35 # the width of the bars +n_groups = 5 +means_men = (20, 35, 30, 35, 27) +std_men = (2, 3, 4, 1, 2) -plt.subplot(111) -rects1 = plt.bar(ind, menMeans, width, - color='r', - yerr=menStd, - error_kw=dict(elinewidth=6, ecolor='pink')) +means_women = (25, 32, 34, 20, 25) +std_women = (3, 5, 2, 3, 3) -womenMeans = (25, 32, 34, 20, 25) -womenStd = (3, 5, 2, 3, 3) -rects2 = plt.bar(ind+width, womenMeans, width, - color='y', - yerr=womenStd, - error_kw=dict(elinewidth=6, ecolor='yellow')) +index = np.arange(n_groups) +bar_width = 0.35 -# add some -plt.ylabel('Scores') -plt.title('Scores by group and gender') -plt.xticks(ind+width, ('G1', 'G2', 'G3', 'G4', 'G5') ) +opacity = 0.4 +error_config = {'ecolor': '0.3'} -plt.legend( (rects1[0], rects2[0]), ('Men', 'Women') ) +rects1 = plt.bar(index, means_men, bar_width, + alpha=opacity, + color='b', + yerr=std_men, + error_kw=error_config, + label='Men') -def autolabel(rects): - # attach some text labels - for rect in rects: - height = rect.get_height() - plt.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height), - ha='center', va='bottom') +rects2 = plt.bar(index + bar_width, means_women, bar_width, + alpha=opacity, + color='r', + yerr=std_women, + error_kw=error_config, + label='Women') -autolabel(rects1) -autolabel(rects2) +plt.xlabel('Group') +plt.ylabel('Scores') +plt.title('Scores by group and gender') +plt.xticks(index + bar_width, ('A', 'B', 'C', 'D', 'E')) +plt.legend() +plt.tight_layout() plt.show() diff --git a/examples/pylab_examples/legend_demo.py b/examples/pylab_examples/legend_demo.py index 34a4a56981f2..63f25a46bb26 100644 --- a/examples/pylab_examples/legend_demo.py +++ b/examples/pylab_examples/legend_demo.py @@ -1,46 +1,42 @@ -#!/usr/bin/env python -# Thanks to Charles Twardy for this example -# -#See http://matplotlib.org/examples/pylab_examples/legend_demo2.html -# for an example controlling which lines the legend uses and the order -# they are drawn in. +""" +Demo of the legend function with a few features. +In addition to the basic legend, this demo shows a few optional features: + + * Custom legend placement. + * A keyword argument to a drop-shadow. + * Setting the background color. + * Setting the font size. + * Setting the line width. +""" import numpy as np import matplotlib.pyplot as plt -a = np.arange(0,3,.02) -b = np.arange(0,3,.02) + +# Example data +a = np.arange(0,3, .02) +b = np.arange(0,3, .02) c = np.exp(a) d = c[::-1] -ax = plt.subplot(111) -plt.plot(a,c,'k--',a,d,'k:',a,c+d,'k') -plt.legend(('Model length', 'Data length', 'Total message length'), - 'upper center', shadow=True, fancybox=True) -plt.ylim([-1,20]) -plt.grid(False) -plt.xlabel('Model complexity --->') -plt.ylabel('Message length --->') -plt.title('Minimum Message Length') - -plt.setp(plt.gca(), 'yticklabels', []) -plt.setp(plt.gca(), 'xticklabels', []) - -# set some legend properties. All the code below is optional. The -# defaults are usually sensible but if you need more control, this -# shows you how -leg = plt.gca().get_legend() -ltext = leg.get_texts() # all the text.Text instance in the legend -llines = leg.get_lines() # all the lines.Line2D instance in the legend -frame = leg.get_frame() # the patch.Rectangle instance surrounding the legend - -# see text.Text, lines.Line2D, and patches.Rectangle for more info on -# the settable properties of lines, text, and rectangles -frame.set_facecolor('0.80') # set the frame face color to light gray -plt.setp(ltext, fontsize='small') # the legend text fontsize -plt.setp(llines, linewidth=1.5) # the legend linewidth -#leg.draw_frame(False) # don't draw the legend frame -plt.show() +# Create plots with pre-defined labels. +# Alternatively, you can pass labels explicitly when calling `legend`. +fig, ax = plt.subplots() +ax.plot(a, c, 'k--', label='Model length') +ax.plot(a, d, 'k:', label='Data length') +ax.plot(a, c+d, 'k', label='Total message length') +# Now add the legend with some customizations. +legend = ax.legend(loc='upper center', shadow=True) +# The frame is matplotlib.patches.Rectangle instance surrounding the legend. +frame = legend.get_frame() +frame.set_facecolor('0.90') +# Set the fontsize +for label in legend.get_texts(): + label.set_fontsize('large') + +for label in legend.get_lines(): + label.set_linewidth(1.5) # the legend line width +plt.show() diff --git a/examples/pylab_examples/polar_demo.py b/examples/pylab_examples/polar_demo.py index 9492b59e3d93..3127cb55fde2 100644 --- a/examples/pylab_examples/polar_demo.py +++ b/examples/pylab_examples/polar_demo.py @@ -1,64 +1,17 @@ -#!/usr/bin/env python -# -# matplotlib now has a PolarAxes class and a polar function in the -# matplotlib interface. This is considered alpha and the interface -# may change as we work out how polar axes should best be integrated -# -# The only function that has been tested on polar axes is "plot" (the -# pylab interface function "polar" calls ax.plot where ax is a -# PolarAxes) -- other axes plotting functions may work on PolarAxes -# but haven't been tested and may need tweaking. -# -# you can get a PolarSubplot instance by doing, for example -# -# subplot(211, polar=True) -# -# or a PolarAxes instance by doing -# axes([left, bottom, width, height], polar=True) -# -# The view limits (eg xlim and ylim) apply to the lower left and upper -# right of the rectangular box that surrounds to polar axes. e.g., if -# you have -# -# r = arange(0,1,0.01) -# theta = 2*pi*r -# -# the lower left corner is 5/4pi, sqrt(2) and the -# upper right corner is 1/4pi, sqrt(2) -# -# you could change the radial bounding box (zoom out) by setting the -# ylim (radial coordinate is the second argument to the plot command, -# as in MATLAB, though this is not advised currently because it is not -# clear to me how the axes should behave in the change of view limits. -# Please advise me if you have opinions. Likewise, the pan/zoom -# controls probably do not do what you think they do and are better -# left alone on polar axes. Perhaps I will disable them for polar -# axes unless we come up with a meaningful, useful and functional -# implementation for them. -# -# See the pylab rgrids and thetagrids functions for -# information on how to customize the grid locations and labels -import matplotlib +""" +Demo of a line plot on a polar axis. +""" import numpy as np -from matplotlib.pyplot import figure, show, rc, grid +import matplotlib.pyplot as plt -# radar green, solid grid lines -rc('grid', color='#316931', linewidth=1, linestyle='-') -rc('xtick', labelsize=15) -rc('ytick', labelsize=15) - -# force square figure and square axes looks better for polar, IMO -width, height = matplotlib.rcParams['figure.figsize'] -size = min(width, height) -# make a square figure -fig = figure(figsize=(size, size)) -ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c') r = np.arange(0, 3.0, 0.01) -theta = 2*np.pi*r -ax.plot(theta, r, color='#ee8d18', lw=3) +theta = 2 * np.pi * r + +ax = plt.subplot(111, polar=True) +ax.plot(theta, r, color='r', linewidth=3) ax.set_rmax(2.0) -grid(True) +ax.grid(True) -ax.set_title("And there was much rejoicing!", fontsize=20) -show() +ax.set_title("A line plot on a polar axis", va='bottom') +plt.show() diff --git a/examples/pylab_examples/scatter_demo2.py b/examples/pylab_examples/scatter_demo2.py index 6c06adf27980..6eb9e18a192f 100644 --- a/examples/pylab_examples/scatter_demo2.py +++ b/examples/pylab_examples/scatter_demo2.py @@ -1,38 +1,33 @@ """ -make a scatter plot with varying color and size arguments +Demo of scatter plot with varying marker colors and sizes. """ -import matplotlib import numpy as np import matplotlib.pyplot as plt -import matplotlib.mlab as mlab import matplotlib.cbook as cbook -# load a numpy record array from yahoo csv data with fields date, +# Load a numpy record array from yahoo csv data with fields date, # open, close, volume, adj_close from the mpl-data/example directory. # The record array stores python datetime.date as an object array in # the date column datafile = cbook.get_sample_data('goog.npy') -r = np.load(datafile).view(np.recarray) -r = r[-250:] # get the most recent 250 trading days +price_data = np.load(datafile).view(np.recarray) +price_data = price_data[-250:] # get the most recent 250 trading days -delta1 = np.diff(r.adj_close)/r.adj_close[:-1] +delta1 = np.diff(price_data.adj_close)/price_data.adj_close[:-1] -# size in points ^2 -volume = (15*r.volume[:-2]/r.volume[0])**2 -close = 0.003*r.close[:-2]/0.003*r.open[:-2] +# Marker size in units of points^2 +volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2 +close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2] -fig = plt.figure() -ax = fig.add_subplot(111) -ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.75) - -#ticks = arange(-0.06, 0.061, 0.02) -#xticks(ticks) -#yticks(ticks) +fig, ax = plt.subplots() +ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5) ax.set_xlabel(r'$\Delta_i$', fontsize=20) ax.set_ylabel(r'$\Delta_{i+1}$', fontsize=20) ax.set_title('Volume and percent change') + ax.grid(True) +fig.tight_layout() plt.show() diff --git a/examples/pylab_examples/table_demo.py b/examples/pylab_examples/table_demo.py index a4495fb97174..8e80056c347d 100644 --- a/examples/pylab_examples/table_demo.py +++ b/examples/pylab_examples/table_demo.py @@ -1,57 +1,9 @@ -#!/usr/bin/env python -import matplotlib +""" +Demo of table function to display a table within a plot. +""" +import numpy as np +import matplotlib.pyplot as plt -from pylab import * -from matplotlib.colors import colorConverter - - -#Some simple functions to generate colours. -def pastel(colour, weight=2.4): - """ Convert colour into a nice pastel shade""" - rgb = asarray(colorConverter.to_rgb(colour)) - # scale colour - maxc = max(rgb) - if maxc < 1.0 and maxc > 0: - # scale colour - scale = 1.0 / maxc - rgb = rgb * scale - # now decrease saturation - total = sum(rgb) - slack = 0 - for x in rgb: - slack += 1.0 - x - - # want to increase weight from total to weight - # pick x s.t. slack * x == weight - total - # x = (weight - total) / slack - x = (weight - total) / slack - - rgb = [c + (x * (1.0-c)) for c in rgb] - - return rgb - -def get_colours(n): - """ Return n pastel colours. """ - base = asarray([[1,0,0], [0,1,0], [0,0,1]]) - - if n <= 3: - return base[0:n] - - # how many new colours to we need to insert between - # red and green and between green and blue? - needed = (((n - 3) + 1) / 2, (n - 3) / 2) - - colours = [] - for start in (0, 1): - for x in linspace(0, 1, needed[start]+2): - colours.append((base[start] * (1.0 - x)) + - (base[start+1] * x)) - - return [pastel(c) for c in colours[0:n]] - - - -axes([0.2, 0.2, 0.7, 0.6]) # leave room below the axes for the table data = [[ 66386, 174296, 75131, 577908, 32015], [ 58230, 381139, 78045, 99308, 160454], @@ -59,34 +11,45 @@ def get_colours(n): [ 78415, 81858, 150656, 193263, 69638], [ 139361, 331509, 343164, 781380, 52269]] -colLabels = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail') -rowLabels = ['%d year' % x for x in (100, 50, 20, 10, 5)] +columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail') +rows = ['%d year' % x for x in (100, 50, 20, 10, 5)] + +values = np.arange(0, 2500, 500) +value_increment = 1000 -# Get some pastel shades for the colours -colours = get_colours(len(colLabels)) -colours.reverse() -rows = len(data) +# Get some pastel shades for the colors +colors = plt.cm.BuPu(np.linspace(0, 0.5, len(columns))) +n_rows = len(data) -ind = arange(len(colLabels)) + 0.3 # the x locations for the groups -cellText = [] -width = 0.4 # the width of the bars -yoff = array([0.0] * len(colLabels)) # the bottom values for stacked bar chart -for row in range(rows): - bar(ind, data[row], width, bottom=yoff, color=colours[row]) - yoff = yoff + data[row] - cellText.append(['%1.1f' % (x/1000.0) for x in yoff]) +index = np.arange(len(columns)) + 0.3 +bar_width = 0.4 + +# Initialize the vertical-offset for the stacked bar chart. +y_offset = np.array([0.0] * len(columns)) + +# Plot bars and create text labels for the table +cell_text = [] +for row in range(n_rows): + plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row]) + y_offset = y_offset + data[row] + cell_text.append(['%1.1f' % (x/1000.0) for x in y_offset]) +# Reverse colors and text labels to display the last value at the top. +colors = colors[::-1] +cell_text.reverse() # Add a table at the bottom of the axes -colours.reverse() -cellText.reverse() -the_table = table(cellText=cellText, - rowLabels=rowLabels, rowColours=colours, - colLabels=colLabels, - loc='bottom') -ylabel("Loss $1000's") -vals = arange(0, 2500, 500) -yticks(vals*1000, ['%d' % val for val in vals]) -xticks([]) -title('Loss by Disaster') +the_table = plt.table(cellText=cell_text, + rowLabels=rows, + rowColours=colors, + colLabels=columns, + loc='bottom') + +# Adjust layout to make room for the table: +plt.subplots_adjust(left=0.2, bottom=0.2) + +plt.ylabel("Loss in ${0}'s".format(value_increment)) +plt.yticks(values * value_increment, ['%d' % val for val in values]) +plt.xticks([]) +plt.title('Loss by Disaster') -show() +plt.show()