diff --git a/CHANGELOG b/CHANGELOG index c873ade5a3ea..8d2c91c224cb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -90,6 +90,10 @@ 2012-11-09 Make plt.subplot() without arguments act as subplot(111) - PI +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 diff --git a/doc/users/whats_new.rst b/doc/users/whats_new.rst index 33f60d78a4df..7730d1d453fa 100644 --- a/doc/users/whats_new.rst +++ b/doc/users/whats_new.rst @@ -138,6 +138,14 @@ Andrew Dawson added a new keyword argument *extendrect* to :meth:`~matplotlib.pyplot.colorbar` to optionally make colorbar extensions rectangular instead of triangular. +Examples now use subplots() +--------------------------- +For the sake of brevity and clarity, most of the :ref:`examples +` now use the newer :func:`~matplotlib.pyplot.subplots`, which +creates a figure and one (or multiple) axes object(s) in one call. The old way +involved a call to :func:`~matplotlib.pyplot.figure`, followed by one (or +multiple) :func:`~matplotlib.pyplot.subplot` calls. + Calling subplot() without arguments ----------------------------------- A call to :func:`~matplotlib.pyplot.subplot` without any arguments now 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/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_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_tk.py b/examples/animation/old_animation/animation_blit_tk.py index 54e288efd621..19779aba4a15 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) -canvas = ax.figure.canvas +fig, ax = plt.subplots() +canvas = fig.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..dc7d90c75bc6 100644 --- a/examples/animation/old_animation/animation_blit_wx.py +++ b/examples/animation/old_animation/animation_blit_wx.py @@ -10,6 +10,7 @@ import matplotlib matplotlib.use('WXAgg') matplotlib.rcParams['toolbar'] = 'None' +import matplotlib.pyplot as plt import wx import sys @@ -24,8 +25,8 @@ matplotlib.backends.backend_wxagg._use_accelerator(False) -ax = p.subplot(111) -canvas = ax.figure.canvas +fig, ax = plt.subplots() +canvas = fig.canvas p.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs diff --git a/examples/animation/old_animation/draggable_legend.py b/examples/animation/old_animation/draggable_legend.py index 93895a78d046..2a6d8041b6b8 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..ff37fc48bc7d 100644 --- a/examples/animation/old_animation/histogram_tkagg.py +++ b/examples/animation/old_animation/histogram_tkagg.py @@ -2,7 +2,6 @@ This example shows how to use a path patch to draw a bunch of rectangles for an animated histogram """ -import time import numpy as np import matplotlib matplotlib.use('TkAgg') # do this before importing pylab @@ -11,8 +10,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..16541597623b 100644 --- a/examples/animation/old_animation/simple_idle_wx.py +++ b/examples/animation/old_animation/simple_idle_wx.py @@ -2,16 +2,13 @@ A simple example of an animated plot using a wx backend """ from __future__ import print_function -import time import numpy as np import matplotlib matplotlib.use('WXAgg') # do this before importing pylab 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..a427524effd6 100644 --- a/examples/animation/old_animation/simple_timer_wx.py +++ b/examples/animation/old_animation/simple_timer_wx.py @@ -2,16 +2,13 @@ """ A simple example of an animated plot using a wx backend """ -import time import numpy as np import matplotlib matplotlib.use('WXAgg') # do this before importing pylab 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..7f659afd020e 100644 --- a/examples/animation/old_animation/strip_chart_demo.py +++ b/examples/animation/old_animation/strip_chart_demo.py @@ -13,6 +13,7 @@ import matplotlib matplotlib.use('GTKAgg') import numpy as np +import matplotlib.pyplot as plt from matplotlib.lines import Line2D @@ -62,11 +63,8 @@ def update(self, *args): return True -from pylab import figure, show - -fig = figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() scope = Scope(ax) gobject.idle_add(scope.update) -show() +plt.show() 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..2ca94cf5a1ac 100644 --- a/examples/animation/strip_chart_demo.py +++ b/examples/animation/strip_chart_demo.py @@ -2,7 +2,6 @@ Emulate an oscilloscope. Requires the animation API introduced in matplotlib 1.0 SVN. """ -import matplotlib import numpy as np from matplotlib.lines import Line2D import matplotlib.pyplot as plt @@ -44,8 +43,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/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/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/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..ce3847da79f9 100644 --- a/examples/api/joinstyle.py +++ b/examples/api/joinstyle.py @@ -4,7 +4,6 @@ """ import numpy as np -import matplotlib import matplotlib.pyplot as plt def plot_angle(ax, x, y, angle, style): @@ -17,8 +16,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/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/quad_bezier.py b/examples/api/quad_bezier.py index 5314dfb936b2..07e85d479e3c 100644 --- a/examples/api/quad_bezier.py +++ b/examples/api/quad_bezier.py @@ -1,12 +1,10 @@ -import numpy as np import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt 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..9b6425070ea5 100644 --- a/examples/api/watermark_image.py +++ b/examples/api/watermark_image.py @@ -3,7 +3,6 @@ """ from __future__ import print_function import numpy as np -import matplotlib import matplotlib.cbook as cbook import matplotlib.image as image import matplotlib.pyplot as plt @@ -13,8 +12,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..1a1f5d0e3784 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 68c36c655ea5..d814c8ce334b 100755 --- a/examples/event_handling/keypress_demo.py +++ b/examples/event_handling/keypress_demo.py @@ -17,8 +17,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..a7458efdea1f 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)), @@ -72,7 +71,7 @@ def pathpatch_changed(self, pathpatch): 'this method is called whenever the pathpatchgon object is called' # only copy the artist props to the line (except visibility) vis = self.line.get_visible() - Artist.update_from(self.line, pathpatch) + plt.Artist.update_from(self.line, pathpatch) self.line.set_visible(vis) # don't use the pathpatch visibility state 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/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 a391fb2ca7cd..a52434b282ff 100644 --- a/examples/pylab_examples/agg_buffer_to_array.py +++ b/examples/pylab_examples/agg_buffer_to_array.py @@ -1,10 +1,8 @@ -import matplotlib -from pylab import figure, show +import matplotlib.pyplot as plt 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() @@ -18,7 +16,7 @@ X.shape = h,w,4 # now display the array X as an Axes in a new figure -fig2 = figure() +fig2 = plt.figure() ax2 = fig2.add_subplot(111, frameon=False) ax2.imshow(X) -show() +plt.show() 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 e71357d743e3..2cc9860d3889 100644 --- a/examples/pylab_examples/barchart_demo.py +++ b/examples/pylab_examples/barchart_demo.py @@ -7,11 +7,9 @@ n_groups = 5 -means_men = (20, 35, 30, 35, 27) -std_men = (2, 3, 4, 1, 2) - means_women = (25, 32, 34, 20, 25) std_women = (3, 5, 2, 3, 3) +fig, ax = plt.subplots() index = np.arange(n_groups) bar_width = 0.35 diff --git a/examples/pylab_examples/barchart_demo2.py b/examples/pylab_examples/barchart_demo2.py index 0886fe8fded8..54681c888ee6 100644 --- a/examples/pylab_examples/barchart_demo2.py +++ b/examples/pylab_examples/barchart_demo2.py @@ -11,7 +11,6 @@ import numpy as np import matplotlib.pyplot as plt import pylab -from matplotlib.patches import Polygon from matplotlib.ticker import MaxNLocator @@ -28,8 +27,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..98883c6f1bc8 100644 --- a/examples/pylab_examples/boxplot_demo3.py +++ b/examples/pylab_examples/boxplot_demo3.py @@ -1,5 +1,4 @@ import matplotlib.pyplot as plt -import matplotlib.transforms as mtransforms import numpy as np def fakeBootStrapper(n): @@ -34,8 +33,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..ba496dde7955 100644 --- a/examples/pylab_examples/centered_ticklabels.py +++ b/examples/pylab_examples/centered_ticklabels.py @@ -12,9 +12,7 @@ # between the major ticks. Here is an example that labels the months, # centered between the ticks -import datetime import numpy as np -import matplotlib import matplotlib.cbook as cbook import matplotlib.dates as dates import matplotlib.ticker as ticker @@ -25,8 +23,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..44e72237869a 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 = 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..834d52201ea1 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 = 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..91559a05387c 100755 --- a/examples/pylab_examples/custom_ticker1.py +++ b/examples/pylab_examples/custom_ticker1.py @@ -11,9 +11,10 @@ millions of dollars on the y axis """ from matplotlib.ticker import FuncFormatter -from pylab import * +import matplotlib.pyplot as plt +import numpy as np -x = arange(4) +x = np.arange(4) money = [1.5e5, 2.5e6, 5.5e6, 2.0e7] def millions(x, pos): @@ -22,8 +23,8 @@ 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') ) -show() +plt.bar(x, money) +plt.xticks( x + 0.5, ('Bill', 'Fred', 'Mary', 'Sue') ) +plt.show() diff --git a/examples/pylab_examples/dashpointlabel.py b/examples/pylab_examples/dashpointlabel.py index fe5149d5f878..7a1ab43bb9f8 100644 --- a/examples/pylab_examples/dashpointlabel.py +++ b/examples/pylab_examples/dashpointlabel.py @@ -1,4 +1,4 @@ -import pylab +import matplotlib.pyplot as plt DATA = ((1, 3), (2, 4), @@ -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') @@ -36,5 +34,5 @@ ax.set_xlim((0.0, 5.0)) ax.set_ylim((0.0, 5.0)) -pylab.show() +plt.show() diff --git a/examples/pylab_examples/date_demo1.py b/examples/pylab_examples/date_demo1.py index bc5370bef52c..51b852a4951e 100644 --- a/examples/pylab_examples/date_demo1.py +++ b/examples/pylab_examples/date_demo1.py @@ -14,7 +14,7 @@ yahoo finance to get the data for plotting """ -from pylab import figure, show +import matplotlib.pyplot as plt from matplotlib.finance import quotes_historical_yahoo from matplotlib.dates import YearLocator, MonthLocator, DateFormatter import datetime @@ -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 @@ -50,4 +49,4 @@ def price(x): return '$%1.2f'%x ax.grid(True) fig.autofmt_xdate() -show() +plt.show() diff --git a/examples/pylab_examples/date_demo2.py b/examples/pylab_examples/date_demo2.py index 6fa276cf233c..d6420f97674c 100755 --- a/examples/pylab_examples/date_demo2.py +++ b/examples/pylab_examples/date_demo2.py @@ -7,7 +7,7 @@ """ from __future__ import print_function import datetime -from pylab import figure, show +import matplotlib.pyplot as plt from matplotlib.dates import MONDAY from matplotlib.finance import quotes_historical_yahoo from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter @@ -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) @@ -45,4 +44,4 @@ fig.autofmt_xdate() -show() +plt.show() diff --git a/examples/pylab_examples/date_demo_convert.py b/examples/pylab_examples/date_demo_convert.py index d2ad0d096146..7ccb7c6f649d 100644 --- a/examples/pylab_examples/date_demo_convert.py +++ b/examples/pylab_examples/date_demo_convert.py @@ -1,7 +1,7 @@ #!/usr/bin/env python import datetime -from matplotlib.pyplot import figure, show +import matplotlib.pyplot as plt from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange from numpy import arange @@ -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 @@ -31,4 +30,4 @@ ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') fig.autofmt_xdate() -show() +plt.show() diff --git a/examples/pylab_examples/date_demo_rrule.py b/examples/pylab_examples/date_demo_rrule.py index d0df79caec30..c8dbef935396 100644 --- a/examples/pylab_examples/date_demo_rrule.py +++ b/examples/pylab_examples/date_demo_rrule.py @@ -5,8 +5,9 @@ See https://moin.conectiva.com.br/DateUtil for help with rrules """ -from pylab import * +import matplotlib.pyplot as plt from matplotlib.dates import YEARLY, DateFormatter, rrulewrapper, RRuleLocator, drange +import numpy as np import datetime # tick every 5th easter @@ -18,14 +19,14 @@ delta = datetime.timedelta(days=100) dates = drange(date1, date2, delta) -s = rand(len(dates)) # make up some random y values +s = np.random.rand(len(dates)) # make up some random y values -ax = subplot(111) -plot_date(dates, s) +fig, ax = plt.subplots() +plt.plot_date(dates, s) ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) labels = ax.get_xticklabels() -setp(labels, rotation=30, fontsize=10) +plt.setp(labels, rotation=30, fontsize=10) -show() +plt.show() diff --git a/examples/pylab_examples/date_index_formatter.py b/examples/pylab_examples/date_index_formatter.py index 9b1144544283..270ee2d319ca 100644 --- a/examples/pylab_examples/date_index_formatter.py +++ b/examples/pylab_examples/date_index_formatter.py @@ -11,7 +11,7 @@ from __future__ import print_function import numpy from matplotlib.mlab import csv2rec -from pylab import figure, show +import matplotlib.pyplot as plt import matplotlib.cbook as cbook from matplotlib.ticker import Formatter @@ -33,9 +33,8 @@ 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() -show() +plt.show() diff --git a/examples/pylab_examples/demo_annotation_box.py b/examples/pylab_examples/demo_annotation_box.py index ed1fd71943c4..169c52c8d8e0 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..ebf8d76bb677 100644 --- a/examples/pylab_examples/fill_between_demo.py +++ b/examples/pylab_examples/fill_between_demo.py @@ -1,16 +1,12 @@ #!/usr/bin/env python -import matplotlib.mlab as mlab -from matplotlib.pyplot import figure, show +import matplotlib.pyplot as plt import numpy as np x = np.arange(0.0, 2, 0.01) y1 = np.sin(2*np.pi*x) y2 = 1.2*np.sin(4*np.pi*x) -fig = figure() -ax1 = fig.add_subplot(311) -ax2 = fig.add_subplot(312, sharex=ax1) -ax3 = fig.add_subplot(313, sharex=ax1) +fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True) ax1.fill_between(x, 0, y1) ax1.set_ylabel('between y1 and 0') @@ -26,8 +22,7 @@ # this is different than calling # fill_between(x[where], y1[where],y2[where] # because of edge effects over multiple contiguous regions. -fig = figure() -ax = fig.add_subplot(211) +fig, (ax, ax1) = plt.subplots(2, 1, sharex=True) ax.plot(x, y1, x, y2, color='black') ax.fill_between(x, y1, y2, where=y2>=y1, facecolor='green', interpolate=True) ax.fill_between(x, y1, y2, where=y2<=y1, facecolor='red', interpolate=True) @@ -35,7 +30,6 @@ # Test support for masked arrays. y2 = np.ma.masked_greater(y2, 1.0) -ax1 = fig.add_subplot(212, sharex=ax) ax1.plot(x, y1, x, y2, color='black') ax1.fill_between(x, y1, y2, where=y2>=y1, facecolor='green', interpolate=True) ax1.fill_between(x, y1, y2, where=y2<=y1, facecolor='red', interpolate=True) @@ -47,8 +41,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') @@ -62,6 +55,4 @@ ax.fill_between(x, 0, 1, where=y<-theta, facecolor='red', alpha=0.5, transform=trans) - -show() - +plt.show() diff --git a/examples/pylab_examples/finance_demo.py b/examples/pylab_examples/finance_demo.py index c14b750f8b08..9d0318e2f234 100644 --- a/examples/pylab_examples/finance_demo.py +++ b/examples/pylab_examples/finance_demo.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from pylab import * +import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator, HourLocator, \ DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo, candlestick,\ @@ -19,9 +19,8 @@ if len(quotes) == 0: raise SystemExit -fig = figure() +fig, ax = plt.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) @@ -32,7 +31,7 @@ ax.xaxis_date() ax.autoscale_view() -setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right') +plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') -show() +plt.show() 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..6a5fb69d13ae 100644 --- a/examples/pylab_examples/hist_colormapped.py +++ b/examples/pylab_examples/hist_colormapped.py @@ -1,12 +1,11 @@ -import numpy as n -from pylab import figure, show +import numpy as np +import matplotlib.pyplot as plt 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) +N, bins, patches = ax.hist(np.random.rand(Ntotal), 20) #I'll color code by height, but you could use any scalar @@ -21,4 +20,4 @@ thispatch.set_facecolor(color) -show() +plt.show() 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 63f25a46bb26..fefc97ea7937 100644 --- a/examples/pylab_examples/legend_demo.py +++ b/examples/pylab_examples/legend_demo.py @@ -30,7 +30,7 @@ legend = ax.legend(loc='upper center', shadow=True) # The frame is matplotlib.patches.Rectangle instance surrounding the legend. -frame = legend.get_frame() +frame = legend.get_frame() frame.set_facecolor('0.90') # Set the fontsize diff --git a/examples/pylab_examples/major_minor_demo1.py b/examples/pylab_examples/major_minor_demo1.py index 81090b065d7a..ec9db4673414 100644 --- a/examples/pylab_examples/major_minor_demo1.py +++ b/examples/pylab_examples/major_minor_demo1.py @@ -30,7 +30,8 @@ """ -from pylab import * +import matplotlib.pyplot as plt +import numpy as np from matplotlib.ticker import MultipleLocator, FormatStrFormatter majorLocator = MultipleLocator(20) @@ -38,11 +39,11 @@ minorLocator = MultipleLocator(5) -t = arange(0.0, 100.0, 0.1) -s = sin(0.1*pi*t)*exp(-t*0.01) +t = np.arange(0.0, 100.0, 0.1) +s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01) -ax = subplot(111) -plot(t,s) +fig, ax = plt.subplots() +plt.plot(t,s) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) @@ -50,4 +51,4 @@ #for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) -show() +plt.show() 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..bb6ce4254f93 100755 --- a/examples/pylab_examples/movie_demo.py +++ b/examples/pylab_examples/movie_demo.py @@ -3,18 +3,19 @@ from __future__ import print_function -import os, sys -from pylab import * +import os +import matplotlib.pyplot as plt +import numpy as np 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') + plt.cla() + plt.imshow(np.random.rand(5,5), interpolation='nearest') fname = '_tmp%03d.png'%i print('Saving frame', fname) - savefig(fname) + plt.savefig(fname) files.append(fname) print('Making movie animation.mpg - this make take a while') 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/scatter_custom_symbol.py b/examples/pylab_examples/scatter_custom_symbol.py index 602e2a97d2f9..845d5194c8f4 100644 --- a/examples/pylab_examples/scatter_custom_symbol.py +++ b/examples/pylab_examples/scatter_custom_symbol.py @@ -1,5 +1,5 @@ -from matplotlib.pyplot import figure, show -from numpy import arange, pi, cos, sin, pi +import matplotlib.pyplot as plt +from numpy import arange, pi, cos, sin from numpy.random import rand # unit area ellipse @@ -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() +plt.show() diff --git a/examples/pylab_examples/scatter_demo2.py b/examples/pylab_examples/scatter_demo2.py index 6eb9e18a192f..a6ad75ffbdad 100644 --- a/examples/pylab_examples/scatter_demo2.py +++ b/examples/pylab_examples/scatter_demo2.py @@ -30,6 +30,3 @@ fig.tight_layout() plt.show() - - - 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..e95b3391ec7c 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 = 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..38a699d208db 100644 --- a/examples/units/artist_tests.py +++ b/examples/units/artist_tests.py @@ -11,14 +11,12 @@ import matplotlib.patches as patches import matplotlib.text as text import matplotlib.collections as collections -import matplotlib.units as units 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 +49,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 04c222a5673f..c75cf92681af 100644 --- a/examples/widgets/slider_demo.py +++ b/examples/widgets/slider_demo.py @@ -2,8 +2,7 @@ import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons -fig = plt.figure() -ax = fig.add_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/animation.py b/lib/matplotlib/animation.py index c1822df960e6..1d935f423920 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -253,7 +253,7 @@ def isAvailable(cls): class FileMovieWriter(MovieWriter): '`MovieWriter` subclass that handles writing to a file.' def __init__(self, *args, **kwargs): - MovieWriter.__init__(self, *args) + MovieWriter.__init__(self, *args, **kwargs) self.frame_format = rcParams['animation.frame_format'] def setup(self, fig, outfile, dpi, frame_prefix='_tmp', clear_temp=True): diff --git a/lib/matplotlib/axes.py b/lib/matplotlib/axes.py index 8b8f2587c3c1..1f93652e09dd 100644 --- a/lib/matplotlib/axes.py +++ b/lib/matplotlib/axes.py @@ -7316,13 +7316,35 @@ def imshow(self, X, cmap=None, norm=None, aspect=None, return im - def _pcolorargs(self, funcname, *args): + @staticmethod + def _pcolorargs(funcname, *args, **kw): + # This takes one kwarg, allmatch. + # If allmatch is True, then the incoming X, Y, C must + # have matching dimensions, taking into account that + # X and Y can be 1-D rather than 2-D. This perfect + # match is required for Gouroud shading. For flat + # shading, X and Y specify boundaries, so we need + # one more boundary than color in each direction. + # For convenience, and consistent with Matlab, we + # discard the last row and/or column of C if necessary + # to meet this condition. This is done if allmatch + # is False. + + allmatch = kw.pop("allmatch", False) + if len(args) == 1: C = args[0] numRows, numCols = C.shape - X, Y = np.meshgrid(np.arange(numCols + 1), np.arange(numRows + 1)) - elif len(args) == 3: + if allmatch: + X, Y = np.meshgrid(np.arange(numCols), np.arange(numRows)) + else: + X, Y = np.meshgrid(np.arange(numCols + 1), + np.arange(numRows + 1)) + return X, Y, C + + if len(args) == 3: X, Y, C = args + numRows, numCols = C.shape else: raise TypeError( 'Illegal arguments to %s; see help(%s)' % (funcname, funcname)) @@ -7339,6 +7361,17 @@ def _pcolorargs(self, funcname, *args): raise TypeError( 'Incompatible X, Y inputs to %s; see help(%s)' % ( funcname, funcname)) + if allmatch: + if not (Nx == numCols and Ny == numRows): + raise TypeError('Dimensions of C %s are incompatible with' + ' X (%d) and/or Y (%d); see help(%s)' % ( + C.shape, Nx, Ny, funcname)) + else: + if not (numCols in (Nx, Nx-1) and numRows in (Ny, Ny-1)): + raise TypeError('Dimensions of C %s are incompatible with' + ' X (%d) and/or Y (%d); see help(%s)' % ( + C.shape, Nx, Ny, funcname)) + C = C[:Ny-1, :Nx-1] return X, Y, C @docstring.dedent_interpd @@ -7439,7 +7472,7 @@ def pcolor(self, *args, **kwargs): x = np.arange(5) y = np.arange(3) - X, Y = meshgrid(x,y) + X, Y = np.meshgrid(x, y) is equivalent to:: @@ -7453,9 +7486,9 @@ def pcolor(self, *args, **kwargs): so if you have:: - C = rand( len(x), len(y)) + C = rand(len(x), len(y)) - then you need:: + then you need to transpose C:: pcolor(X, Y, C.T) @@ -7504,7 +7537,7 @@ def pcolor(self, *args, **kwargs): '1.2', 'shading', alternative='edgecolors', obj_type='option') shading = kwargs.pop('shading', 'flat') - X, Y, C = self._pcolorargs('pcolor', *args) + X, Y, C = self._pcolorargs('pcolor', *args, allmatch=False) Ny, Nx = X.shape # convert to MA, if necessary. @@ -7515,7 +7548,7 @@ def pcolor(self, *args, **kwargs): xymask = (mask[0:-1, 0:-1] + mask[1:, 1:] + mask[0:-1, 1:] + mask[1:, 0:-1]) # don't plot if C or any of the surrounding vertices are masked. - mask = ma.getmaskarray(C)[0:Ny - 1, 0:Nx - 1] + xymask + mask = ma.getmaskarray(C) + xymask newaxis = np.newaxis compress = np.compress @@ -7693,15 +7726,13 @@ def pcolormesh(self, *args, **kwargs): antialiased = kwargs.pop('antialiased', False) kwargs.setdefault('edgecolors', 'None') - X, Y, C = self._pcolorargs('pcolormesh', *args) + allmatch = (shading == 'gouraud') + + X, Y, C = self._pcolorargs('pcolormesh', *args, allmatch=allmatch) Ny, Nx = X.shape # convert to one dimensional arrays - if shading != 'gouraud': - C = ma.ravel(C[0:Ny - 1, 0:Nx - 1]) # data point in each cell is - # value at lower left corner - else: - C = C.ravel() + C = C.ravel() X = X.ravel() Y = Y.ravel() diff --git a/lib/matplotlib/backends/backend_gtk3.py b/lib/matplotlib/backends/backend_gtk3.py index 43c041738209..88eee7ff5616 100644 --- a/lib/matplotlib/backends/backend_gtk3.py +++ b/lib/matplotlib/backends/backend_gtk3.py @@ -3,10 +3,22 @@ import os, sys def fn_name(): return sys._getframe(1).f_code.co_name +try: + import gi +except ImportError: + raise ImportError("Gtk3 backend requires pygobject to be installed.") + +try: + gi.require_version("Gtk", "3.0") +except ValueError: + raise ImportError( + "Gtk3 backend requires the GObject introspection bindings for Gtk 3 " + "to be installed.") + try: from gi.repository import Gtk, Gdk, GObject except ImportError: - raise ImportError("GTK3 backend requires pygobject to be installed.") + raise ImportError("Gtk3 backend requires pygobject to be installed.") import matplotlib from matplotlib._pylab_helpers import Gcf diff --git a/lib/matplotlib/backends/backend_mixed.py b/lib/matplotlib/backends/backend_mixed.py index 4b1a8b95b08a..511304855514 100644 --- a/lib/matplotlib/backends/backend_mixed.py +++ b/lib/matplotlib/backends/backend_mixed.py @@ -48,6 +48,7 @@ def __init__(self, figure, width, height, dpi, vector_renderer, # the figure dpi before and after the rasterization. Although # this looks ugly, I couldn't find a better solution. -JJL self.figure=figure + self._figdpi = figure.get_dpi() self._bbox_inches_restore = bbox_inches_restore @@ -121,16 +122,19 @@ def stop_rasterizing(self): image.is_grayscale = False image.flipud_out() gc = self._renderer.new_gc() + # TODO: If the mixedmode resolution differs from the figure's + # dpi, the image must be scaled (dpi->_figdpi). Not all + # backends support this. self._renderer.draw_image( gc, - float(l)/self.dpi*72., - (float(height) - b - h)/self.dpi*72., + float(l) / self.dpi * self._figdpi, + (float(height)-b-h) / self.dpi * self._figdpi, image) self._raster_renderer = None self._rasterizing = False - # restore the figure dpi. - self.figure.set_dpi(72) + # restore the figure dpi. + self.figure.set_dpi(self._figdpi) if self._bbox_inches_restore: # when tight bbox is used r = process_figure_for_rasterizing(self.figure, diff --git a/lib/matplotlib/backends/backend_pgf.py b/lib/matplotlib/backends/backend_pgf.py index c9015d3a5237..63c48082a85f 100644 --- a/lib/matplotlib/backends/backend_pgf.py +++ b/lib/matplotlib/backends/backend_pgf.py @@ -13,6 +13,7 @@ import matplotlib as mpl from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase +from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.figure import Figure from matplotlib.text import Text from matplotlib.path import Path @@ -738,7 +739,7 @@ def __init__(self, *args): def get_default_filetype(self): return 'pdf' - def _print_pgf_to_fh(self, fh): + def _print_pgf_to_fh(self, fh, *args, **kwargs): header_text = r"""%% Creator: Matplotlib, PGF backend %% %% To include the figure in your LaTeX document, write @@ -767,6 +768,7 @@ def _print_pgf_to_fh(self, fh): # get figure size in inch w, h = self.figure.get_figwidth(), self.figure.get_figheight() + dpi = self.figure.get_dpi() # create pgfpicture environment and write the pgf code fh.write(header_text) @@ -777,7 +779,10 @@ def _print_pgf_to_fh(self, fh): writeln(fh, r"\begin{pgfpicture}") writeln(fh, r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}" % (w, h)) writeln(fh, r"\pgfusepath{use as bounding box}") - renderer = RendererPgf(self.figure, fh) + _bbox_inches_restore = kwargs.pop("bbox_inches_restore", None) + renderer = MixedModeRenderer(self.figure, w, h, dpi, + RendererPgf(self.figure, fh), + bbox_inches_restore=_bbox_inches_restore) self.figure.draw(renderer) # end the pgfpicture environment @@ -796,14 +801,14 @@ def print_pgf(self, fname_or_fh, *args, **kwargs): # figure out where the pgf is to be written to if is_string_like(fname_or_fh): with codecs.open(fname_or_fh, "w", encoding="utf-8") as fh: - self._print_pgf_to_fh(fh) + self._print_pgf_to_fh(fh, *args, **kwargs) elif is_writable_file_like(fname_or_fh): raise ValueError("saving pgf to a stream is not supported, " + "consider using the pdf option of the pgf-backend") else: raise ValueError("filename must be a path") - def _print_pdf_to_fh(self, fh): + def _print_pdf_to_fh(self, fh, *args, **kwargs): w, h = self.figure.get_figwidth(), self.figure.get_figheight() try: @@ -814,7 +819,7 @@ def _print_pdf_to_fh(self, fh): fname_pdf = os.path.join(tmpdir, "figure.pdf") # print figure to pgf and compile it with latex - self.print_pgf(fname_pgf) + self.print_pgf(fname_pgf, *args, **kwargs) latex_preamble = get_preamble() latex_fontspec = get_fontspec() @@ -856,13 +861,13 @@ def print_pdf(self, fname_or_fh, *args, **kwargs): # figure out where the pdf is to be written to if is_string_like(fname_or_fh): with open(fname_or_fh, "wb") as fh: - self._print_pdf_to_fh(fh) + self._print_pdf_to_fh(fh, *args, **kwargs) elif is_writable_file_like(fname_or_fh): - self._print_pdf_to_fh(fname_or_fh) + self._print_pdf_to_fh(fname_or_fh, *args, **kwargs) else: raise ValueError("filename must be a path or a file-like object") - def _print_png_to_fh(self, fh): + def _print_png_to_fh(self, fh, *args, **kwargs): converter = make_pdf_to_png_converter() try: @@ -871,7 +876,7 @@ def _print_png_to_fh(self, fh): fname_pdf = os.path.join(tmpdir, "figure.pdf") fname_png = os.path.join(tmpdir, "figure.png") # create pdf and try to convert it to png - self.print_pdf(fname_pdf) + self.print_pdf(fname_pdf, *args, **kwargs) converter(fname_pdf, fname_png, dpi=self.figure.dpi) # copy file contents to target with open(fname_png, "rb") as fh_src: @@ -888,9 +893,9 @@ def print_png(self, fname_or_fh, *args, **kwargs): """ if is_string_like(fname_or_fh): with open(fname_or_fh, "wb") as fh: - self._print_png_to_fh(fh) + self._print_png_to_fh(fh, *args, **kwargs) elif is_writable_file_like(fname_or_fh): - self._print_png_to_fh(fname_or_fh) + self._print_png_to_fh(fname_or_fh, *args, **kwargs) else: raise ValueError("filename must be a path or a file-like object") diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 2c0426d78f2f..cbbfb96f58a6 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -1276,7 +1276,6 @@ def update_datalim_to_current(self): x, y = self.asarrays() self.dataLim.update_from_data(x, y, True) - self.dataLim.update_numerix(x, y, True) def movavg(x,n): """ diff --git a/lib/matplotlib/pylab.py b/lib/matplotlib/pylab.py index 5de759bbaaca..bf8b97ba5eb7 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 (nrows, ncols, plot_number) + 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 diff --git a/lib/matplotlib/tests/baseline_images/test_backend_pgf/pgf_mixedmode.pdf b/lib/matplotlib/tests/baseline_images/test_backend_pgf/pgf_mixedmode.pdf new file mode 100644 index 000000000000..86dfbbc527cf Binary files /dev/null and b/lib/matplotlib/tests/baseline_images/test_backend_pgf/pgf_mixedmode.pdf differ diff --git a/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.pdf b/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.pdf index 192890d2cd07..9526a55043a5 100644 Binary files a/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.pdf and b/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.pdf differ diff --git a/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.png b/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.png index d6ad8e0114e1..eff0430fe58a 100644 Binary files a/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.png and b/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.png differ diff --git a/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.svg b/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.svg index b73afae3fb32..9c4c06627f9c 100644 --- a/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.svg +++ b/lib/matplotlib/tests/baseline_images/test_transforms/pre_transform_data.svg @@ -5,7 +5,7 @@ @@ -49,7 +49,7 @@ L92.5748 -82.7503 L92.5748 -59.2357" id="C0_0_d6879774b7"/> - + @@ -77,7 +77,7 @@ L333.997 -59.2357 L333.997 -59.2357" id="C1_0_d5dad72e48"/> - + @@ -106,7 +106,7 @@ L253.523 -90.5885 L293.76 -86.6694" id="C2_0_f77b20b182"/> - + @@ -135,7 +135,7 @@ L173.049 -121.941 L213.286 -118.022" id="C3_0_05e8bb0faf"/> - + @@ -162,7 +162,7 @@ L92.5748 -153.294 L132.812 -149.375" id="C4_0_8fef5974c0"/> - + @@ -191,7 +191,7 @@ L333.997 -153.294 L374.234 -149.375" id="C5_0_06dd094376"/> - + @@ -219,7 +219,7 @@ L253.523 -184.647 L293.76 -180.728" id="C6_0_505e2f4f40"/> - + @@ -239,7 +239,7 @@ L173.049 -216 L213.286 -212.081" id="C7_0_06d336a9bf"/> - + @@ -534,148 +534,148 @@ L226.698 -310.059 L226.698 -300.261" id="C8_2f_d396b34810"/> - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -694,154 +694,154 @@ z " id="C9_0_919e3f95db"/> - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -2942,151 +2942,151 @@ z " id="Cb_30_91dfad6065"/> - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -5517,1780 +5517,1780 @@ M453.297 -178.597 L453.297 -178.597" id="Cc_24f_abb5b36b8e"/> - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -7299,20 +7299,20 @@ L453.297 -178.597" id="Cc_24f_abb5b36b8e"/> +L0 -4" id="m93b0483c22" style="stroke:#000000;stroke-width:0.5;"/> - + +L0 4" id="m741efc42ff" style="stroke:#000000;stroke-width:0.5;"/> - + @@ -7338,7 +7338,7 @@ Q6.59375 17.9688 6.59375 36.375 Q6.59375 54.8281 13.0625 64.5156 Q19.5312 74.2188 31.7812 74.2188" id="BitstreamVeraSans-Roman-30"/> - + @@ -7346,12 +7346,12 @@ Q19.5312 74.2188 31.7812 74.2188" id="BitstreamVeraSans-Roman-30"/> - + - + @@ -7381,7 +7381,7 @@ Q49.8594 40.875 45.4062 35.4062 Q44.1875 33.9844 37.6406 27.2188 Q31.1094 20.4531 19.1875 8.29688" id="BitstreamVeraSans-Roman-32"/> - + @@ -7390,12 +7390,12 @@ Q31.1094 20.4531 19.1875 8.29688" id="BitstreamVeraSans-Roman-32"/> - + - + @@ -7421,7 +7421,7 @@ L4.89062 26.7031 z " id="BitstreamVeraSans-Roman-34"/> - + @@ -7430,12 +7430,12 @@ z - + - + @@ -7470,7 +7470,7 @@ Q23.3906 74.2188 37.2031 74.2188 Q40.9219 74.2188 44.7031 73.4844 Q48.4844 72.75 52.5938 71.2969" id="BitstreamVeraSans-Roman-36"/> - + @@ -7479,12 +7479,12 @@ Q48.4844 72.75 52.5938 71.2969" id="BitstreamVeraSans-Roman-36"/> - + - + @@ -7527,7 +7527,7 @@ Q38.1406 66.4062 31.7812 66.4062 Q25.3906 66.4062 21.8438 63.2344 Q18.3125 60.0625 18.3125 54.3906" id="BitstreamVeraSans-Roman-38"/> - + @@ -7536,12 +7536,12 @@ Q18.3125 60.0625 18.3125 54.3906" id="BitstreamVeraSans-Roman-38"/> - + - + @@ -7562,7 +7562,7 @@ L12.4062 0 z " id="BitstreamVeraSans-Roman-31"/> - + @@ -7576,25 +7576,25 @@ z +L4 0" id="m728421d6d4" style="stroke:#000000;stroke-width:0.5;"/> - + +L-4 0" id="mcb0005524f" style="stroke:#000000;stroke-width:0.5;"/> - + - + @@ -7602,17 +7602,17 @@ L-4 0" id="m0d5b0a6425" style="stroke:#000000;stroke-linecap:butt;stroke-width:0 - + - + - + @@ -7621,17 +7621,17 @@ L-4 0" id="m0d5b0a6425" style="stroke:#000000;stroke-linecap:butt;stroke-width:0 - + - + - + @@ -7640,17 +7640,17 @@ L-4 0" id="m0d5b0a6425" style="stroke:#000000;stroke-linecap:butt;stroke-width:0 - + - + - + @@ -7659,17 +7659,17 @@ L-4 0" id="m0d5b0a6425" style="stroke:#000000;stroke-linecap:butt;stroke-width:0 - + - + - + @@ -7678,17 +7678,17 @@ L-4 0" id="m0d5b0a6425" style="stroke:#000000;stroke-linecap:butt;stroke-width:0 - + - + - + diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 1e77570d366e..a812e3b14418 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -1,4 +1,6 @@ from nose.tools import assert_equal +from nose.tools import assert_raises + import numpy as np from numpy import ma @@ -293,7 +295,6 @@ def test_shaped_data(): plt.plot( y2 ) plt.subplot( 413 ) - from nose.tools import assert_raises assert_raises(ValueError,plt.plot, (y1,y2)) plt.subplot( 414 ) @@ -662,6 +663,20 @@ def test_pcolormesh(): ax = fig.add_subplot(133) ax.pcolormesh(Qx,Qz,Z, shading="gouraud") +def test_pcolorargs(): + n = 12 + x = np.linspace(-1.5, 1.5, n) + y = np.linspace(-1.5, 1.5, n*2) + X, Y = np.meshgrid(x, y) + Z = np.sqrt(X**2 + Y**2)/5 + + _, ax = plt.subplots() + assert_raises(TypeError, ax.pcolormesh, y, x, Z) + assert_raises(TypeError, ax.pcolormesh, X, Y, Z.T) + assert_raises(TypeError, ax.pcolormesh, x, y, Z[:-1, :-1], + shading="gouraud") + assert_raises(TypeError, ax.pcolormesh, X, Y, Z[:-1, :-1], + shading="gouraud") @image_comparison(baseline_images=['canonical']) def test_canonical(): diff --git a/lib/matplotlib/tests/test_backend_pgf.py b/lib/matplotlib/tests/test_backend_pgf.py index 8f922e7727f0..34c31ce9a604 100644 --- a/lib/matplotlib/tests/test_backend_pgf.py +++ b/lib/matplotlib/tests/test_backend_pgf.py @@ -145,6 +145,18 @@ def test_pathclip(): plt.savefig(os.path.join(result_dir, "pgf_pathclip.pdf")) +# test mixed mode rendering +@switch_backend('pgf') +def test_mixedmode(): + if not check_for('xelatex'): + raise SkipTest('xelatex + pgf is required') + + Y, X = np.ogrid[-1:1:40j, -1:1:40j] + plt.figure() + plt.pcolor(X**2 + Y**2).set_rasterized(True) + compare_figure('pgf_mixedmode.pdf') + + if __name__ == '__main__': import nose nose.runmodule(argv=['-s','--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index 1790c04ee9f8..54586d608c1a 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -2,7 +2,7 @@ import unittest from nose.tools import assert_equal, assert_raises -import numpy.testing as np_test +import numpy.testing as np_test from numpy.testing import assert_almost_equal from matplotlib.transforms import Affine2D, BlendedGenericTransform from matplotlib.path import Path @@ -61,7 +61,7 @@ def test_external_transform_api(): class ScaledBy(object): def __init__(self, scale_factor): self._scale_factor = scale_factor - + def _as_mpl_transform(self, axes): return mtrans.Affine2D().scale(self._scale_factor) + axes.transData @@ -70,28 +70,28 @@ def _as_mpl_transform(self, axes): ax.set_xlim(0, 100) ax.set_ylim(0, 100) # assert that the top transform of the line is the scale transform. - np.testing.assert_allclose(line.get_transform()._a.get_matrix(), + np.testing.assert_allclose(line.get_transform()._a.get_matrix(), mtrans.Affine2D().scale(10).get_matrix()) - + @image_comparison(baseline_images=['pre_transform_data']) def test_pre_transform_plotting(): # a catch-all for as many as possible plot layouts which handle pre-transforming the data - # NOTE: The axis range is important in this plot. It should be x10 what the data suggests it should be + # NOTE: The axis range is important in this plot. It should be x10 what the data suggests it should be ax = plt.axes() times10 = mtrans.Affine2D().scale(10) - + ax.contourf(np.arange(48).reshape(6, 8), transform=times10 + ax.transData) - - ax.pcolormesh(np.linspace(0, 4, 7), - np.linspace(5.5, 8, 9), - np.arange(48).reshape(6, 8), + + ax.pcolormesh(np.linspace(0, 4, 7), + np.linspace(5.5, 8, 9), + np.arange(48).reshape(8, 6), transform=times10 + ax.transData) - - ax.scatter(np.linspace(0, 10), np.linspace(10, 0), + + ax.scatter(np.linspace(0, 10), np.linspace(10, 0), transform=times10 + ax.transData) - - + + x = np.linspace(8, 10, 20) y = np.linspace(1, 5, 20) u = 2*np.sin(x) + np.cos(y[:, np.newaxis]) @@ -99,13 +99,13 @@ def test_pre_transform_plotting(): ax.streamplot(x, y, u, v, transform=times10 + ax.transData, density=(1, 1), linewidth=u**2 + v**2) - + # reduce the vector data down a bit for barb and quiver plotting x, y = x[::3], y[::3] u, v = u[::3, ::3], v[::3, ::3] - + ax.quiver(x, y + 5, u, v, transform=times10 + ax.transData) - + ax.barbs(x - 3, y + 5, u**2, v**2, transform=times10 + ax.transData) @@ -114,7 +114,7 @@ def test_contour_pre_transform_limits(): ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.contourf(xs, ys, np.log(xs * ys), transform=mtrans.Affine2D().scale(0.1) + ax.transData) - + expected = np.array([[ 1.5 , 1.24], [ 2. , 1.25]]) assert_almost_equal(expected, ax.dataLim.get_points()) @@ -126,7 +126,7 @@ def test_pcolor_pre_transform_limits(): ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.pcolor(xs, ys, np.log(xs * ys), transform=mtrans.Affine2D().scale(0.1) + ax.transData) - + expected = np.array([[ 1.5 , 1.24], [ 2. , 1.25]]) assert_almost_equal(expected, ax.dataLim.get_points()) @@ -138,11 +138,11 @@ def test_pcolormesh_pre_transform_limits(): ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.pcolormesh(xs, ys, np.log(xs * ys), transform=mtrans.Affine2D().scale(0.1) + ax.transData) - + expected = np.array([[ 1.5 , 1.24], [ 2. , 1.25]]) assert_almost_equal(expected, ax.dataLim.get_points()) - + def test_Affine2D_from_values(): points = np.array([ [0,0], @@ -248,7 +248,7 @@ def setUp(self): # self.stack1.write_graphviz(file('stack1.dot', 'w')) # self.stack2.write_graphviz(file('stack2.dot', 'w')) # self.stack2_subset.write_graphviz(file('stack2_subset.dot', 'w')) - + def test_transform_depth(self): assert_equal(self.stack1.depth, 4) assert_equal(self.stack2.depth, 4) @@ -274,7 +274,7 @@ def test_transform_shortcuts(self): self.assertEqual(self.stack1 - self.stack2_subset, self.ta1) self.assertEqual(self.stack2 - self.stack2_subset, self.ta1) - assert_equal((self.stack2_subset - self.stack2), + assert_equal((self.stack2_subset - self.stack2), self.ta1.inverted(), ) assert_equal((self.stack2_subset - self.stack2).depth, 1) @@ -289,7 +289,7 @@ def test_transform_shortcuts(self): self.assertEqual(self.stack1 - self.ta3, self.ta1 + (self.tn1 + self.ta2)) self.assertEqual(self.stack2 - self.ta3, self.ta1 + self.tn1 + self.ta2) - + self.assertEqual((self.ta2 + self.ta3) - self.ta3 + self.ta3, self.ta2 + self.ta3) def test_contains_branch(self): @@ -354,7 +354,7 @@ def test_affine_simplification(self): class TestTransformPlotInterface(unittest.TestCase): def tearDown(self): plt.close() - + def test_line_extent_axes_coords(self): # a simple line in axes coordinates ax = plt.axes() @@ -426,7 +426,7 @@ def test_pathc_extents_affine(self): patch = mpatches.PathPatch(pth, transform=offset + ax.transData) ax.add_patch(patch) expeted_data_lim = np.array([[0., 0.], [10., 10.]]) + 10 - np.testing.assert_array_almost_equal(ax.dataLim.get_points(), + np.testing.assert_array_almost_equal(ax.dataLim.get_points(), expeted_data_lim) @@ -440,7 +440,7 @@ def test_line_extents_for_non_affine_transData(self): # before a transData transformation, hence the data limits # are not what is being shown on the actual plot. expeted_data_lim = np.array([[0., 0.], [9., 9.]]) + [0, 10] - np.testing.assert_array_almost_equal(ax.dataLim.get_points(), + np.testing.assert_array_almost_equal(ax.dataLim.get_points(), expeted_data_lim)