From c6e6770cff24b1397c12080c4c27c157de05cd99 Mon Sep 17 00:00:00 2001 From: Paul Ivanov Date: Wed, 7 Nov 2012 18:41:10 -0800 Subject: [PATCH 1/2] use plt.subplots() in examples as much as possible At the recent LBL Software Carpentry Workshop, it was pointed out that there's an inconsistency within our documentation for how to create new figures with subplots. Indeed, most examples were using the old way, something like: fig = plt.figure() ax = plt.subplot(111) # or plt.add_subplot(111) This patch changes a whole bunch of instances like the above to: fig, ax = plt.subplots() We should strive to have a minimal amount of constants in our code, especially unusual ones like `111`, which only make sense to Matlab refugees. I have left unchanged examples which were using axes keywords passed to subplot() and add_subplot(), since those end up transforming things like: figure() subplot(111, axisbg='w') to plt.subplots(subplot_kw=dict(axisbg='w')) which isn't necessarily better. I also did not touch most of the user_interfaces examples, since those did not involve using plt, but instead explicitly imported Figure, and used the OO approach on Figure instances. Also updated instaces where the old "import pylab as p" convention was used to use our standard "import matplotlib.pyplot as plt" I have also updated some, but not all uses of subplot(121) etc, but I'm a bit exhausted after doing all of these. --- examples/animation/animate_decay.py | 3 +- examples/animation/bayes_update.py | 3 +- examples/animation/histogram.py | 3 +- .../old_animation/animate_decay_tk_blit.py | 3 +- .../old_animation/animation_blit_fltk.py | 12 ++--- .../old_animation/animation_blit_gtk.py | 3 +- .../old_animation/animation_blit_gtk2.py | 3 +- .../old_animation/animation_blit_qt.py | 2 +- .../old_animation/animation_blit_tk.py | 14 +++--- .../old_animation/animation_blit_wx.py | 2 +- .../old_animation/draggable_legend.py | 5 +- .../animation/old_animation/gtk_timeout.py | 3 +- .../old_animation/histogram_tkagg.py | 3 +- .../old_animation/simple_anim_gtk.py | 4 +- .../old_animation/simple_anim_tkagg.py | 3 +- .../animation/old_animation/simple_idle_wx.py | 4 +- .../old_animation/simple_timer_wx.py | 4 +- .../old_animation/strip_chart_demo.py | 3 +- examples/animation/random_data.py | 3 +- examples/animation/simple_anim.py | 3 +- examples/animation/strip_chart_demo.py | 3 +- examples/api/README.txt | 3 +- examples/api/agg_oo.py | 6 +-- examples/api/barchart_demo.py | 3 +- examples/api/collections_demo.py | 50 ++++++++----------- examples/api/color_cycle.py | 18 +++---- examples/api/compound_path.py | 3 +- examples/api/date_demo.py | 3 +- examples/api/date_index_formatter.py | 6 +-- examples/api/demo_affine_image.py | 5 +- examples/api/donut_demo.py | 3 +- examples/api/engineering_formatter.py | 2 +- examples/api/fahrenheit_celsius_scales.py | 5 +- examples/api/font_family_rc.py | 3 +- examples/api/font_file.py | 3 +- examples/api/hinton_demo.py | 3 +- examples/api/histogram_demo.py | 3 +- examples/api/histogram_path_demo.py | 3 +- examples/api/image_zcoord.py | 3 +- examples/api/joinstyle.py | 3 +- examples/api/legend_demo.py | 3 +- examples/api/line_with_text.py | 3 +- examples/api/patch_collection.py | 3 +- examples/api/path_patch_demo.py | 3 +- examples/api/quad_bezier.py | 3 +- examples/api/scatter_piecharts.py | 3 +- examples/api/span_regions.py | 3 +- examples/api/two_scales.py | 3 +- examples/api/unicode_minus.py | 3 +- examples/api/watermark_image.py | 3 +- examples/api/watermark_text.py | 4 +- examples/axes_grid/demo_axes_divider.py | 4 +- examples/axes_grid/demo_axes_hbox_divider.py | 12 ++--- examples/axes_grid/demo_axes_rgb.py | 5 +- .../demo_colorbar_with_inset_locator.py | 14 ++---- examples/axes_grid/inset_locator_demo.py | 10 ++-- examples/axes_grid/inset_locator_demo2.py | 4 +- examples/axes_grid/scatter_hist.py | 6 +-- examples/event_handling/data_browser.py | 4 +- .../event_handling/figure_axes_enter_leave.py | 8 +-- examples/event_handling/idle_and_timeout.py | 3 +- examples/event_handling/keypress_demo.py | 3 +- examples/event_handling/legend_picking.py | 3 +- examples/event_handling/looking_glass.py | 3 +- examples/event_handling/path_editor.py | 3 +- examples/event_handling/pick_event_demo.py | 34 ++++++------- examples/event_handling/pick_event_demo2.py | 3 +- examples/event_handling/poly_editor.py | 3 +- examples/event_handling/pong_gtk.py | 3 +- examples/event_handling/pong_qt.py | 2 +- examples/event_handling/resample.py | 3 +- examples/event_handling/timers.py | 3 +- examples/event_handling/viewlims.py | 5 +- examples/misc/longshort.py | 3 +- examples/misc/multiprocess.py | 4 +- examples/misc/rasterization_demo.py | 5 +- .../pylab_examples/agg_buffer_to_array.py | 3 +- examples/pylab_examples/annotation_demo3.py | 6 +-- examples/pylab_examples/aspect_loglog.py | 3 +- examples/pylab_examples/axes_props.py | 2 +- examples/pylab_examples/barchart_demo.py | 2 +- examples/pylab_examples/barchart_demo2.py | 4 +- examples/pylab_examples/boxplot_demo2.py | 3 +- examples/pylab_examples/boxplot_demo3.py | 3 +- examples/pylab_examples/broken_barh.py | 3 +- .../pylab_examples/centered_ticklabels.py | 3 +- .../colorbar_tick_labelling_demo.py | 6 +-- examples/pylab_examples/coords_demo.py | 2 +- examples/pylab_examples/coords_report.py | 2 +- examples/pylab_examples/cursor_demo.py | 2 +- examples/pylab_examples/custom_ticker1.py | 2 +- examples/pylab_examples/dashpointlabel.py | 4 +- examples/pylab_examples/date_demo1.py | 3 +- examples/pylab_examples/date_demo2.py | 3 +- examples/pylab_examples/date_demo_convert.py | 3 +- examples/pylab_examples/date_demo_rrule.py | 2 +- .../pylab_examples/date_index_formatter.py | 3 +- .../pylab_examples/demo_annotation_box.py | 4 +- examples/pylab_examples/demo_ribbon_box.py | 4 +- examples/pylab_examples/dolphin.py | 3 +- examples/pylab_examples/ellipse_collection.py | 2 +- examples/pylab_examples/fill_between_demo.py | 3 +- examples/pylab_examples/fill_demo2.py | 7 ++- examples/pylab_examples/finance_demo.py | 3 +- examples/pylab_examples/findobj_demo.py | 3 +- examples/pylab_examples/hist_colormapped.py | 3 +- examples/pylab_examples/integral_demo.py | 2 +- examples/pylab_examples/interp_demo.py | 7 ++- examples/pylab_examples/legend_demo.py | 2 +- examples/pylab_examples/major_minor_demo1.py | 2 +- examples/pylab_examples/major_minor_demo2.py | 2 +- examples/pylab_examples/movie_demo.py | 6 +-- .../multiple_yaxis_with_spines.py | 3 +- examples/pylab_examples/pcolor_demo2.py | 2 +- .../pylab_examples/scatter_custom_symbol.py | 3 +- examples/pylab_examples/scatter_demo2.py | 3 +- examples/pylab_examples/stackplot_demo.py | 6 +-- examples/pylab_examples/stock_demo.py | 2 +- examples/pylab_examples/system_monitor.py | 3 +- examples/pylab_examples/text_handles.py | 2 +- examples/units/annotate_with_units.py | 4 +- examples/units/artist_tests.py | 7 ++- examples/units/bar_unit_demo.py | 3 +- .../user_interfaces/lineprops_dialog_gtk.py | 3 +- examples/user_interfaces/pylab_with_gtk.py | 2 +- examples/user_interfaces/svg_tooltip.py | 3 +- examples/widgets/buttons.py | 2 +- examples/widgets/check_buttons.py | 2 +- examples/widgets/radio_buttons.py | 2 +- examples/widgets/rectangle_selector.py | 2 +- examples/widgets/slider_demo.py | 2 +- lib/matplotlib/pylab.py | 3 +- 132 files changed, 214 insertions(+), 360 deletions(-) diff --git a/examples/animation/animate_decay.py b/examples/animation/animate_decay.py index 90267c605032..a8694615e99b 100644 --- a/examples/animation/animate_decay.py +++ b/examples/animation/animate_decay.py @@ -11,8 +11,7 @@ def data_gen(): yield t, np.sin(2*np.pi*t) * np.exp(-t/10.) data_gen.t = 0 -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() line, = ax.plot([], [], lw=2) ax.set_ylim(-1.1, 1.1) ax.set_xlim(0, 5) diff --git a/examples/animation/bayes_update.py b/examples/animation/bayes_update.py index e3ba5a356a20..bdd38d4977cc 100644 --- a/examples/animation/bayes_update.py +++ b/examples/animation/bayes_update.py @@ -39,8 +39,7 @@ def __call__(self, i): self.line.set_data(self.x, y) return self.line, -fig = plt.figure() -ax = fig.add_subplot(1, 1, 1) +fig, ax = plt.subplots() ud = UpdateDist(ax, prob=0.7) anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init, interval=100, blit=True) diff --git a/examples/animation/histogram.py b/examples/animation/histogram.py index b1aa9249dff7..f81d4f397269 100644 --- a/examples/animation/histogram.py +++ b/examples/animation/histogram.py @@ -9,8 +9,7 @@ import matplotlib.path as path import matplotlib.animation as animation -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() # histogram our data with numpy data = np.random.randn(1000) diff --git a/examples/animation/old_animation/animate_decay_tk_blit.py b/examples/animation/old_animation/animate_decay_tk_blit.py index cae4c4a2b973..36e451f803f6 100644 --- a/examples/animation/old_animation/animate_decay_tk_blit.py +++ b/examples/animation/old_animation/animate_decay_tk_blit.py @@ -10,8 +10,7 @@ def data_gen(): return np.sin(2*np.pi*t) * np.exp(-t/10.) data_gen.t = 0 -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() line, = ax.plot([], [], animated=True, lw=2) ax.set_ylim(-1.1, 1.1) ax.set_xlim(0, 5) diff --git a/examples/animation/old_animation/animation_blit_fltk.py b/examples/animation/old_animation/animation_blit_fltk.py index 9a178bc540ff..8d59df8317bd 100644 --- a/examples/animation/old_animation/animation_blit_fltk.py +++ b/examples/animation/old_animation/animation_blit_fltk.py @@ -3,7 +3,7 @@ import fltk import matplotlib matplotlib.use('FltkAgg') -import pylab as p +import matplotlib.pyplot as plt import numpy as npy import time @@ -42,13 +42,13 @@ def update(self,ptr): sys.exit() return True -ax = p.subplot(111) -p.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs -p.grid() # to ensure proper background restore +fig, ax = plt.subplots() +plt.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs +plt.grid() # to ensure proper background restore # create the initial line x = npy.arange(0,2*npy.pi,0.01) -line, = p.plot(x, npy.sin(x), animated=True) -p.draw() +line, = plt.plot(x, npy.sin(x), animated=True) +plt.draw() anim=animator(ax) fltk.Fl.add_idle(anim.update) diff --git a/examples/animation/old_animation/animation_blit_gtk.py b/examples/animation/old_animation/animation_blit_gtk.py index a13fed6d3ff8..9200daf778f7 100755 --- a/examples/animation/old_animation/animation_blit_gtk.py +++ b/examples/animation/old_animation/animation_blit_gtk.py @@ -16,8 +16,7 @@ import matplotlib.pyplot as plt -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() canvas = fig.canvas fig.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs diff --git a/examples/animation/old_animation/animation_blit_gtk2.py b/examples/animation/old_animation/animation_blit_gtk2.py index b15b1ab177a6..58673fd95c2d 100755 --- a/examples/animation/old_animation/animation_blit_gtk2.py +++ b/examples/animation/old_animation/animation_blit_gtk2.py @@ -148,9 +148,8 @@ def update_line(self, *args): plt.rcParams["text.usetex"] = False -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.xaxis.set_animated(True) ax.yaxis.set_animated(True) canvas = fig.canvas diff --git a/examples/animation/old_animation/animation_blit_qt.py b/examples/animation/old_animation/animation_blit_qt.py index 272997315e93..12a28ffa3fd6 100644 --- a/examples/animation/old_animation/animation_blit_qt.py +++ b/examples/animation/old_animation/animation_blit_qt.py @@ -24,7 +24,7 @@ class BlitQT(QObject): def __init__(self): QObject.__init__(self, None, "app") - self.ax = p.subplot(111) + fig, self.ax = plt.subplots() self.canvas = self.ax.figure.canvas self.cnt = 0 diff --git a/examples/animation/old_animation/animation_blit_tk.py b/examples/animation/old_animation/animation_blit_tk.py index 54e288efd621..0a83e1c75198 100644 --- a/examples/animation/old_animation/animation_blit_tk.py +++ b/examples/animation/old_animation/animation_blit_tk.py @@ -7,17 +7,17 @@ matplotlib.use('TkAgg') import sys -import pylab as p +import matplotlib.pyplot as plt import numpy as npy import time -ax = p.subplot(111) +fig, ax = plt.subplots() canvas = ax.figure.canvas # create the initial line x = npy.arange(0,2*npy.pi,0.01) -line, = p.plot(x, npy.sin(x), animated=True, lw=2) +line, = plt.plot(x, npy.sin(x), animated=True, lw=2) def run(*args): background = canvas.copy_from_bbox(ax.bbox) @@ -43,12 +43,12 @@ def run(*args): run.cnt = 0 -p.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs -p.grid() # to ensure proper background restore -manager = p.get_current_fig_manager() +plt.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs +plt.grid() # to ensure proper background restore +manager = plt.get_current_fig_manager() manager.window.after(100, run) -p.show() +plt.show() diff --git a/examples/animation/old_animation/animation_blit_wx.py b/examples/animation/old_animation/animation_blit_wx.py index f2ad18be03d7..6071581b31b3 100644 --- a/examples/animation/old_animation/animation_blit_wx.py +++ b/examples/animation/old_animation/animation_blit_wx.py @@ -24,7 +24,7 @@ matplotlib.backends.backend_wxagg._use_accelerator(False) -ax = p.subplot(111) +fig, ax = plt.subplots() canvas = ax.figure.canvas diff --git a/examples/animation/old_animation/draggable_legend.py b/examples/animation/old_animation/draggable_legend.py index fca88158b02c..e9161c1b0e92 100644 --- a/examples/animation/old_animation/draggable_legend.py +++ b/examples/animation/old_animation/draggable_legend.py @@ -1,13 +1,12 @@ import matplotlib.pyplot as plt - -ax = plt.subplot(111) +fig, ax = plt.subplots() ax.plot([1,2,3], label="test") l = ax.legend() d1 = l.draggable() -xy = 1, 2 +xy = 1, 2 txt = ax.annotate("Test", xy, xytext=(-30, 30), textcoords="offset points", bbox=dict(boxstyle="round",fc=(0.2, 1, 1)), diff --git a/examples/animation/old_animation/gtk_timeout.py b/examples/animation/old_animation/gtk_timeout.py index b35e2b659dd1..d76f609cdb9e 100644 --- a/examples/animation/old_animation/gtk_timeout.py +++ b/examples/animation/old_animation/gtk_timeout.py @@ -5,8 +5,7 @@ import matplotlib.pyplot as plt -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() line, = ax.plot(np.random.rand(10)) ax.set_ylim(0, 1) diff --git a/examples/animation/old_animation/histogram_tkagg.py b/examples/animation/old_animation/histogram_tkagg.py index 5536e4477d32..8236ac0b5e83 100644 --- a/examples/animation/old_animation/histogram_tkagg.py +++ b/examples/animation/old_animation/histogram_tkagg.py @@ -11,8 +11,7 @@ import matplotlib.patches as patches import matplotlib.path as path -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() # histogram our data with numpy data = np.random.randn(1000) diff --git a/examples/animation/old_animation/simple_anim_gtk.py b/examples/animation/old_animation/simple_anim_gtk.py index 6a851edd18db..ecdec7333640 100644 --- a/examples/animation/old_animation/simple_anim_gtk.py +++ b/examples/animation/old_animation/simple_anim_gtk.py @@ -9,9 +9,7 @@ import matplotlib.pyplot as plt -fig = plt.figure() - -ax = fig.add_subplot(111) +fig, ax = plt.subplots() def animate(): tstart = time.time() # for profiling diff --git a/examples/animation/old_animation/simple_anim_tkagg.py b/examples/animation/old_animation/simple_anim_tkagg.py index 427323ff14b2..e8a3a5ca314e 100755 --- a/examples/animation/old_animation/simple_anim_tkagg.py +++ b/examples/animation/old_animation/simple_anim_tkagg.py @@ -10,8 +10,7 @@ matplotlib.use('TkAgg') # do this before importing pylab import matplotlib.pyplot as plt -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() def animate(): tstart = time.time() # for profiling diff --git a/examples/animation/old_animation/simple_idle_wx.py b/examples/animation/old_animation/simple_idle_wx.py index bcc77df9137b..0612ee6fd3a0 100644 --- a/examples/animation/old_animation/simple_idle_wx.py +++ b/examples/animation/old_animation/simple_idle_wx.py @@ -9,9 +9,7 @@ import matplotlib.pyplot as plt -fig = plt.figure() - -ax = fig.add_subplot(111) +fig, ax = plt.subplots() t = np.arange(0, 2*np.pi, 0.1) line, = ax.plot(t, np.sin(t)) dt = 0.05 diff --git a/examples/animation/old_animation/simple_timer_wx.py b/examples/animation/old_animation/simple_timer_wx.py index 6e7b1607c591..a5b6f96acb98 100644 --- a/examples/animation/old_animation/simple_timer_wx.py +++ b/examples/animation/old_animation/simple_timer_wx.py @@ -9,9 +9,7 @@ import matplotlib.pyplot as plt -fig = plt.figure() - -ax = fig.add_subplot(111) +fig, ax = plt.subplots() t = np.arange(0, 2*np.pi, 0.1) line, = ax.plot(t, np.sin(t)) dt = 0.05 diff --git a/examples/animation/old_animation/strip_chart_demo.py b/examples/animation/old_animation/strip_chart_demo.py index ac7587a261d3..2362c8cb4f65 100644 --- a/examples/animation/old_animation/strip_chart_demo.py +++ b/examples/animation/old_animation/strip_chart_demo.py @@ -64,8 +64,7 @@ def update(self, *args): from pylab import figure, show -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() scope = Scope(ax) gobject.idle_add(scope.update) diff --git a/examples/animation/random_data.py b/examples/animation/random_data.py index 1a31e963a246..c3044a3dee61 100644 --- a/examples/animation/random_data.py +++ b/examples/animation/random_data.py @@ -2,8 +2,7 @@ import matplotlib.pyplot as plt import matplotlib.animation as animation -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() line, = ax.plot(np.random.rand(10)) ax.set_ylim(0, 1) diff --git a/examples/animation/simple_anim.py b/examples/animation/simple_anim.py index 78c9cdfc3ae2..d19196337522 100644 --- a/examples/animation/simple_anim.py +++ b/examples/animation/simple_anim.py @@ -5,8 +5,7 @@ import matplotlib.pyplot as plt import matplotlib.animation as animation -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() x = np.arange(0, 2*np.pi, 0.01) # x-array line, = ax.plot(x, np.sin(x)) diff --git a/examples/animation/strip_chart_demo.py b/examples/animation/strip_chart_demo.py index 119fac9f6719..33ff9d430d0e 100644 --- a/examples/animation/strip_chart_demo.py +++ b/examples/animation/strip_chart_demo.py @@ -44,8 +44,7 @@ def emitter(p=0.03): else: yield np.random.rand(1) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() scope = Scope(ax) # pass a generator in "emitter" to produce data for the update func diff --git a/examples/api/README.txt b/examples/api/README.txt index dec5d9da970d..a0b901f9d20c 100644 --- a/examples/api/README.txt +++ b/examples/api/README.txt @@ -29,8 +29,7 @@ A simple example of the recommended style is:: import numpy as np import matplotlib.pyplot as plt - fig = plt.figure() - ax = fig.add_subplot(111) # or add_axes + fig, ax = plt.subplots() ax.plot(np.random.rand(10)) ax.set_xlabel('some x data') ax.set_ylabel('some y data') diff --git a/examples/api/agg_oo.py b/examples/api/agg_oo.py index 94acbc119a32..1a5859b4b757 100644 --- a/examples/api/agg_oo.py +++ b/examples/api/agg_oo.py @@ -6,12 +6,10 @@ from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure -fig = Figure() -canvas = FigureCanvas(fig) -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot([1,2,3]) ax.set_title('hi mom') ax.grid(True) ax.set_xlabel('time') ax.set_ylabel('volts') -canvas.print_figure('test') +fig.canvas.print_figure('test') diff --git a/examples/api/barchart_demo.py b/examples/api/barchart_demo.py index 2c3468a47625..a717eb7541ec 100644 --- a/examples/api/barchart_demo.py +++ b/examples/api/barchart_demo.py @@ -11,8 +11,7 @@ ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd) womenMeans = (25, 32, 34, 20, 25) diff --git a/examples/api/collections_demo.py b/examples/api/collections_demo.py index c967be18ba22..243f1464fa47 100644 --- a/examples/api/collections_demo.py +++ b/examples/api/collections_demo.py @@ -41,69 +41,63 @@ # Make a list of colors cycling through the rgbcmyk series. colors = [colorConverter.to_rgba(c) for c in ('r','g','b','c','y','m','k')] -fig = plt.figure() +fig, axes = plt.subplots(2,2) +((ax1, ax2), (ax3, ax4)) = axes # unpack the axes + -a = fig.add_subplot(2,2,1) col = collections.LineCollection([spiral], offsets=xyo, - transOffset=a.transData) + transOffset=ax1.transData) trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0) col.set_transform(trans) # the points to pixels transform # Note: the first argument to the collection initializer # must be a list of sequences of x,y tuples; we have only # one sequence, but we still have to put it in a list. -a.add_collection(col, autolim=True) +ax1.add_collection(col, autolim=True) # autolim=True enables autoscaling. For collections with # offsets like this, it is neither efficient nor accurate, # but it is good enough to generate a plot that you can use # as a starting point. If you know beforehand the range of # x and y that you want to show, it is better to set them # explicitly, leave out the autolim kwarg (or set it to False), - # and omit the 'a.autoscale_view()' call below. + # and omit the 'ax1.autoscale_view()' call below. # Make a transform for the line segments such that their size is # given in points: col.set_color(colors) -a.autoscale_view() # See comment above, after a.add_collection. -a.set_title('LineCollection using offsets') +ax1.autoscale_view() # See comment above, after ax1.add_collection. +ax1.set_title('LineCollection using offsets') # The same data as above, but fill the curves. - -a = fig.add_subplot(2,2,2) - col = collections.PolyCollection([spiral], offsets=xyo, - transOffset=a.transData) + transOffset=ax2.transData) trans = transforms.Affine2D().scale(fig.dpi/72.0) col.set_transform(trans) # the points to pixels transform -a.add_collection(col, autolim=True) +ax2.add_collection(col, autolim=True) col.set_color(colors) -a.autoscale_view() -a.set_title('PolyCollection using offsets') +ax2.autoscale_view() +ax2.set_title('PolyCollection using offsets') # 7-sided regular polygons -a = fig.add_subplot(2,2,3) - col = collections.RegularPolyCollection(7, sizes = np.fabs(xx)*10.0, offsets=xyo, - transOffset=a.transData) + transOffset=ax3.transData) trans = transforms.Affine2D().scale(fig.dpi/72.0) col.set_transform(trans) # the points to pixels transform -a.add_collection(col, autolim=True) +ax3.add_collection(col, autolim=True) col.set_color(colors) -a.autoscale_view() -a.set_title('RegularPolyCollection using offsets') +ax3.autoscale_view() +ax3.set_title('RegularPolyCollection using offsets') # Simulate a series of ocean current profiles, successively # offset by 0.1 m/s so that they form what is sometimes called # a "waterfall" plot or a "stagger" plot. -a = fig.add_subplot(2,2,4) - nverts = 60 ncurves = 20 offs = (0.1, 0.0) @@ -118,14 +112,14 @@ segs.append(curve) col = collections.LineCollection(segs, offsets=offs) -a.add_collection(col, autolim=True) +ax4.add_collection(col, autolim=True) col.set_color(colors) -a.autoscale_view() -a.set_title('Successive data offsets') -a.set_xlabel('Zonal velocity component (m/s)') -a.set_ylabel('Depth (m)') +ax4.autoscale_view() +ax4.set_title('Successive data offsets') +ax4.set_xlabel('Zonal velocity component (m/s)') +ax4.set_ylabel('Depth (m)') # Reverse the y-axis so depth increases downward -a.set_ylim(a.get_ylim()[::-1]) +ax4.set_ylim(ax4.get_ylim()[::-1]) plt.show() diff --git a/examples/api/color_cycle.py b/examples/api/color_cycle.py index 6b2abe873cd2..4396dcc73adf 100644 --- a/examples/api/color_cycle.py +++ b/examples/api/color_cycle.py @@ -11,17 +11,15 @@ yy.shape = 6,4 mpl.rc('lines', linewidth=4) - -fig = plt.figure() mpl.rcParams['axes.color_cycle'] = ['r', 'g', 'b', 'c'] -ax = fig.add_subplot(2,1,1) -ax.plot(yy) -ax.set_title('Changed default color cycle to rgbc') - -ax = fig.add_subplot(2,1,2) -ax.set_color_cycle(['c', 'm', 'y', 'k']) -ax.plot(yy) -ax.set_title('This axes only, cycle is cmyk') + +fig, (ax1, ax2) = plt.subplots(2, 1) +ax1.plot(yy) +ax1.set_title('Changed default color cycle to rgbc') + +ax2.set_color_cycle(['c', 'm', 'y', 'k']) +ax2.plot(yy) +ax2.set_title('This axes only, cycle is cmyk') plt.show() diff --git a/examples/api/compound_path.py b/examples/api/compound_path.py index 3155010954b9..ea52986c7c95 100644 --- a/examples/api/compound_path.py +++ b/examples/api/compound_path.py @@ -23,8 +23,7 @@ pathpatch = PathPatch(path, facecolor='None', edgecolor='green') -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.add_patch(pathpatch) ax.set_title('A compound path') diff --git a/examples/api/date_demo.py b/examples/api/date_demo.py index 4348c2105064..1de554387718 100644 --- a/examples/api/date_demo.py +++ b/examples/api/date_demo.py @@ -28,8 +28,7 @@ datafile = cbook.get_sample_data('goog.npy') r = np.load(datafile).view(np.recarray) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(r.date, r.adj_close) diff --git a/examples/api/date_index_formatter.py b/examples/api/date_index_formatter.py index 7b4843aac9ce..691e4a1e66fd 100644 --- a/examples/api/date_index_formatter.py +++ b/examples/api/date_index_formatter.py @@ -19,8 +19,7 @@ # first we'll do it the default way, with gaps on weekends -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(r.date, r.adj_close, 'o-') fig.autofmt_xdate() @@ -32,8 +31,7 @@ def format_date(x, pos=None): thisind = np.clip(int(x+0.5), 0, N-1) return r.date[thisind].strftime('%Y-%m-%d') -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(ind, r.adj_close, 'o-') ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) fig.autofmt_xdate() diff --git a/examples/api/demo_affine_image.py b/examples/api/demo_affine_image.py index 68e416fbfd29..036f4a526898 100644 --- a/examples/api/demo_affine_image.py +++ b/examples/api/demo_affine_image.py @@ -32,8 +32,8 @@ def imshow_affine(ax, z, *kl, **kwargs): if 1: # image rotation - - ax1 = plt.subplot(121) + + fig, (ax1, ax2) = plt.subplots(1,2) Z = get_image() im1 = imshow_affine(ax1, Z, interpolation='none', cmap=cm.jet, origin='lower', @@ -55,7 +55,6 @@ def imshow_affine(ax, z, *kl, **kwargs): # image skew - ax2 = plt.subplot(122) im2 = ax2.imshow(Z, interpolation='none', cmap=cm.jet, origin='lower', extent=[-2, 4, -3, 2], clip_on=True) diff --git a/examples/api/donut_demo.py b/examples/api/donut_demo.py index 4bc56b1be886..b36b0e7f3291 100644 --- a/examples/api/donut_demo.py +++ b/examples/api/donut_demo.py @@ -18,8 +18,7 @@ def make_circle(r): Path = mpath.Path -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() inside_vertices = make_circle(0.5) outside_vertices = make_circle(1.0) diff --git a/examples/api/engineering_formatter.py b/examples/api/engineering_formatter.py index a71f5e230450..e70803885269 100644 --- a/examples/api/engineering_formatter.py +++ b/examples/api/engineering_formatter.py @@ -7,7 +7,7 @@ from matplotlib.ticker import EngFormatter -ax = plt.subplot(111) +fig, ax = plt.subplots() ax.set_xscale('log') formatter = EngFormatter(unit='Hz', places=1) ax.xaxis.set_major_formatter(formatter) diff --git a/examples/api/fahrenheit_celsius_scales.py b/examples/api/fahrenheit_celsius_scales.py index 5250dfb34ae1..72a52f4fa41b 100644 --- a/examples/api/fahrenheit_celsius_scales.py +++ b/examples/api/fahrenheit_celsius_scales.py @@ -4,9 +4,8 @@ import matplotlib.pyplot as plt -fig = plt.figure() -ax1 = fig.add_subplot(111) # the Fahrenheit scale -ax2 = ax1.twinx() # the Celsius scale +fig, ax1 = plt.subplots() # ax1 is the Fahrenheit scale +ax2 = ax1.twinx() # ax2 is the Celsius scale def Tc(Tf): return (5./9.)*(Tf-32) diff --git a/examples/api/font_family_rc.py b/examples/api/font_family_rc.py index d379e3163471..d3b2d4acca37 100644 --- a/examples/api/font_family_rc.py +++ b/examples/api/font_family_rc.py @@ -22,8 +22,7 @@ rcParams['font.sans-serif'] = ['Tahoma'] import matplotlib.pyplot as plt -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot([1,2,3], label='test') ax.legend() diff --git a/examples/api/font_file.py b/examples/api/font_file.py index 495b1905f679..e5f4127d1c9d 100644 --- a/examples/api/font_file.py +++ b/examples/api/font_file.py @@ -11,8 +11,7 @@ import matplotlib.pyplot as plt -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot([1,2,3]) if sys.platform == 'win32': diff --git a/examples/api/hinton_demo.py b/examples/api/hinton_demo.py index 700e13c1bb65..463928a7cdd2 100644 --- a/examples/api/hinton_demo.py +++ b/examples/api/hinton_demo.py @@ -11,8 +11,7 @@ def hinton(W, maxWeight=None, ax=None): Draws a Hinton diagram for visualizing a weight matrix. """ if not ax: - fig = plt.figure() - ax = fig.add_subplot(1, 1, 1) + fig, ax = plt.subplots() if not maxWeight: maxWeight = 2**np.ceil(np.log(np.abs(W).max())/np.log(2)) diff --git a/examples/api/histogram_demo.py b/examples/api/histogram_demo.py index 11c4b0adaba1..213291921d46 100644 --- a/examples/api/histogram_demo.py +++ b/examples/api/histogram_demo.py @@ -9,8 +9,7 @@ mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() # the histogram of the data n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75) diff --git a/examples/api/histogram_path_demo.py b/examples/api/histogram_path_demo.py index 9b21b509d800..0789264b7bca 100644 --- a/examples/api/histogram_path_demo.py +++ b/examples/api/histogram_path_demo.py @@ -15,8 +15,7 @@ import matplotlib.patches as patches import matplotlib.path as path -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() # histogram our data with numpy data = np.random.randn(1000) diff --git a/examples/api/image_zcoord.py b/examples/api/image_zcoord.py index 170f8df5e5be..69b40135075f 100644 --- a/examples/api/image_zcoord.py +++ b/examples/api/image_zcoord.py @@ -8,8 +8,7 @@ X = 10*np.random.rand(5,3) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.imshow(X, cmap=cm.jet, interpolation='nearest') numrows, numcols = X.shape diff --git a/examples/api/joinstyle.py b/examples/api/joinstyle.py index dc1a4661f52d..0693c7c3e437 100644 --- a/examples/api/joinstyle.py +++ b/examples/api/joinstyle.py @@ -17,8 +17,7 @@ def plot_angle(ax, x, y, angle, style): ax.plot(xx[1:2], yy[1:2], 'o', color='red', markersize=3) ax.text(x,y+.2,'%.0f degrees' % angle) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.set_title('Join style') for x,style in enumerate((('miter', 'round', 'bevel'))): diff --git a/examples/api/legend_demo.py b/examples/api/legend_demo.py index 31d257f1e831..75f88f1a3afd 100644 --- a/examples/api/legend_demo.py +++ b/examples/api/legend_demo.py @@ -6,8 +6,7 @@ c = np.exp(a) d = c[::-1] -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() 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) diff --git a/examples/api/line_with_text.py b/examples/api/line_with_text.py index 87be46d43edb..6c72aa2dfac0 100644 --- a/examples/api/line_with_text.py +++ b/examples/api/line_with_text.py @@ -50,8 +50,7 @@ def draw(self, renderer): -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() x, y = np.random.rand(2, 20) line = MyLine(x, y, mfc='red', ms=12, label='line label') #line.text.set_text('line label') diff --git a/examples/api/patch_collection.py b/examples/api/patch_collection.py index 44d3d403a19e..98b4ca4f6b58 100644 --- a/examples/api/patch_collection.py +++ b/examples/api/patch_collection.py @@ -5,8 +5,7 @@ import matplotlib.pyplot as plt -fig=plt.figure() -ax=fig.add_subplot(111) +fig, ax = plt.subplots() resolution = 50 # the number of vertices N = 3 diff --git a/examples/api/path_patch_demo.py b/examples/api/path_patch_demo.py index d28fa2c37015..0949c11c119d 100644 --- a/examples/api/path_patch_demo.py +++ b/examples/api/path_patch_demo.py @@ -5,8 +5,7 @@ Path = mpath.Path -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() pathdata = [ (Path.MOVETO, (1.58, -2.57)), diff --git a/examples/api/quad_bezier.py b/examples/api/quad_bezier.py index 5314dfb936b2..5bf28b94586b 100644 --- a/examples/api/quad_bezier.py +++ b/examples/api/quad_bezier.py @@ -5,8 +5,7 @@ Path = mpath.Path -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() pp1 = mpatches.PathPatch( Path([(0, 0), (1, 0), (1, 1), (0, 0)], [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), diff --git a/examples/api/scatter_piecharts.py b/examples/api/scatter_piecharts.py index 48997fb11d57..424fa70411a2 100644 --- a/examples/api/scatter_piecharts.py +++ b/examples/api/scatter_piecharts.py @@ -32,8 +32,7 @@ xy3 = list(zip(x,y)) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.scatter( np.arange(3), np.arange(3), marker=(xy1,0), s=sizes, facecolor='blue' ) ax.scatter( np.arange(3), np.arange(3), marker=(xy2,0), s=sizes, facecolor='green' ) ax.scatter( np.arange(3), np.arange(3), marker=(xy3,0), s=sizes, facecolor='red' ) diff --git a/examples/api/span_regions.py b/examples/api/span_regions.py index 7acc223e1708..1cfbdcf3dd10 100644 --- a/examples/api/span_regions.py +++ b/examples/api/span_regions.py @@ -14,8 +14,7 @@ s2 = 1.2*np.sin(4*np.pi*t) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.set_title('using span_where') ax.plot(t, s1, color='black') ax.axhline(0, color='black', lw=2) diff --git a/examples/api/two_scales.py b/examples/api/two_scales.py index 475f3ac666f7..356c81336905 100644 --- a/examples/api/two_scales.py +++ b/examples/api/two_scales.py @@ -24,8 +24,7 @@ import numpy as np import matplotlib.pyplot as plt -fig = plt.figure() -ax1 = fig.add_subplot(111) +fig, ax1 = plt.subplots() t = np.arange(0.01, 10.0, 0.01) s1 = np.exp(t) ax1.plot(t, s1, 'b-') diff --git a/examples/api/unicode_minus.py b/examples/api/unicode_minus.py index 5fc352668997..d84fb04f5b03 100644 --- a/examples/api/unicode_minus.py +++ b/examples/api/unicode_minus.py @@ -11,8 +11,7 @@ import matplotlib.pyplot as plt matplotlib.rcParams['axes.unicode_minus'] = False -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o') ax.set_title('Using hypen instead of unicode minus') plt.show() diff --git a/examples/api/watermark_image.py b/examples/api/watermark_image.py index 3d437193a05a..fcfaae00abd3 100644 --- a/examples/api/watermark_image.py +++ b/examples/api/watermark_image.py @@ -13,8 +13,7 @@ im = image.imread(datafile) im[:,:,-1] = 0.5 # set the alpha channel -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange') ax.grid() diff --git a/examples/api/watermark_text.py b/examples/api/watermark_text.py index 7d87de100032..0d09141050a9 100644 --- a/examples/api/watermark_text.py +++ b/examples/api/watermark_text.py @@ -7,9 +7,7 @@ import matplotlib.pyplot as plt -fig = plt.figure() - -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange') ax.grid() diff --git a/examples/axes_grid/demo_axes_divider.py b/examples/axes_grid/demo_axes_divider.py index 5a0652cf1052..df56d9f3f532 100644 --- a/examples/axes_grid/demo_axes_divider.py +++ b/examples/axes_grid/demo_axes_divider.py @@ -75,7 +75,7 @@ def demo_locatable_axes_easy(ax): ax_cb.yaxis.tick_right() -def demo_images_side_by_sied(ax): +def demo_images_side_by_side(ax): from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) @@ -120,7 +120,7 @@ def demo(): # two images side by side with fixed padding. ax = fig1.add_subplot(2, 2, 4) - demo_images_side_by_sied(ax) + demo_images_side_by_side(ax) plt.draw() plt.show() diff --git a/examples/axes_grid/demo_axes_hbox_divider.py b/examples/axes_grid/demo_axes_hbox_divider.py index fe72bdc14195..f63061ac45e7 100644 --- a/examples/axes_grid/demo_axes_hbox_divider.py +++ b/examples/axes_grid/demo_axes_hbox_divider.py @@ -23,19 +23,15 @@ def make_heights_equal(fig, rect, ax1, ax2, pad): if __name__ == "__main__": - fig1 = plt.figure() - arr1 = np.arange(20).reshape((4,5)) arr2 = np.arange(20).reshape((5,4)) - ax1 = plt.subplot(121) - ax2 = plt.subplot(122) - + fig, (ax1, ax2) = plt.subplots(1,2) ax1.imshow(arr1, interpolation="nearest") ax2.imshow(arr2, interpolation="nearest") rect = 111 # subplot param for combined axes - make_heights_equal(fig1, rect, ax1, ax2, pad=0.5) # pad in inches + make_heights_equal(fig, rect, ax1, ax2, pad=0.5) # pad in inches for ax in [ax1, ax2]: ax.locator_params(nbins=4) @@ -44,7 +40,9 @@ def make_heights_equal(fig, rect, ax1, ax2, pad): ax3 = plt.axes([0.5, 0.5, 0.001, 0.001], frameon=False) ax3.xaxis.set_visible(False) ax3.yaxis.set_visible(False) - ax3.annotate("Location of two axes are adjusted\n so that they have equal heights\n while maintaining their aspect ratios", (0.5, 0.5), + ax3.annotate("Location of two axes are adjusted\n" + "so that they have equal heights\n" + "while maintaining their aspect ratios", (0.5, 0.5), xycoords="axes fraction", va="center", ha="center", bbox=dict(boxstyle="round, pad=1", fc="w")) diff --git a/examples/axes_grid/demo_axes_rgb.py b/examples/axes_grid/demo_axes_rgb.py index 08c704c08ed2..b7374c2766d6 100644 --- a/examples/axes_grid/demo_axes_rgb.py +++ b/examples/axes_grid/demo_axes_rgb.py @@ -41,10 +41,7 @@ def make_cube(r, g, b): def demo_rgb(): - fig = plt.figure(1) - fig.clf() - - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax_r, ax_g, ax_b = make_rgb_axes(ax, pad=0.02) #fig.add_axes(ax_r) #fig.add_axes(ax_g) diff --git a/examples/axes_grid/demo_colorbar_with_inset_locator.py b/examples/axes_grid/demo_colorbar_with_inset_locator.py index bc5cd79cfc6c..1085e45d95ee 100644 --- a/examples/axes_grid/demo_colorbar_with_inset_locator.py +++ b/examples/axes_grid/demo_colorbar_with_inset_locator.py @@ -2,10 +2,7 @@ from mpl_toolkits.axes_grid1.inset_locator import inset_axes -fig = plt.figure(1, [6, 3]) - -# first subplot -ax1 = fig.add_subplot(121) +fig, (ax1, ax2) = plt.subplots(1, 2, figsize=[6, 3]) axins1 = inset_axes(ax1, width="50%", # width = 10% of parent_bbox width @@ -16,15 +13,12 @@ plt.colorbar(im1, cax=axins1, orientation="horizontal", ticks=[1,2,3]) axins1.xaxis.set_ticks_position("bottom") -# first subplot -ax = fig.add_subplot(122) - -axins = inset_axes(ax, +axins = inset_axes(ax2, width="5%", # width = 10% of parent_bbox width height="50%", # height : 50% loc=3, bbox_to_anchor=(1.05, 0., 1, 1), - bbox_transform=ax.transAxes, + bbox_transform=ax2.transAxes, borderpad=0, ) @@ -32,7 +26,7 @@ # of the legend. you may want to play with the borderpad value and # the bbox_to_anchor coordinate. -im=ax.imshow([[1,2],[2, 3]]) +im=ax2.imshow([[1,2],[2, 3]]) plt.colorbar(im, cax=axins, ticks=[1,2,3]) plt.draw() diff --git a/examples/axes_grid/inset_locator_demo.py b/examples/axes_grid/inset_locator_demo.py index 9dfe0024feb7..78c97da089d5 100644 --- a/examples/axes_grid/inset_locator_demo.py +++ b/examples/axes_grid/inset_locator_demo.py @@ -14,10 +14,9 @@ def add_sizebar(ax, size): ax.add_artist(asb) -fig = plt.figure(1, [5.5, 3]) +fig, (ax,ax2) = plt.subplots(1,2, figsize=[5.5, 3]) # first subplot -ax = fig.add_subplot(1,2,1) ax.set_aspect(1.) axins = inset_axes(ax, @@ -30,15 +29,14 @@ def add_sizebar(ax, size): # second subplot -ax = fig.add_subplot(1,2,2) -ax.set_aspect(1.) +ax2.set_aspect(1.) -axins = zoomed_inset_axes(ax, 0.5, loc=1) # zoom = 0.5 +axins = zoomed_inset_axes(ax2, 0.5, loc=1) # zoom = 0.5 plt.xticks(visible=False) plt.yticks(visible=False) -add_sizebar(ax, 0.5) +add_sizebar(ax2, 0.5) add_sizebar(axins, 0.5) plt.draw() diff --git a/examples/axes_grid/inset_locator_demo2.py b/examples/axes_grid/inset_locator_demo2.py index a4e08be34931..211faa4bffd8 100644 --- a/examples/axes_grid/inset_locator_demo2.py +++ b/examples/axes_grid/inset_locator_demo2.py @@ -13,9 +13,7 @@ def get_demo_image(): # z is a numpy array of 15x15 return z, (-3,4,-4,3) - -fig = plt.figure(1, [5,4]) -ax = fig.add_subplot(111) +fig, ax = plt.subplots(figsize=[5,4]) # prepare the demo image Z, extent = get_demo_image() diff --git a/examples/axes_grid/scatter_hist.py b/examples/axes_grid/scatter_hist.py index b846704e0e71..273ae5d9348c 100644 --- a/examples/axes_grid/scatter_hist.py +++ b/examples/axes_grid/scatter_hist.py @@ -1,17 +1,15 @@ import numpy as np import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid1 import make_axes_locatable # the random data x = np.random.randn(1000) y = np.random.randn(1000) -fig = plt.figure(1, figsize=(5.5,5.5)) - -from mpl_toolkits.axes_grid1 import make_axes_locatable +fig, axScatter = plt.subplots(figsize=(5.5,5.5)) # the scatter plot: -axScatter = plt.subplot(111) axScatter.scatter(x, y) axScatter.set_aspect(1.) diff --git a/examples/event_handling/data_browser.py b/examples/event_handling/data_browser.py index 7e11c3fade42..d4c9692552ee 100644 --- a/examples/event_handling/data_browser.py +++ b/examples/event_handling/data_browser.py @@ -70,11 +70,9 @@ def update(self): xs = np.mean(X, axis=1) ys = np.std(X, axis=1) - fig = plt.figure() - ax = fig.add_subplot(211) + fig, (ax, ax2) = plt.subplots(2, 1) ax.set_title('click on point to plot time series') line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance - ax2 = fig.add_subplot(212) browser = PointBrowser() diff --git a/examples/event_handling/figure_axes_enter_leave.py b/examples/event_handling/figure_axes_enter_leave.py index 7b9175ff3860..af6de53e8e60 100644 --- a/examples/event_handling/figure_axes_enter_leave.py +++ b/examples/event_handling/figure_axes_enter_leave.py @@ -25,20 +25,16 @@ def leave_figure(event): event.canvas.figure.patch.set_facecolor('grey') event.canvas.draw() -fig1 = plt.figure() +fig1, (ax, ax2) = plt.subplots(2, 1) fig1.suptitle('mouse hover over figure or axes to trigger events') -ax1 = fig1.add_subplot(211) -ax2 = fig1.add_subplot(212) fig1.canvas.mpl_connect('figure_enter_event', enter_figure) fig1.canvas.mpl_connect('figure_leave_event', leave_figure) fig1.canvas.mpl_connect('axes_enter_event', enter_axes) fig1.canvas.mpl_connect('axes_leave_event', leave_axes) -fig2 = plt.figure() +fig2, (ax, ax2) = plt.subplots(2, 1) fig2.suptitle('mouse hover over figure or axes to trigger events') -ax1 = fig2.add_subplot(211) -ax2 = fig2.add_subplot(212) fig2.canvas.mpl_connect('figure_enter_event', enter_figure) fig2.canvas.mpl_connect('figure_leave_event', leave_figure) diff --git a/examples/event_handling/idle_and_timeout.py b/examples/event_handling/idle_and_timeout.py index 6dbff324a390..a6de8195f10e 100644 --- a/examples/event_handling/idle_and_timeout.py +++ b/examples/event_handling/idle_and_timeout.py @@ -7,8 +7,7 @@ import numpy as np import matplotlib.pyplot as plt -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() t = np.arange(0.0, 2.0, 0.01) y1 = np.sin(2*np.pi*t) diff --git a/examples/event_handling/keypress_demo.py b/examples/event_handling/keypress_demo.py index 501798f84d2a..ae490939d0ba 100755 --- a/examples/event_handling/keypress_demo.py +++ b/examples/event_handling/keypress_demo.py @@ -15,8 +15,7 @@ def press(event): xl.set_visible(not visible) fig.canvas.draw() -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() fig.canvas.mpl_connect('key_press_event', press) diff --git a/examples/event_handling/legend_picking.py b/examples/event_handling/legend_picking.py index 4505b09bd971..1c37ad3c6e85 100644 --- a/examples/event_handling/legend_picking.py +++ b/examples/event_handling/legend_picking.py @@ -8,8 +8,7 @@ y1 = 2*np.sin(2*np.pi*t) y2 = 4*np.sin(2*np.pi*2*t) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.set_title('Click on legend line to toggle line on/off') line1, = ax.plot(t, y1, lw=2, color='red', label='1 HZ') line2, = ax.plot(t, y2, lw=2, color='blue', label='2 HZ') diff --git a/examples/event_handling/looking_glass.py b/examples/event_handling/looking_glass.py index 3ceeb68f8231..eb98998d0832 100644 --- a/examples/event_handling/looking_glass.py +++ b/examples/event_handling/looking_glass.py @@ -3,8 +3,7 @@ import matplotlib.patches as patches x, y = np.random.rand(2, 200) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() circ = patches.Circle( (0.5, 0.5), 0.25, alpha=0.8, fc='yellow') ax.add_patch(circ) diff --git a/examples/event_handling/path_editor.py b/examples/event_handling/path_editor.py index 38148c78dffc..7fb82dff50a2 100644 --- a/examples/event_handling/path_editor.py +++ b/examples/event_handling/path_editor.py @@ -5,8 +5,7 @@ Path = mpath.Path -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() pathdata = [ (Path.MOVETO, (1.58, -2.57)), diff --git a/examples/event_handling/pick_event_demo.py b/examples/event_handling/pick_event_demo.py index 68a27e4c221a..57bfa0b6b10b 100755 --- a/examples/event_handling/pick_event_demo.py +++ b/examples/event_handling/pick_event_demo.py @@ -65,7 +65,7 @@ def pick_handler(event): """ from __future__ import print_function -from matplotlib.pyplot import figure, show +import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Rectangle from matplotlib.text import Text @@ -74,15 +74,12 @@ def pick_handler(event): from numpy.random import rand if 1: # simple picking, lines, rectangles and text - fig = figure() - ax1 = fig.add_subplot(211) + fig, (ax1, ax2) = plt.subplots(2,1) ax1.set_title('click on points, rectangles or text', picker=True) ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red')) line, = ax1.plot(rand(100), 'o', picker=5) # 5 points tolerance # pick the rectangle - ax2 = fig.add_subplot(212) - bars = ax2.bar(range(10), rand(10), picker=True) for label in ax2.get_xticklabels(): # make the xtick labels pickable label.set_picker(True) @@ -140,10 +137,9 @@ def line_picker(line, mouseevent): def onpick2(event): print('onpick2 line:', event.pickx, event.picky) - fig = figure() - ax1 = fig.add_subplot(111) - ax1.set_title('custom picker for line data') - line, = ax1.plot(rand(100), rand(100), 'o', picker=line_picker) + fig, ax = plt.subplots() + ax.set_title('custom picker for line data') + line, = ax.plot(rand(100), rand(100), 'o', picker=line_picker) fig.canvas.mpl_connect('pick_event', onpick2) @@ -154,20 +150,18 @@ def onpick3(event): ind = event.ind print('onpick3 scatter:', ind, np.take(x, ind), np.take(y, ind)) - fig = figure() - ax1 = fig.add_subplot(111) - col = ax1.scatter(x, y, 100*s, c, picker=True) + fig, ax = plt.subplots() + col = ax.scatter(x, y, 100*s, c, picker=True) #fig.savefig('pscoll.eps') fig.canvas.mpl_connect('pick_event', onpick3) if 1: # picking images (matplotlib.image.AxesImage) - fig = figure() - ax1 = fig.add_subplot(111) - im1 = ax1.imshow(rand(10,5), extent=(1,2,1,2), picker=True) - im2 = ax1.imshow(rand(5,10), extent=(3,4,1,2), picker=True) - im3 = ax1.imshow(rand(20,25), extent=(1,2,3,4), picker=True) - im4 = ax1.imshow(rand(30,12), extent=(3,4,3,4), picker=True) - ax1.axis([0,5,0,5]) + fig, ax = plt.subplots() + im1 = ax.imshow(rand(10,5), extent=(1,2,1,2), picker=True) + im2 = ax.imshow(rand(5,10), extent=(3,4,1,2), picker=True) + im3 = ax.imshow(rand(20,25), extent=(1,2,3,4), picker=True) + im4 = ax.imshow(rand(30,12), extent=(3,4,3,4), picker=True) + ax.axis([0,5,0,5]) def onpick4(event): artist = event.artist @@ -179,5 +173,5 @@ def onpick4(event): fig.canvas.mpl_connect('pick_event', onpick4) -show() +plt.show() diff --git a/examples/event_handling/pick_event_demo2.py b/examples/event_handling/pick_event_demo2.py index 0f4513309be8..3d2a18e685a0 100644 --- a/examples/event_handling/pick_event_demo2.py +++ b/examples/event_handling/pick_event_demo2.py @@ -11,8 +11,7 @@ xs = numpy.mean(X, axis=1) ys = numpy.std(X, axis=1) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.set_title('click on point to plot time series') line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance diff --git a/examples/event_handling/poly_editor.py b/examples/event_handling/poly_editor.py index c7d96df66d51..191740cd242d 100644 --- a/examples/event_handling/poly_editor.py +++ b/examples/event_handling/poly_editor.py @@ -145,7 +145,6 @@ def motion_notify_callback(self, event): import matplotlib.pyplot as plt from matplotlib.patches import Polygon - fig = plt.figure() theta = np.arange(0, 2*np.pi, 0.1) r = 1.5 @@ -154,7 +153,7 @@ def motion_notify_callback(self, event): poly = Polygon(list(zip(xs, ys)), animated=True) - ax = plt.subplot(111) + fig, ax = plt.subplots() ax.add_patch(poly) p = PolygonInteractor(ax, poly) diff --git a/examples/event_handling/pong_gtk.py b/examples/event_handling/pong_gtk.py index fb8479f6301a..24469a123dfc 100755 --- a/examples/event_handling/pong_gtk.py +++ b/examples/event_handling/pong_gtk.py @@ -16,8 +16,7 @@ import pipong -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() canvas = ax.figure.canvas diff --git a/examples/event_handling/pong_qt.py b/examples/event_handling/pong_qt.py index d27b6c1101e7..801564844c60 100644 --- a/examples/event_handling/pong_qt.py +++ b/examples/event_handling/pong_qt.py @@ -23,7 +23,7 @@ class BlitQT(QObject): def __init__(self): QObject.__init__(self, None, "app") - self.ax = plt.subplot(111) + _, self.ax = plt.subplots() self.animation = pipong.Game(self.ax) def timerEvent(self, evt): diff --git a/examples/event_handling/resample.py b/examples/event_handling/resample.py index a9df778cd3e4..76c9514d3a76 100644 --- a/examples/event_handling/resample.py +++ b/examples/event_handling/resample.py @@ -39,8 +39,7 @@ def update(self, ax): d = DataDisplayDownsampler(xdata, ydata) -fig = plt.figure() -ax = fig.add_subplot(1, 1, 1) +fig, ax = plt.subplots() #Hook up the line xdata, ydata = d.downsample(xdata[0], xdata[-1]) diff --git a/examples/event_handling/timers.py b/examples/event_handling/timers.py index 2541f11aae3e..0e293a84975c 100644 --- a/examples/event_handling/timers.py +++ b/examples/event_handling/timers.py @@ -8,8 +8,7 @@ def update_title(axes): axes.set_title(datetime.now()) axes.figure.canvas.draw() -fig = plt.figure() -ax = fig.add_subplot(1, 1, 1) +fig, ax = plt.subplots() x = np.linspace(-3, 3) ax.plot(x, x*x) diff --git a/examples/event_handling/viewlims.py b/examples/event_handling/viewlims.py index fe5838cbc6c6..be2565366af5 100644 --- a/examples/event_handling/viewlims.py +++ b/examples/event_handling/viewlims.py @@ -58,11 +58,8 @@ def ax_update(self, ax): md = MandlebrotDisplay() Z = md(-2., 0.5, -1.25, 1.25) -fig = plt.figure() -ax1 = fig.add_subplot(1, 2, 1) +fig1, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(Z, origin='lower', extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max())) - -ax2 = fig.add_subplot(1, 2, 2) ax2.imshow(Z, origin='lower', extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max())) rect = UpdatingRect([0, 0], 0, 0, facecolor='None', edgecolor='black') diff --git a/examples/misc/longshort.py b/examples/misc/longshort.py index 06b0302b80d0..9cb2a2a50890 100644 --- a/examples/misc/longshort.py +++ b/examples/misc/longshort.py @@ -38,8 +38,7 @@ tr = (1+g).cumprod() # the total return # plot the return -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(r.date, tr) ax.set_title('total return: long APPL, short GOOG') ax.grid() diff --git a/examples/misc/multiprocess.py b/examples/misc/multiprocess.py index 09aa4ed94462..1d2b12b30476 100644 --- a/examples/misc/multiprocess.py +++ b/examples/misc/multiprocess.py @@ -53,9 +53,7 @@ def __call__(self, pipe): print('starting plotter...') self.pipe = pipe - self.fig = plt.figure() - - self.ax = self.fig.add_subplot(111) + self.fig, self.ax = plt.subplots() self.gid = gobject.timeout_add(1000, self.poll_draw()) print('...done') diff --git a/examples/misc/rasterization_demo.py b/examples/misc/rasterization_demo.py index a03daaac9278..067099c56a28 100644 --- a/examples/misc/rasterization_demo.py +++ b/examples/misc/rasterization_demo.py @@ -8,19 +8,17 @@ xx = x*np.cos(theta) - y*np.sin(theta) yy = x*np.sin(theta) + y*np.cos(theta) -ax1 = plt.subplot(221) +fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) ax1.set_aspect(1) ax1.pcolormesh(xx, yy, d) ax1.set_title("No Rasterization") -ax2 = plt.subplot(222) ax2.set_aspect(1) ax2.set_title("Rasterization") m = ax2.pcolormesh(xx, yy, d) m.set_rasterized(True) -ax3 = plt.subplot(223) ax3.set_aspect(1) ax3.pcolormesh(xx, yy, d) ax3.text(0.5, 0.5, "Text", alpha=0.2, @@ -29,7 +27,6 @@ ax3.set_title("No Rasterization") -ax4 = plt.subplot(224) ax4.set_aspect(1) m = ax4.pcolormesh(xx, yy, d) m.set_zorder(-20) diff --git a/examples/pylab_examples/agg_buffer_to_array.py b/examples/pylab_examples/agg_buffer_to_array.py index 9167ac8b70ea..eace74be4572 100644 --- a/examples/pylab_examples/agg_buffer_to_array.py +++ b/examples/pylab_examples/agg_buffer_to_array.py @@ -3,8 +3,7 @@ import numpy as np # make an agg figure -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot([1,2,3]) ax.set_title('a simple figure') fig.canvas.draw() diff --git a/examples/pylab_examples/annotation_demo3.py b/examples/pylab_examples/annotation_demo3.py index cf78da77cdbb..31261ae66bb6 100644 --- a/examples/pylab_examples/annotation_demo3.py +++ b/examples/pylab_examples/annotation_demo3.py @@ -1,10 +1,6 @@ import matplotlib.pyplot as plt -fig = plt.figure(1) -fig.clf() - -ax1 = plt.subplot(121) -ax2 = plt.subplot(122) +fig, (ax1, ax2) = plt.subplots(1, 2) bbox_args = dict(boxstyle="round", fc="0.8") arrow_args = dict(arrowstyle="->") diff --git a/examples/pylab_examples/aspect_loglog.py b/examples/pylab_examples/aspect_loglog.py index 4ce384633e91..db22322d8be6 100644 --- a/examples/pylab_examples/aspect_loglog.py +++ b/examples/pylab_examples/aspect_loglog.py @@ -1,6 +1,6 @@ import matplotlib.pyplot as plt -ax1 = plt.subplot(121) +fig, (ax1, ax2) = plt.subplots(1, 2) ax1.set_xscale("log") ax1.set_yscale("log") ax1.set_xlim(1e1, 1e3) @@ -8,7 +8,6 @@ ax1.set_aspect(1) ax1.set_title("adjustable = box") -ax2 = plt.subplot(122) ax2.set_xscale("log") ax2.set_yscale("log") ax2.set_adjustable("datalim") diff --git a/examples/pylab_examples/axes_props.py b/examples/pylab_examples/axes_props.py index 7fe564ef7d49..6f1324b5ad53 100644 --- a/examples/pylab_examples/axes_props.py +++ b/examples/pylab_examples/axes_props.py @@ -36,7 +36,7 @@ t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) -ax = subplot(111) +fig, ax = plt.subplots() ax.plot(t, s) ax.grid(True) diff --git a/examples/pylab_examples/barchart_demo.py b/examples/pylab_examples/barchart_demo.py index e5f86cf4d2c5..e56ba957608a 100644 --- a/examples/pylab_examples/barchart_demo.py +++ b/examples/pylab_examples/barchart_demo.py @@ -11,7 +11,7 @@ width = 0.35 # the width of the bars -plt.subplot(111) +fig, ax = plt.subplots() rects1 = plt.bar(ind, menMeans, width, color='r', yerr=menStd, diff --git a/examples/pylab_examples/barchart_demo2.py b/examples/pylab_examples/barchart_demo2.py index 53ffdc419688..d2c82709f926 100644 --- a/examples/pylab_examples/barchart_demo2.py +++ b/examples/pylab_examples/barchart_demo2.py @@ -28,8 +28,8 @@ scores = ['7', '48', '12:52', '17', '14'] rankings = np.round(np.random.uniform(0, 1, numTests)*100, 0) -fig = plt.figure(figsize=(9,7)) -ax1 = fig.add_subplot(111) + +fig, ax1 = plt.subplots(figsize=(9,7)) plt.subplots_adjust(left=0.115, right=0.88) fig.canvas.set_window_title('Eldorado K-8 Fitness Chart') pos = np.arange(numTests)+0.5 #Center bars on the Y-axis ticks diff --git a/examples/pylab_examples/boxplot_demo2.py b/examples/pylab_examples/boxplot_demo2.py index 6f4c9ad3e878..5a5b8a4e1c27 100644 --- a/examples/pylab_examples/boxplot_demo2.py +++ b/examples/pylab_examples/boxplot_demo2.py @@ -34,9 +34,8 @@ data = [norm, normBoot, logn, lognBoot, expo, expoBoot, gumb, gumbBoot, tria, triaBoot] -fig = plt.figure(figsize=(10,6)) +fig, ax1 = plt.subplots(figsize=(10,6)) fig.canvas.set_window_title('A Boxplot Example') -ax1 = fig.add_subplot(111) plt.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25) bp = plt.boxplot(data, notch=0, sym='+', vert=1, whis=1.5) diff --git a/examples/pylab_examples/boxplot_demo3.py b/examples/pylab_examples/boxplot_demo3.py index fe7e5b77a3d5..42e39d8007df 100644 --- a/examples/pylab_examples/boxplot_demo3.py +++ b/examples/pylab_examples/boxplot_demo3.py @@ -34,8 +34,7 @@ def fakeBootStrapper(n): medians = [None, None, med1, med2] conf_intervals = [None, None, CI1, CI2] -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() pos = np.array(range(len(treatments)))+1 bp = ax.boxplot(treatments, sym='k+', positions=pos, notch=1, bootstrap=5000, diff --git a/examples/pylab_examples/broken_barh.py b/examples/pylab_examples/broken_barh.py index 3d427e61f618..9d8085f52252 100644 --- a/examples/pylab_examples/broken_barh.py +++ b/examples/pylab_examples/broken_barh.py @@ -3,8 +3,7 @@ """ import matplotlib.pyplot as plt -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.broken_barh([ (110, 30), (150, 10) ] , (10, 9), facecolors='blue') ax.broken_barh([ (10, 50), (100, 20), (130, 10)] , (20, 9), facecolors=('red', 'yellow', 'green')) diff --git a/examples/pylab_examples/centered_ticklabels.py b/examples/pylab_examples/centered_ticklabels.py index b6e40deb50fd..2063a3ea665f 100644 --- a/examples/pylab_examples/centered_ticklabels.py +++ b/examples/pylab_examples/centered_ticklabels.py @@ -25,8 +25,7 @@ r = np.load(fh); fh.close() r = r[-250:] # get the last 250 days -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(r.date, r.adj_close) ax.xaxis.set_major_locator(dates.MonthLocator()) diff --git a/examples/pylab_examples/colorbar_tick_labelling_demo.py b/examples/pylab_examples/colorbar_tick_labelling_demo.py index 63c84232a04e..1a368da458f2 100644 --- a/examples/pylab_examples/colorbar_tick_labelling_demo.py +++ b/examples/pylab_examples/colorbar_tick_labelling_demo.py @@ -9,8 +9,7 @@ from numpy.random import randn # Make plot with vertical (default) colorbar -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() data = np.clip(randn(250, 250), -1, 1) @@ -22,8 +21,7 @@ cbar.ax.set_yticklabels(['< -1', '0', '> 1'])# vertically oriented colorbar # Make plot with horizontal colorbar -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() data = np.clip(randn(250, 250), -1, 1) diff --git a/examples/pylab_examples/coords_demo.py b/examples/pylab_examples/coords_demo.py index 9f6cdcb87000..fb92f73943e0 100755 --- a/examples/pylab_examples/coords_demo.py +++ b/examples/pylab_examples/coords_demo.py @@ -10,7 +10,7 @@ t = arange(0.0, 1.0, 0.01) s = sin(2*pi*t) -ax = subplot(111) +fig, ax = plt.subplots() ax.plot(t,s) diff --git a/examples/pylab_examples/coords_report.py b/examples/pylab_examples/coords_report.py index 9710e887b82f..f2fc9a40d266 100644 --- a/examples/pylab_examples/coords_report.py +++ b/examples/pylab_examples/coords_report.py @@ -10,7 +10,7 @@ def millions(x): x = rand(20) y = 1e7*rand(20) -ax = subplot(111) +fig, ax = plt.subplots() ax.fmt_ydata = millions plot(x, y, 'o') diff --git a/examples/pylab_examples/cursor_demo.py b/examples/pylab_examples/cursor_demo.py index e98854f02c37..02dc69284e25 100755 --- a/examples/pylab_examples/cursor_demo.py +++ b/examples/pylab_examples/cursor_demo.py @@ -68,7 +68,7 @@ def mouse_move(self, event): t = arange(0.0, 1.0, 0.01) s = sin(2*2*pi*t) -ax = subplot(111) +fig, ax = plt.subplots() cursor = Cursor(ax) #cursor = SnaptoCursor(ax, t, s) diff --git a/examples/pylab_examples/custom_ticker1.py b/examples/pylab_examples/custom_ticker1.py index 8dc453f7acad..364b12c96c71 100755 --- a/examples/pylab_examples/custom_ticker1.py +++ b/examples/pylab_examples/custom_ticker1.py @@ -22,7 +22,7 @@ def millions(x, pos): formatter = FuncFormatter(millions) -ax = subplot(111) +fig, ax = plt.subplots() ax.yaxis.set_major_formatter(formatter) bar(x, money) xticks( x + 0.5, ('Bill', 'Fred', 'Mary', 'Sue') ) diff --git a/examples/pylab_examples/dashpointlabel.py b/examples/pylab_examples/dashpointlabel.py index fe5149d5f878..248de6f82b43 100644 --- a/examples/pylab_examples/dashpointlabel.py +++ b/examples/pylab_examples/dashpointlabel.py @@ -15,9 +15,7 @@ (1, 20, 30, 60, 10), ) -fig = pylab.figure() -ax = fig.add_subplot(111) - +fig, ax = plt.subplots() (x,y) = zip(*DATA) ax.plot(x, y, marker='o') diff --git a/examples/pylab_examples/date_demo1.py b/examples/pylab_examples/date_demo1.py index bc5370bef52c..1a26d66fd6d3 100644 --- a/examples/pylab_examples/date_demo1.py +++ b/examples/pylab_examples/date_demo1.py @@ -33,8 +33,7 @@ dates = [q[0] for q in quotes] opens = [q[1] for q in quotes] -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot_date(dates, opens, '-') # format the ticks diff --git a/examples/pylab_examples/date_demo2.py b/examples/pylab_examples/date_demo2.py index 6fa276cf233c..8fc86e90ce8c 100755 --- a/examples/pylab_examples/date_demo2.py +++ b/examples/pylab_examples/date_demo2.py @@ -32,8 +32,7 @@ dates = [q[0] for q in quotes] opens = [q[1] for q in quotes] -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot_date(dates, opens, '-') ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) diff --git a/examples/pylab_examples/date_demo_convert.py b/examples/pylab_examples/date_demo_convert.py index d2ad0d096146..36af442ed1ac 100644 --- a/examples/pylab_examples/date_demo_convert.py +++ b/examples/pylab_examples/date_demo_convert.py @@ -12,8 +12,7 @@ y = arange( len(dates)*1.0) -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot_date(dates, y*y) # this is superfluous, since the autoscaler should get it right, but diff --git a/examples/pylab_examples/date_demo_rrule.py b/examples/pylab_examples/date_demo_rrule.py index d0df79caec30..c27106deff4f 100644 --- a/examples/pylab_examples/date_demo_rrule.py +++ b/examples/pylab_examples/date_demo_rrule.py @@ -21,7 +21,7 @@ s = rand(len(dates)) # make up some random y values -ax = subplot(111) +fig, ax = plt.subplots() plot_date(dates, s) ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) diff --git a/examples/pylab_examples/date_index_formatter.py b/examples/pylab_examples/date_index_formatter.py index 9b1144544283..6df72b8ef93c 100644 --- a/examples/pylab_examples/date_index_formatter.py +++ b/examples/pylab_examples/date_index_formatter.py @@ -33,8 +33,7 @@ def __call__(self, x, pos=0): formatter = MyFormatter(r.date) -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.xaxis.set_major_formatter(formatter) ax.plot(numpy.arange(len(r)), r.close, 'o-') fig.autofmt_xdate() diff --git a/examples/pylab_examples/demo_annotation_box.py b/examples/pylab_examples/demo_annotation_box.py index ea82bb53b138..46c46ed21532 100644 --- a/examples/pylab_examples/demo_annotation_box.py +++ b/examples/pylab_examples/demo_annotation_box.py @@ -6,9 +6,7 @@ import numpy as np if 1: - fig = plt.gcf() - fig.clf() - ax = plt.subplot(111) + fig, ax = plt.subplots() offsetbox = TextArea("Test 1", minimumdescent=False) diff --git a/examples/pylab_examples/demo_ribbon_box.py b/examples/pylab_examples/demo_ribbon_box.py index 9ab0be183ec1..617c731588ab 100644 --- a/examples/pylab_examples/demo_ribbon_box.py +++ b/examples/pylab_examples/demo_ribbon_box.py @@ -96,9 +96,7 @@ def draw(self, renderer, *args, **kwargs): from matplotlib.transforms import Bbox, TransformedBbox from matplotlib.ticker import ScalarFormatter - fig = plt.gcf() - fig.clf() - ax = plt.subplot(111) + fig, ax = plt.subplots() years = np.arange(2004, 2009) box_colors = [(0.8, 0.2, 0.2), diff --git a/examples/pylab_examples/dolphin.py b/examples/pylab_examples/dolphin.py index f457ccc0c796..e02fa41200a7 100644 --- a/examples/pylab_examples/dolphin.py +++ b/examples/pylab_examples/dolphin.py @@ -11,8 +11,7 @@ x = r * np.cos(t) y = r * np.sin(t) -fig = plt.figure(figsize=(6,6)) -ax = plt.subplot(111) +fig, ax = plt.subplots(figsize=(6,6)) circle = Circle((0, 0), 1, facecolor='none', edgecolor=(0,0.8,0.8), linewidth=3, alpha=0.5) ax.add_patch(circle) diff --git a/examples/pylab_examples/ellipse_collection.py b/examples/pylab_examples/ellipse_collection.py index bc228db77e89..a6a06a5f4054 100644 --- a/examples/pylab_examples/ellipse_collection.py +++ b/examples/pylab_examples/ellipse_collection.py @@ -13,7 +13,7 @@ aa = X*9 -ax = plt.subplot(1,1,1) +fig, ax = plt.subplots() ec = EllipseCollection( ww, diff --git a/examples/pylab_examples/fill_between_demo.py b/examples/pylab_examples/fill_between_demo.py index 1dd2dc2ea36d..921f93677659 100644 --- a/examples/pylab_examples/fill_between_demo.py +++ b/examples/pylab_examples/fill_between_demo.py @@ -47,8 +47,7 @@ # arrays to a very fine grid before plotting. # show how to use transforms to create axes spans where a certain condition is satisfied -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() y = np.sin(4*np.pi*x) ax.plot(x, y, color='black') diff --git a/examples/pylab_examples/fill_demo2.py b/examples/pylab_examples/fill_demo2.py index 77b86d79017e..a6cc402f1e24 100644 --- a/examples/pylab_examples/fill_demo2.py +++ b/examples/pylab_examples/fill_demo2.py @@ -1,10 +1,9 @@ -from matplotlib.pyplot import figure, show +import matplotlib.pyplot as plt from numpy import arange, sin, pi -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() t = arange(0.0,3.01,0.01) s = sin(2*pi*t) c = sin(4*pi*t) ax.fill(t, s, 'b', t, c, 'g', alpha=0.2) -show() +plt.show() diff --git a/examples/pylab_examples/finance_demo.py b/examples/pylab_examples/finance_demo.py index 81aac7a2bd9d..6ce070ffbec6 100644 --- a/examples/pylab_examples/finance_demo.py +++ b/examples/pylab_examples/finance_demo.py @@ -19,9 +19,8 @@ if len(quotes) == 0: raise SystemExit -fig = figure() +fig, ax = subplots() fig.subplots_adjust(bottom=0.2) -ax = fig.add_subplot(111) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) diff --git a/examples/pylab_examples/findobj_demo.py b/examples/pylab_examples/findobj_demo.py index 73e61f783bd3..0fd96f1dd824 100644 --- a/examples/pylab_examples/findobj_demo.py +++ b/examples/pylab_examples/findobj_demo.py @@ -10,8 +10,7 @@ c = np.exp(a) d = c[::-1] -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() 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) diff --git a/examples/pylab_examples/hist_colormapped.py b/examples/pylab_examples/hist_colormapped.py index cce35e889fdc..7c4451584206 100644 --- a/examples/pylab_examples/hist_colormapped.py +++ b/examples/pylab_examples/hist_colormapped.py @@ -3,8 +3,7 @@ import matplotlib.cm as cm import matplotlib.colors as colors -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() Ntotal = 1000 N, bins, patches = ax.hist(n.random.rand(Ntotal), 20) diff --git a/examples/pylab_examples/integral_demo.py b/examples/pylab_examples/integral_demo.py index 436482ce189a..950cccae2cb1 100644 --- a/examples/pylab_examples/integral_demo.py +++ b/examples/pylab_examples/integral_demo.py @@ -7,7 +7,7 @@ def func(x): return (x-3)*(x-5)*(x-7)+85 -ax = subplot(111) +fig, ax = plt.subplots() a, b = 2, 9 # integral area x = arange(0, 10, 0.01) diff --git a/examples/pylab_examples/interp_demo.py b/examples/pylab_examples/interp_demo.py index 0f7375475d18..911781f07d3d 100644 --- a/examples/pylab_examples/interp_demo.py +++ b/examples/pylab_examples/interp_demo.py @@ -1,4 +1,4 @@ -from matplotlib.pyplot import figure, show +import matplotlib.pyplot as plt from numpy import pi, sin, linspace from matplotlib.mlab import stineman_interp @@ -7,8 +7,7 @@ xi = linspace(x[0],x[-1],100); yi = stineman_interp(xi,x,y,yp); -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(x,y,'ro',xi,yi,'-b.') -show() +plt.show() diff --git a/examples/pylab_examples/legend_demo.py b/examples/pylab_examples/legend_demo.py index 5151dfe203a0..944b48c80d4f 100644 --- a/examples/pylab_examples/legend_demo.py +++ b/examples/pylab_examples/legend_demo.py @@ -12,7 +12,7 @@ c = np.exp(a) d = c[::-1] -ax = plt.subplot(111) +fig, ax = plt.subplots() 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) diff --git a/examples/pylab_examples/major_minor_demo1.py b/examples/pylab_examples/major_minor_demo1.py index 81090b065d7a..09c9e25f5a6a 100644 --- a/examples/pylab_examples/major_minor_demo1.py +++ b/examples/pylab_examples/major_minor_demo1.py @@ -41,7 +41,7 @@ t = arange(0.0, 100.0, 0.1) s = sin(0.1*pi*t)*exp(-t*0.01) -ax = subplot(111) +fig, ax = plt.subplots() plot(t,s) ax.xaxis.set_major_locator(majorLocator) diff --git a/examples/pylab_examples/major_minor_demo2.py b/examples/pylab_examples/major_minor_demo2.py index eaeed688ac86..bb0a2633faca 100644 --- a/examples/pylab_examples/major_minor_demo2.py +++ b/examples/pylab_examples/major_minor_demo2.py @@ -22,7 +22,7 @@ t = np.arange(0.0, 100.0, 0.01) s = np.sin(2*np.pi*t)*np.exp(-t*0.01) -ax = plt.subplot(111) +fig, ax = plt.subplots() plt.plot(t,s) ax.xaxis.set_minor_locator(minorLocator) diff --git a/examples/pylab_examples/movie_demo.py b/examples/pylab_examples/movie_demo.py index 7748c3b53d61..9534fb3a2e96 100755 --- a/examples/pylab_examples/movie_demo.py +++ b/examples/pylab_examples/movie_demo.py @@ -3,12 +3,12 @@ from __future__ import print_function -import os, sys +import os from pylab import * files = [] -figure(figsize=(5,5)) -ax = subplot(111) + +fig, ax = plt.subplots(figsize=(5,5)) for i in range(50): # 50 frames cla() imshow(rand(5,5), interpolation='nearest') diff --git a/examples/pylab_examples/multiple_yaxis_with_spines.py b/examples/pylab_examples/multiple_yaxis_with_spines.py index a0051246b202..3b13b770feff 100644 --- a/examples/pylab_examples/multiple_yaxis_with_spines.py +++ b/examples/pylab_examples/multiple_yaxis_with_spines.py @@ -6,10 +6,9 @@ def make_patch_spines_invisible(ax): for sp in ax.spines.itervalues(): sp.set_visible(False) -fig = plt.figure() +fig, host = plt.subplots() fig.subplots_adjust(right=0.75) -host = fig.add_subplot(111) par1 = host.twinx() par2 = host.twinx() diff --git a/examples/pylab_examples/pcolor_demo2.py b/examples/pylab_examples/pcolor_demo2.py index f5ae2c9fa3ea..66af1ad6f0e4 100644 --- a/examples/pylab_examples/pcolor_demo2.py +++ b/examples/pylab_examples/pcolor_demo2.py @@ -19,7 +19,7 @@ def func3(x,y): Z = func3(X, Y) -ax = subplot(111) +fig, ax = plt.subplots() im = imshow(Z, cmap=cm.RdBu, vmax=abs(Z).max(), vmin=-abs(Z).max()) #im.set_interpolation('nearest') #im.set_interpolation('bicubic') diff --git a/examples/pylab_examples/scatter_custom_symbol.py b/examples/pylab_examples/scatter_custom_symbol.py index 602e2a97d2f9..d26499570d08 100644 --- a/examples/pylab_examples/scatter_custom_symbol.py +++ b/examples/pylab_examples/scatter_custom_symbol.py @@ -11,8 +11,7 @@ x,y,s,c = rand(4, 30) s*= 10**2. -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.scatter(x,y,s,c,marker=None,verts =verts) show() diff --git a/examples/pylab_examples/scatter_demo2.py b/examples/pylab_examples/scatter_demo2.py index 6c06adf27980..4acf0e46ffd7 100644 --- a/examples/pylab_examples/scatter_demo2.py +++ b/examples/pylab_examples/scatter_demo2.py @@ -21,8 +21,7 @@ volume = (15*r.volume[:-2]/r.volume[0])**2 close = 0.003*r.close[:-2]/0.003*r.open[:-2] -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.75) #ticks = arange(-0.06, 0.061, 0.02) diff --git a/examples/pylab_examples/stackplot_demo.py b/examples/pylab_examples/stackplot_demo.py index 0148dd8430a9..63eafc15a500 100644 --- a/examples/pylab_examples/stackplot_demo.py +++ b/examples/pylab_examples/stackplot_demo.py @@ -7,12 +7,10 @@ y1, y2, y3 = fnx(), fnx(), fnx() -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.stackplot(x, y) plt.show() -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.stackplot(x, y1, y2, y3) plt.show() diff --git a/examples/pylab_examples/stock_demo.py b/examples/pylab_examples/stock_demo.py index 6c2aec82d709..4891c9310711 100644 --- a/examples/pylab_examples/stock_demo.py +++ b/examples/pylab_examples/stock_demo.py @@ -6,7 +6,7 @@ d1, p1, d2, p2 = get_two_stock_data() -ax = subplot(111) +fig, ax = plt.subplots() lines = plot(d1, p1, 'bs', d2, p2, 'go') xlabel('Days') ylabel('Normalized price') diff --git a/examples/pylab_examples/system_monitor.py b/examples/pylab_examples/system_monitor.py index 4a20679a0e27..76b0b965f0c6 100644 --- a/examples/pylab_examples/system_monitor.py +++ b/examples/pylab_examples/system_monitor.py @@ -22,8 +22,7 @@ def get_stats(): # interactive mode, you'll need to use a GUI event handler/timer. ion() -fig = figure(1) -ax = subplot(111) +fig, ax = plt.subplots() ind = arange(1,4) pm, pc, pn = bar(ind, get_stats()) centers = ind + 0.5*pm.get_width() diff --git a/examples/pylab_examples/text_handles.py b/examples/pylab_examples/text_handles.py index bd4bb2d0b9ca..2a1a21fae8e0 100644 --- a/examples/pylab_examples/text_handles.py +++ b/examples/pylab_examples/text_handles.py @@ -17,7 +17,7 @@ def f(t): t2 = arange(0.0, 5.0, 0.02) -subplot(111) +fig, ax = plt.subplots() plot(t1, f(t1), 'bo', t2, f(t2), 'k') text(3.0, 0.6, 'f(t) = exp(-t) sin(2 pi t)') ttext = title('Fun with text!') diff --git a/examples/units/annotate_with_units.py b/examples/units/annotate_with_units.py index deb06f378295..19a99c3b2187 100644 --- a/examples/units/annotate_with_units.py +++ b/examples/units/annotate_with_units.py @@ -1,9 +1,7 @@ import matplotlib.pyplot as plt from basic_units import cm -fig = plt.figure() -ax = fig.add_subplot(111) - +fig, ax = plt.subplots() ax.annotate( "Note 01", [0.5*cm, 0.5*cm] ) diff --git a/examples/units/artist_tests.py b/examples/units/artist_tests.py index aa88496085f5..c861aaaad5ca 100644 --- a/examples/units/artist_tests.py +++ b/examples/units/artist_tests.py @@ -15,10 +15,9 @@ from basic_units import cm, inch import numpy as np -from matplotlib.pyplot import figure, show +import matplotlib.pyplot as plt -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.xaxis.set_units(cm) ax.yaxis.set_units(cm) @@ -51,5 +50,5 @@ #ax.xaxis.set_units(inch) ax.grid(True) ax.set_title("Artists with units") -show() +plt.show() diff --git a/examples/units/bar_unit_demo.py b/examples/units/bar_unit_demo.py index 9d5a1175cd46..f7f7715cde2a 100644 --- a/examples/units/bar_unit_demo.py +++ b/examples/units/bar_unit_demo.py @@ -8,8 +8,7 @@ menMeans = (150*cm, 160*cm, 146*cm, 172*cm, 155*cm) menStd = ( 20*cm, 30*cm, 32*cm, 10*cm, 20*cm) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars diff --git a/examples/user_interfaces/lineprops_dialog_gtk.py b/examples/user_interfaces/lineprops_dialog_gtk.py index f7c86b47c5df..828120249b97 100644 --- a/examples/user_interfaces/lineprops_dialog_gtk.py +++ b/examples/user_interfaces/lineprops_dialog_gtk.py @@ -14,8 +14,7 @@ def f(t): t2 = np.arange(0.0, 5.0, 0.02) t3 = np.arange(0.0, 2.0, 0.01) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() l1, = ax.plot(t1, f(t1), 'bo', label='line 1') l2, = ax.plot(t2, f(t2), 'k--', label='line 2') diff --git a/examples/user_interfaces/pylab_with_gtk.py b/examples/user_interfaces/pylab_with_gtk.py index 4aca382ffe3c..7f89334378be 100644 --- a/examples/user_interfaces/pylab_with_gtk.py +++ b/examples/user_interfaces/pylab_with_gtk.py @@ -8,7 +8,7 @@ import matplotlib.pyplot as plt -ax = plt.subplot(111) +fig, ax = plt.subplots() plt.plot([1,2,3], 'ro-', label='easy as 1 2 3') plt.plot([1,4,9], 'gs--', label='easy as 1 2 3 squared') plt.legend() diff --git a/examples/user_interfaces/svg_tooltip.py b/examples/user_interfaces/svg_tooltip.py index 15a435c1fe7f..6ec48307b4ab 100644 --- a/examples/user_interfaces/svg_tooltip.py +++ b/examples/user_interfaces/svg_tooltip.py @@ -28,8 +28,7 @@ ET.register_namespace("","http://www.w3.org/2000/svg") -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() # Create patches to which tooltips will be assigned. circle = plt.Circle((0,0), 5, fc='blue') diff --git a/examples/widgets/buttons.py b/examples/widgets/buttons.py index 6c3d68423f24..d5695e6b9436 100644 --- a/examples/widgets/buttons.py +++ b/examples/widgets/buttons.py @@ -5,7 +5,7 @@ freqs = np.arange(2, 20, 3) -ax = plt.subplot(111) +fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) t = np.arange(0.0, 1.0, 0.001) s = np.sin(2*np.pi*freqs[0]*t) diff --git a/examples/widgets/check_buttons.py b/examples/widgets/check_buttons.py index 2ef55709cf0c..843bad9abd19 100644 --- a/examples/widgets/check_buttons.py +++ b/examples/widgets/check_buttons.py @@ -7,7 +7,7 @@ s1 = np.sin(4*np.pi*t) s2 = np.sin(6*np.pi*t) -ax = plt.subplot(111) +fig, ax = plt.subplots() l0, = ax.plot(t, s0, visible=False, lw=2) l1, = ax.plot(t, s1, lw=2) l2, = ax.plot(t, s2, lw=2) diff --git a/examples/widgets/radio_buttons.py b/examples/widgets/radio_buttons.py index 8d4f32c3d03a..43c5e986b2d2 100644 --- a/examples/widgets/radio_buttons.py +++ b/examples/widgets/radio_buttons.py @@ -7,7 +7,7 @@ s1 = np.sin(4*np.pi*t) s2 = np.sin(8*np.pi*t) -ax = plt.subplot(111) +fig, ax = plt.subplots() l, = ax.plot(t, s0, lw=2, color='red') plt.subplots_adjust(left=0.3) diff --git a/examples/widgets/rectangle_selector.py b/examples/widgets/rectangle_selector.py index ed3d2eacbb5f..fa21a30d23df 100644 --- a/examples/widgets/rectangle_selector.py +++ b/examples/widgets/rectangle_selector.py @@ -29,7 +29,7 @@ def toggle_selector(event): toggle_selector.RS.set_active(True) -current_ax = plt.subplot(111) # make a new plotingrange +fig, current_ax = plt.subplots() # make a new plotingrange N = 100000 # If N is large one can see x = np.linspace(0.0, 10.0, N) # improvement by use blitting! diff --git a/examples/widgets/slider_demo.py b/examples/widgets/slider_demo.py index d3db0a027130..89e38b99a8c3 100644 --- a/examples/widgets/slider_demo.py +++ b/examples/widgets/slider_demo.py @@ -2,7 +2,7 @@ import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons -ax = plt.subplot(111) +fig, ax = plt.subplots() plt.subplots_adjust(left=0.25, bottom=0.25) t = np.arange(0.0, 1.0, 0.001) a0 = 5 diff --git a/lib/matplotlib/pylab.py b/lib/matplotlib/pylab.py index 2111d4fa734d..edad3302c8fd 100644 --- a/lib/matplotlib/pylab.py +++ b/lib/matplotlib/pylab.py @@ -83,7 +83,8 @@ specgram - a spectrogram plot spy - plot sparsity pattern using markers or image stem - make a stem plot - subplot - make a subplot (numrows, numcols, axesnum) + subplot - make one subplot (numrows, numcols, axesnum) + subplots - make a figure with a set of (numrows, numcols) subplots subplots_adjust - change the params controlling the subplot positions of current figure subplot_tool - launch the subplot configuration tool suptitle - add a figure title From 1832965ff75fb5635f7609c1721a313a0e87e2f3 Mon Sep 17 00:00:00 2001 From: Paul Ivanov Date: Thu, 8 Nov 2012 01:25:11 -0800 Subject: [PATCH 2/2] documenting the example changes in the CHANGELOG --- CHANGELOG | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 1124187a8d84..e5cb0cb506a4 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,7 @@ +2012-11-08 Replaced plt.figure and plt.subplot calls by the newer, more + convenient single call to plt.subplots() in the documentation + examples - PI + 2012-10-05 Add support for saving animations as animated GIFs. - JVDP 2012-08-11 Fix path-closing bug in patches.Polygon, so that regardless