From 6bda3c1462f55c2b01b4dca81ace3c7b3e4987d2 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Tue, 8 Jul 2014 20:34:53 -0400 Subject: [PATCH] Revert "pep8ify more examples in examples/ + use np.radians/np.degrees" --- examples/animation/animate_decay.py | 13 ++- examples/animation/basic_example.py | 9 +- examples/animation/basic_example_writer.py | 7 +- examples/animation/bayes_update.py | 4 +- .../animation/double_pendulum_animated.py | 49 ++++++----- examples/animation/dynamic_image.py | 6 +- examples/animation/dynamic_image2.py | 5 +- examples/animation/histogram.py | 26 +++--- examples/animation/moviewriter.py | 5 +- examples/animation/rain.py | 18 ++-- examples/animation/random_data.py | 5 +- examples/animation/simple_3danim.py | 16 ++-- examples/animation/simple_anim.py | 10 +-- examples/animation/strip_chart_demo.py | 6 +- examples/animation/subplots.py | 24 ++---- examples/animation/unchained.py | 2 +- examples/axes_grid/demo_axes_divider.py | 11 ++- examples/axes_grid/demo_axes_grid.py | 37 ++++---- examples/axes_grid/demo_axes_grid2.py | 42 ++++----- examples/axes_grid/demo_axes_hbox_divider.py | 19 +++-- examples/axes_grid/demo_axes_rgb.py | 33 +++---- examples/axes_grid/demo_axisline_style.py | 2 +- .../demo_colorbar_with_inset_locator.py | 16 ++-- examples/axes_grid/demo_curvelinear_grid.py | 38 +++++---- examples/axes_grid/demo_curvelinear_grid2.py | 28 +++--- examples/axes_grid/demo_edge_colorbar.py | 21 ++--- examples/axes_grid/demo_floating_axes.py | 85 ++++++++++--------- examples/axes_grid/demo_floating_axis.py | 15 ++-- examples/axes_grid/demo_imagegrid_aspect.py | 8 +- examples/axes_grid/demo_parasite_axes2.py | 6 +- examples/axes_grid/inset_locator_demo.py | 20 ++--- examples/axes_grid/inset_locator_demo2.py | 10 +-- .../make_room_for_ylabel_using_axesgrid.py | 23 ++--- examples/axes_grid/parasite_simple2.py | 6 +- examples/axes_grid/scatter_hist.py | 10 +-- examples/axes_grid/simple_anchored_artists.py | 9 +- examples/axes_grid/simple_axesgrid.py | 10 +-- examples/axes_grid/simple_axesgrid2.py | 26 +++--- examples/axes_grid/simple_axisline4.py | 7 +- examples/color/color_cycle_demo.py | 6 +- examples/color/colormaps_reference.py | 3 +- examples/color/named_colors.py | 2 +- examples/pylab_examples/tricontour_demo.py | 4 +- examples/pylab_examples/tripcolor_demo.py | 4 +- examples/pylab_examples/triplot_demo.py | 4 +- examples/units/annotate_with_units.py | 13 +-- examples/units/ellipse_with_units.py | 4 +- examples/user_interfaces/svg_histogram.py | 54 ++++++------ examples/user_interfaces/svg_tooltip.py | 57 ++++++------- examples/user_interfaces/wxcursor_demo.py | 23 +++-- examples/widgets/buttons.py | 8 +- examples/widgets/check_buttons.py | 16 ++-- examples/widgets/cursor.py | 4 +- examples/widgets/lasso_selector_demo.py | 2 - examples/widgets/menu.py | 33 +++---- examples/widgets/multicursor.py | 4 +- examples/widgets/radio_buttons.py | 14 +-- examples/widgets/rectangle_selector.py | 14 ++- examples/widgets/slider_demo.py | 13 +-- examples/widgets/span_selector.py | 10 +-- 60 files changed, 478 insertions(+), 501 deletions(-) diff --git a/examples/animation/animate_decay.py b/examples/animation/animate_decay.py index 5b4ace31c3c9..a8694615e99b 100644 --- a/examples/animation/animate_decay.py +++ b/examples/animation/animate_decay.py @@ -2,14 +2,13 @@ import matplotlib.pyplot as plt import matplotlib.animation as animation - def data_gen(): t = data_gen.t cnt = 0 while cnt < 1000: - cnt += 1 + cnt+=1 t += 0.05 - yield t, np.sin(2 * np.pi * t) * np.exp(-t / 10.) + yield t, np.sin(2*np.pi*t) * np.exp(-t/10.) data_gen.t = 0 fig, ax = plt.subplots() @@ -18,22 +17,20 @@ def data_gen(): ax.set_xlim(0, 5) ax.grid() xdata, ydata = [], [] - - def run(data): # update the data - t, y = data + t,y = data xdata.append(t) ydata.append(y) xmin, xmax = ax.get_xlim() if t >= xmax: - ax.set_xlim(xmin, 2 * xmax) + ax.set_xlim(xmin, 2*xmax) ax.figure.canvas.draw() line.set_data(xdata, ydata) return line, ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10, - repeat=False) + repeat=False) plt.show() diff --git a/examples/animation/basic_example.py b/examples/animation/basic_example.py index 35ee0ebc14d5..82cfdc3e40fc 100644 --- a/examples/animation/basic_example.py +++ b/examples/animation/basic_example.py @@ -2,9 +2,8 @@ import matplotlib.pyplot as plt import matplotlib.animation as animation - def update_line(num, data, line): - line.set_data(data[..., :num]) + line.set_data(data[...,:num]) return line, fig1 = plt.figure() @@ -16,8 +15,8 @@ def update_line(num, data, line): plt.xlabel('x') plt.title('test') line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l), - interval=50, blit=True) -# line_ani.save('lines.mp4') + interval=50, blit=True) +#line_ani.save('lines.mp4') fig2 = plt.figure() @@ -29,7 +28,7 @@ def update_line(num, data, line): ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),)) im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000, - blit=True) + blit=True) #im_ani.save('im.mp4', metadata={'artist':'Guido'}) plt.show() diff --git a/examples/animation/basic_example_writer.py b/examples/animation/basic_example_writer.py index 6f3845dc3f46..fef958942621 100644 --- a/examples/animation/basic_example_writer.py +++ b/examples/animation/basic_example_writer.py @@ -7,9 +7,8 @@ import matplotlib.pyplot as plt import matplotlib.animation as animation - def update_line(num, data, line): - line.set_data(data[..., :num]) + line.set_data(data[...,:num]) return line, # Set up formatting for the movie files @@ -26,7 +25,7 @@ def update_line(num, data, line): plt.xlabel('x') plt.title('test') line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l), - interval=50, blit=True) + interval=50, blit=True) line_ani.save('lines.mp4', writer=writer) fig2 = plt.figure() @@ -39,5 +38,5 @@ def update_line(num, data, line): ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),)) im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000, - blit=True) + blit=True) im_ani.save('im.mp4', writer=writer) diff --git a/examples/animation/bayes_update.py b/examples/animation/bayes_update.py index 246995fe6e9a..e3ba5a356a20 100644 --- a/examples/animation/bayes_update.py +++ b/examples/animation/bayes_update.py @@ -4,9 +4,7 @@ import scipy.stats as ss from matplotlib.animation import FuncAnimation - class UpdateDist(object): - def __init__(self, ax, prob=0.5): self.success = 0 self.prob = prob @@ -45,5 +43,5 @@ def __call__(self, i): ax = fig.add_subplot(1, 1, 1) ud = UpdateDist(ax, prob=0.7) anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init, - interval=100, blit=True) + interval=100, blit=True) plt.show() diff --git a/examples/animation/double_pendulum_animated.py b/examples/animation/double_pendulum_animated.py index 81d205f49441..cae06d64cf1c 100644 --- a/examples/animation/double_pendulum_animated.py +++ b/examples/animation/double_pendulum_animated.py @@ -7,11 +7,11 @@ import scipy.integrate as integrate import matplotlib.animation as animation -G = 9.8 # acceleration due to gravity, in m/s^2 -L1 = 1.0 # length of pendulum 1 in m -L2 = 1.0 # length of pendulum 2 in m -M1 = 1.0 # mass of pendulum 1 in kg -M2 = 1.0 # mass of pendulum 2 in kg +G = 9.8 # acceleration due to gravity, in m/s^2 +L1 = 1.0 # length of pendulum 1 in m +L2 = 1.0 # length of pendulum 2 in m +M1 = 1.0 # mass of pendulum 1 in kg +M2 = 1.0 # mass of pendulum 2 in kg def derivs(state, t): @@ -19,20 +19,19 @@ def derivs(state, t): dydx = np.zeros_like(state) dydx[0] = state[1] - del_ = state[2] - state[0] - den1 = (M1 + M2) * L1 - M2 * L1 * cos(del_) * cos(del_) - dydx[1] = (M2 * L1 * state[1] * state[1] * sin(del_) * cos(del_) - + M2 * G * sin(state[2]) * cos(del_) + M2 * - L2 * state[3] * state[3] * sin(del_) - - (M1 + M2) * G * sin(state[0])) / den1 + del_ = state[2]-state[0] + den1 = (M1+M2)*L1 - M2*L1*cos(del_)*cos(del_) + dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_) + + M2*G*sin(state[2])*cos(del_) + M2*L2*state[3]*state[3]*sin(del_) + - (M1+M2)*G*sin(state[0]))/den1 dydx[2] = state[3] - den2 = (L2 / L1) * den1 - dydx[3] = (-M2 * L2 * state[3] * state[3] * sin(del_) * cos(del_) - + (M1 + M2) * G * sin(state[0]) * cos(del_) - - (M1 + M2) * L1 * state[1] * state[1] * sin(del_) - - (M1 + M2) * G * sin(state[2])) / den2 + den2 = (L2/L1)*den1 + dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*cos(del_) + + (M1+M2)*G*sin(state[0])*cos(del_) + - (M1+M2)*L1*state[1]*state[1]*sin(del_) + - (M1+M2)*G*sin(state[2]))/den2 return dydx @@ -47,17 +46,19 @@ def derivs(state, t): th2 = -10.0 w2 = 0.0 +rad = pi/180 + # initial state -state = np.radians([th1, w1, th2, w2]) +state = np.array([th1, w1, th2, w2])*pi/180. # integrate your ODE using scipy.integrate. y = integrate.odeint(derivs, state, t) -x1 = L1 * sin(y[:, 0]) -y1 = -L1 * cos(y[:, 0]) +x1 = L1*sin(y[:,0]) +y1 = -L1*cos(y[:,0]) -x2 = L2 * sin(y[:, 2]) + x1 -y2 = -L2 * cos(y[:, 2]) + y1 +x2 = L2*sin(y[:,2]) + x1 +y2 = -L2*cos(y[:,2]) + y1 fig = plt.figure() ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2)) @@ -67,23 +68,21 @@ def derivs(state, t): time_template = 'time = %.1fs' time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) - def init(): line.set_data([], []) time_text.set_text('') return line, time_text - def animate(i): thisx = [0, x1[i], x2[i]] thisy = [0, y1[i], y2[i]] line.set_data(thisx, thisy) - time_text.set_text(time_template % (i * dt)) + time_text.set_text(time_template%(i*dt)) return line, time_text ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)), - interval=25, blit=True, init_func=init) + interval=25, blit=True, init_func=init) #ani.save('double_pendulum.mp4', fps=15) plt.show() diff --git a/examples/animation/dynamic_image.py b/examples/animation/dynamic_image.py index 247bbc031ad9..e25e66b0eb33 100644 --- a/examples/animation/dynamic_image.py +++ b/examples/animation/dynamic_image.py @@ -8,7 +8,6 @@ fig = plt.figure() - def f(x, y): return np.sin(x) + np.cos(y) @@ -17,12 +16,11 @@ def f(x, y): im = plt.imshow(f(x, y), cmap=plt.get_cmap('jet')) - def updatefig(*args): - global x, y + global x,y x += np.pi / 15. y += np.pi / 20. - im.set_array(f(x, y)) + im.set_array(f(x,y)) return im, ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True) diff --git a/examples/animation/dynamic_image2.py b/examples/animation/dynamic_image2.py index a424b3bbe160..832b688bda67 100644 --- a/examples/animation/dynamic_image2.py +++ b/examples/animation/dynamic_image2.py @@ -8,7 +8,6 @@ fig = plt.figure() - def f(x, y): return np.sin(x) + np.cos(y) @@ -25,9 +24,9 @@ def f(x, y): ims.append([im]) ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, - repeat_delay=1000) + repeat_delay=1000) -# ani.save('dynamic_images.mp4') +#ani.save('dynamic_images.mp4') plt.show() diff --git a/examples/animation/histogram.py b/examples/animation/histogram.py index e4fbc655572b..f81d4f397269 100644 --- a/examples/animation/histogram.py +++ b/examples/animation/histogram.py @@ -28,36 +28,34 @@ # for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the # CLOSEPOLY; the vert for the closepoly is ignored but we still need # it to keep the codes aligned with the vertices -nverts = nrects * (1 + 3 + 1) +nverts = nrects*(1+3+1) verts = np.zeros((nverts, 2)) codes = np.ones(nverts, int) * path.Path.LINETO codes[0::5] = path.Path.MOVETO codes[4::5] = path.Path.CLOSEPOLY -verts[0::5, 0] = left -verts[0::5, 1] = bottom -verts[1::5, 0] = left -verts[1::5, 1] = top -verts[2::5, 0] = right -verts[2::5, 1] = top -verts[3::5, 0] = right -verts[3::5, 1] = bottom +verts[0::5,0] = left +verts[0::5,1] = bottom +verts[1::5,0] = left +verts[1::5,1] = top +verts[2::5,0] = right +verts[2::5,1] = top +verts[3::5,0] = right +verts[3::5,1] = bottom barpath = path.Path(verts, codes) -patch = patches.PathPatch( - barpath, facecolor='green', edgecolor='yellow', alpha=0.5) +patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5) ax.add_patch(patch) ax.set_xlim(left[0], right[-1]) ax.set_ylim(bottom.min(), top.max()) - def animate(i): # simulate new data coming in data = np.random.randn(1000) n, bins = np.histogram(data, 100) top = bottom + n - verts[1::5, 1] = top - verts[2::5, 1] = top + verts[1::5,1] = top + verts[2::5,1] = top ani = animation.FuncAnimation(fig, animate, 100, repeat=False) plt.show() diff --git a/examples/animation/moviewriter.py b/examples/animation/moviewriter.py index 530bbd714f87..090de236813b 100644 --- a/examples/animation/moviewriter.py +++ b/examples/animation/moviewriter.py @@ -12,7 +12,7 @@ FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='Movie Test', artist='Matplotlib', - comment='Movie support!') + comment='Movie support!') writer = FFMpegWriter(fps=15, metadata=metadata) fig = plt.figure() @@ -21,7 +21,7 @@ plt.xlim(-5, 5) plt.ylim(-5, 5) -x0, y0 = 0, 0 +x0,y0 = 0, 0 with writer.saving(fig, "writer_test.mp4", 100): for i in range(100): @@ -29,3 +29,4 @@ y0 += 0.1 * np.random.randn() l.set_data(x0, y0) writer.grab_frame() + diff --git a/examples/animation/rain.py b/examples/animation/rain.py index 91d6130ab5d4..21ed9710bbe5 100644 --- a/examples/animation/rain.py +++ b/examples/animation/rain.py @@ -8,14 +8,14 @@ """ import numpy as np import matplotlib.pyplot as plt -from matplotlib.animation import FuncAnimation +from matplotlib.animation import FuncAnimation -# Create new Figure and an Axes which fills it. -fig = plt.figure(figsize=(7, 7)) +# Create new Figure and an Axes which fills it. +fig = plt.figure(figsize=(7,7)) ax = fig.add_axes([0, 0, 1, 1], frameon=False) -ax.set_xlim(0, 1), ax.set_xticks([]) -ax.set_ylim(0, 1), ax.set_yticks([]) +ax.set_xlim(0,1), ax.set_xticks([]) +ax.set_ylim(0,1), ax.set_yticks([]) # Create rain data n_drops = 50 @@ -31,7 +31,7 @@ # Construct the scatter which we will update during animation # as the raindrops develop. -scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1], +scat = ax.scatter(rain_drops['position'][:,0], rain_drops['position'][:,1], s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'], facecolors='none') @@ -41,8 +41,8 @@ def update(frame_number): current_index = frame_number % n_drops # Make all colors more transparent as time progresses. - rain_drops['color'][:, 3] -= 1.0 / len(rain_drops) - rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1) + rain_drops['color'][:, 3] -= 1.0/len(rain_drops) + rain_drops['color'][:,3] = np.clip(rain_drops['color'][:,3], 0, 1) # Make all circles bigger. rain_drops['size'] += rain_drops['growth'] @@ -58,7 +58,7 @@ def update(frame_number): scat.set_edgecolors(rain_drops['color']) scat.set_sizes(rain_drops['size']) scat.set_offsets(rain_drops['position']) - + # Construct the animation, using the update function as the animation # director. diff --git a/examples/animation/random_data.py b/examples/animation/random_data.py index d468ffbfce4f..c3044a3dee61 100644 --- a/examples/animation/random_data.py +++ b/examples/animation/random_data.py @@ -6,15 +6,12 @@ line, = ax.plot(np.random.rand(10)) ax.set_ylim(0, 1) - def update(data): line.set_ydata(data) return line, - def data_gen(): - while True: - yield np.random.rand(10) + while True: yield np.random.rand(10) ani = animation.FuncAnimation(fig, update, data_gen, interval=100) plt.show() diff --git a/examples/animation/simple_3danim.py b/examples/animation/simple_3danim.py index 60f54625d839..74e918fdb9dd 100644 --- a/examples/animation/simple_3danim.py +++ b/examples/animation/simple_3danim.py @@ -6,8 +6,7 @@ import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as animation - -def Gen_RandLine(length, dims=2): +def Gen_RandLine(length, dims=2) : """ Create a line using a random walk algorithm @@ -16,22 +15,21 @@ def Gen_RandLine(length, dims=2): """ lineData = np.empty((dims, length)) lineData[:, 0] = np.random.rand(dims) - for index in range(1, length): + for index in range(1, length) : # scaling the random numbers by 0.1 so # movement is small compared to position. # subtraction by 0.5 is to change the range to [-0.5, 0.5] # to allow a line to move backwards. step = ((np.random.rand(dims) - 0.5) * 0.1) - lineData[:, index] = lineData[:, index - 1] + step + lineData[:, index] = lineData[:, index-1] + step return lineData - -def update_lines(num, dataLines, lines): - for line, data in zip(lines, dataLines): +def update_lines(num, dataLines, lines) : + for line, data in zip(lines, dataLines) : # NOTE: there is no .set_data() for 3 dim data... line.set_data(data[0:2, :num]) - line.set_3d_properties(data[2, :num]) + line.set_3d_properties(data[2,:num]) return lines # Attaching 3D axis to the figure @@ -59,6 +57,6 @@ def update_lines(num, dataLines, lines): # Creating the Animation object line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines), - interval=50, blit=False) + interval=50, blit=False) plt.show() diff --git a/examples/animation/simple_anim.py b/examples/animation/simple_anim.py index a43875531604..d19196337522 100644 --- a/examples/animation/simple_anim.py +++ b/examples/animation/simple_anim.py @@ -7,20 +7,18 @@ fig, ax = plt.subplots() -x = np.arange(0, 2 * np.pi, 0.01) # x-array +x = np.arange(0, 2*np.pi, 0.01) # x-array line, = ax.plot(x, np.sin(x)) - def animate(i): - line.set_ydata(np.sin(x + i / 10.0)) # update the data + line.set_ydata(np.sin(x+i/10.0)) # update the data return line, - +#Init only required for blitting to give a clean slate. def init(): - # only required for blitting to give a clean slate. line.set_ydata(np.ma.array(x, mask=True)) return line, ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init, - interval=25, blit=True) + interval=25, blit=True) plt.show() diff --git a/examples/animation/strip_chart_demo.py b/examples/animation/strip_chart_demo.py index 7d59fe74266d..2ca94cf5a1ac 100644 --- a/examples/animation/strip_chart_demo.py +++ b/examples/animation/strip_chart_demo.py @@ -7,9 +7,7 @@ import matplotlib.pyplot as plt import matplotlib.animation as animation - class Scope: - def __init__(self, ax, maxt=2, dt=0.02): self.ax = ax self.dt = dt @@ -23,7 +21,7 @@ def __init__(self, ax, maxt=2, dt=0.02): def update(self, y): lastt = self.tdata[-1] - if lastt > self.tdata[0] + self.maxt: # reset the arrays + if lastt > self.tdata[0] + self.maxt: # reset the arrays self.tdata = [self.tdata[-1]] self.ydata = [self.ydata[-1]] self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt) @@ -50,7 +48,7 @@ def emitter(p=0.03): # pass a generator in "emitter" to produce data for the update func ani = animation.FuncAnimation(fig, scope.update, emitter, interval=10, - blit=True) + blit=True) plt.show() diff --git a/examples/animation/subplots.py b/examples/animation/subplots.py index 2c47e94a7189..462549e658f8 100644 --- a/examples/animation/subplots.py +++ b/examples/animation/subplots.py @@ -8,10 +8,7 @@ # really complex. The length is due solely to the fact that there are a total # of 9 lines that need to be changed for the animation as well as 3 subplots # that need initial set up. - - class SubplotAnimation(animation.TimedAnimation): - def __init__(self): fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) @@ -27,8 +24,7 @@ def __init__(self): ax1.set_ylabel('y') self.line1 = Line2D([], [], color='black') self.line1a = Line2D([], [], color='red', linewidth=2) - self.line1e = Line2D([], [], color='red', - marker='o', markeredgecolor='r') + self.line1e = Line2D([], [], color='red', marker='o', markeredgecolor='r') ax1.add_line(self.line1) ax1.add_line(self.line1a) ax1.add_line(self.line1e) @@ -40,8 +36,7 @@ def __init__(self): ax2.set_ylabel('z') self.line2 = Line2D([], [], color='black') self.line2a = Line2D([], [], color='red', linewidth=2) - self.line2e = Line2D([], [], color='red', - marker='o', markeredgecolor='r') + self.line2e = Line2D([], [], color='red', marker='o', markeredgecolor='r') ax2.add_line(self.line2) ax2.add_line(self.line2a) ax2.add_line(self.line2e) @@ -52,8 +47,7 @@ def __init__(self): ax3.set_ylabel('z') self.line3 = Line2D([], [], color='black') self.line3a = Line2D([], [], color='red', linewidth=2) - self.line3e = Line2D([], [], color='red', - marker='o', markeredgecolor='r') + self.line3e = Line2D([], [], color='red', marker='o', markeredgecolor='r') ax3.add_line(self.line3) ax3.add_line(self.line3a) ax3.add_line(self.line3e) @@ -81,19 +75,19 @@ def _draw_frame(self, framedata): self.line3e.set_data(self.x[head], self.z[head]) self._drawn_artists = [self.line1, self.line1a, self.line1e, - self.line2, self.line2a, self.line2e, - self.line3, self.line3a, self.line3e] + self.line2, self.line2a, self.line2e, + self.line3, self.line3a, self.line3e] def new_frame_seq(self): return iter(range(self.t.size)) def _init_draw(self): - lines = [self.line1, self.line1a, self.line1e, - self.line2, self.line2a, self.line2e, - self.line3, self.line3a, self.line3e] + lines = [self.line1, self.line1a, self.line1e, + self.line2, self.line2a, self.line2e, + self.line3, self.line3a, self.line3e] for l in lines: l.set_data([], []) ani = SubplotAnimation() -# ani.save('test_sub.mp4') +#ani.save('test_sub.mp4') plt.show() diff --git a/examples/animation/unchained.py b/examples/animation/unchained.py index 71cb69aecd12..0a41a6138429 100644 --- a/examples/animation/unchained.py +++ b/examples/animation/unchained.py @@ -44,7 +44,7 @@ ha="left", va="bottom", color="w", family="sans-serif", fontweight="bold", fontsize=16) - +# Update function def update(*args): # Shift all data to the right data[:, 1:] = data[:, :-1] diff --git a/examples/axes_grid/demo_axes_divider.py b/examples/axes_grid/demo_axes_divider.py index 40c1c457072c..df56d9f3f532 100644 --- a/examples/axes_grid/demo_axes_divider.py +++ b/examples/axes_grid/demo_axes_divider.py @@ -1,13 +1,12 @@ import matplotlib.pyplot as plt - def get_demo_image(): import numpy as np from matplotlib.cbook import get_sample_data f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 - return z, (-3, 4, -4, 3) + return z, (-3,4,-4,3) def demo_simple_image(ax): @@ -21,7 +20,7 @@ def demo_simple_image(ax): def demo_locatable_axes_hard(fig1): from mpl_toolkits.axes_grid1 \ - import SubplotDivider, LocatableAxes, Size + import SubplotDivider, LocatableAxes, Size divider = SubplotDivider(fig1, 2, 2, 2, aspect=True) @@ -31,9 +30,9 @@ def demo_locatable_axes_hard(fig1): # axes for colorbar ax_cb = LocatableAxes(fig1, divider.get_position()) - h = [Size.AxesX(ax), # main axes - Size.Fixed(0.05), # padding, 0.1 inch - Size.Fixed(0.2), # colorbar, 0.3 inch + h = [Size.AxesX(ax), # main axes + Size.Fixed(0.05), # padding, 0.1 inch + Size.Fixed(0.2), # colorbar, 0.3 inch ] v = [Size.AxesY(ax)] diff --git a/examples/axes_grid/demo_axes_grid.py b/examples/axes_grid/demo_axes_grid.py index 0bea8ee2a132..add8f29f7d72 100644 --- a/examples/axes_grid/demo_axes_grid.py +++ b/examples/axes_grid/demo_axes_grid.py @@ -1,23 +1,21 @@ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import AxesGrid - def get_demo_image(): import numpy as np from matplotlib.cbook import get_sample_data f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 - return z, (-3, 4, -4, 3) - + return z, (-3,4,-4,3) def demo_simple_grid(fig): """ A grid of 2x2 images with 0.05 inch pad between images and only the lower-left axes is labeled. """ - grid = AxesGrid(fig, 141, # similar to subplot(141) - nrows_ncols=(2, 2), + grid = AxesGrid(fig, 141, # similar to subplot(141) + nrows_ncols = (2, 2), axes_pad = 0.05, label_mode = "1", ) @@ -26,8 +24,7 @@ def demo_simple_grid(fig): for i in range(4): im = grid[i].imshow(Z, extent=extent, interpolation="nearest") - # This only affects axes in first column and second row as share_all = - # False. + # This only affects axes in first column and second row as share_all = False. grid.axes_llc.set_xticks([-2, 0, 2]) grid.axes_llc.set_yticks([-2, 0, 2]) @@ -36,8 +33,8 @@ def demo_grid_with_single_cbar(fig): """ A grid of 2x2 images with a single colorbar """ - grid = AxesGrid(fig, 142, # similar to subplot(142) - nrows_ncols=(2, 2), + grid = AxesGrid(fig, 142, # similar to subplot(142) + nrows_ncols = (2, 2), axes_pad = 0.0, share_all=True, label_mode = "L", @@ -53,7 +50,7 @@ def demo_grid_with_single_cbar(fig): for cax in grid.cbar_axes: cax.toggle_label(False) - + # This affects all axes as share_all = True. grid.axes_llc.set_xticks([-2, 0, 2]) grid.axes_llc.set_yticks([-2, 0, 2]) @@ -64,8 +61,8 @@ def demo_grid_with_each_cbar(fig): A grid of 2x2 images. Each image has its own colorbar. """ - grid = AxesGrid(F, 143, # similar to subplot(143) - nrows_ncols=(2, 2), + grid = AxesGrid(F, 143, # similar to subplot(143) + nrows_ncols = (2, 2), axes_pad = 0.1, label_mode = "1", share_all = True, @@ -86,15 +83,14 @@ def demo_grid_with_each_cbar(fig): grid.axes_llc.set_xticks([-2, 0, 2]) grid.axes_llc.set_yticks([-2, 0, 2]) - def demo_grid_with_each_cbar_labelled(fig): """ A grid of 2x2 images. Each image has its own colorbar. """ - grid = AxesGrid(F, 144, # similar to subplot(144) - nrows_ncols=(2, 2), - axes_pad = (0.45, 0.15), + grid = AxesGrid(F, 144, # similar to subplot(144) + nrows_ncols = (2, 2), + axes_pad = ( 0.45, 0.15), label_mode = "1", share_all = True, cbar_location="right", @@ -104,15 +100,15 @@ def demo_grid_with_each_cbar_labelled(fig): ) Z, extent = get_demo_image() - # Use a different colorbar range every time + # Use a different colorbar range every time limits = ((0, 1), (-2, 2), (-1.7, 1.4), (-1.5, 1)) for i in range(4): - im = grid[i].imshow(Z, extent=extent, interpolation="nearest", - vmin=limits[i][0], vmax=limits[i][1]) + im = grid[i].imshow(Z, extent=extent, interpolation="nearest", + vmin = limits[i][0], vmax = limits[i][1]) grid.cbar_axes[i].colorbar(im) for i, cax in enumerate(grid.cbar_axes): - cax.set_yticks((limits[i][0], limits[i][1])) + cax.set_yticks((limits[i][0], limits[i][1])) # This affects all axes because we set share_all = True. grid.axes_llc.set_xticks([-2, 0, 2]) @@ -131,3 +127,4 @@ def demo_grid_with_each_cbar_labelled(fig): plt.draw() plt.show() + diff --git a/examples/axes_grid/demo_axes_grid2.py b/examples/axes_grid/demo_axes_grid2.py index ad5c98ad38bc..41c8b5ef23aa 100644 --- a/examples/axes_grid/demo_axes_grid2.py +++ b/examples/axes_grid/demo_axes_grid2.py @@ -2,13 +2,12 @@ from mpl_toolkits.axes_grid1 import ImageGrid import numpy as np - def get_demo_image(): from matplotlib.cbook import get_sample_data f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 - return z, (-3, 4, -4, 3) + return z, (-3,4,-4,3) def add_inner_title(ax, title, loc, size=None, **kwargs): @@ -29,27 +28,27 @@ def add_inner_title(ax, title, loc, size=None, **kwargs): # prepare images Z, extent = get_demo_image() - ZS = [Z[i::3, :] for i in range(3)] - extent = extent[0], extent[1] / 3., extent[2], extent[3] + ZS = [Z[i::3,:] for i in range(3)] + extent = extent[0], extent[1]/3., extent[2], extent[3] # demo 1 : colorbar at each axes - grid = ImageGrid(F, 211, # similar to subplot(111) - nrows_ncols=(1, 3), - direction="row", - axes_pad = 0.05, - add_all=True, - label_mode = "1", - share_all = True, - cbar_location="top", - cbar_mode="each", - cbar_size="7%", - cbar_pad="1%", - ) + grid = ImageGrid(F, 211, # similar to subplot(111) + nrows_ncols = (1, 3), + direction="row", + axes_pad = 0.05, + add_all=True, + label_mode = "1", + share_all = True, + cbar_location="top", + cbar_mode="each", + cbar_size="7%", + cbar_pad="1%", + ) + for ax, z in zip(grid, ZS): - im = ax.imshow(z, origin="lower", extent=extent, - interpolation="nearest") + im = ax.imshow(z, origin="lower", extent=extent, interpolation="nearest") ax.cax.colorbar(im) for ax, im_title in zip(grid, ["Image 1", "Image 2", "Image 3"]): @@ -60,8 +59,8 @@ def add_inner_title(ax, title, loc, size=None, **kwargs): ax.cax.toggle_label(True) #axis = ax.cax.axis[ax.cax.orientation] #axis.label.set_text("counts s$^{-1}$") - # axis.label.set_size(10) - # axis.major_ticklabels.set_size(6) + #axis.label.set_size(10) + #axis.major_ticklabels.set_size(6) # changing the colorbar ticks grid[1].cax.set_xticks([-1, 0, 1]) @@ -70,10 +69,11 @@ def add_inner_title(ax, title, loc, size=None, **kwargs): grid[0].set_xticks([-2, 0]) grid[0].set_yticks([-2, 0, 2]) + # demo 2 : shared colorbar grid2 = ImageGrid(F, 212, - nrows_ncols=(1, 3), + nrows_ncols = (1, 3), direction="row", axes_pad = 0.05, add_all=True, diff --git a/examples/axes_grid/demo_axes_hbox_divider.py b/examples/axes_grid/demo_axes_hbox_divider.py index 692ca8454c3e..f63061ac45e7 100644 --- a/examples/axes_grid/demo_axes_hbox_divider.py +++ b/examples/axes_grid/demo_axes_hbox_divider.py @@ -3,10 +3,9 @@ from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider import mpl_toolkits.axes_grid1.axes_size as Size - def make_heights_equal(fig, rect, ax1, ax2, pad): # pad in inches - + h1, v1 = Size.AxesX(ax1), Size.AxesY(ax1) h2, v2 = Size.AxesX(ax2), Size.AxesY(ax2) @@ -17,22 +16,23 @@ def make_heights_equal(fig, rect, ax1, ax2, pad): horizontal=[h1, pad_h, h2], vertical=[v1, pad_v, v2]) + ax1.set_axes_locator(my_divider.new_locator(0)) ax2.set_axes_locator(my_divider.new_locator(2)) - + if __name__ == "__main__": - arr1 = np.arange(20).reshape((4, 5)) - arr2 = np.arange(20).reshape((5, 4)) + arr1 = np.arange(20).reshape((4,5)) + arr2 = np.arange(20).reshape((5,4)) - fig, (ax1, ax2) = plt.subplots(1, 2) + 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(fig, rect, ax1, ax2, pad=0.5) # pad in inches - + rect = 111 # subplot param for combined axes + make_heights_equal(fig, rect, ax1, ax2, pad=0.5) # pad in inches + for ax in [ax1, ax2]: ax.locator_params(nbins=4) @@ -47,3 +47,4 @@ def make_heights_equal(fig, rect, ax1, ax2, pad): bbox=dict(boxstyle="round, pad=1", fc="w")) plt.show() + diff --git a/examples/axes_grid/demo_axes_rgb.py b/examples/axes_grid/demo_axes_rgb.py index de9ca02ee0ff..b7374c2766d6 100644 --- a/examples/axes_grid/demo_axes_rgb.py +++ b/examples/axes_grid/demo_axes_rgb.py @@ -3,24 +3,24 @@ from mpl_toolkits.axes_grid1.axes_rgb import make_rgb_axes, RGBAxes - def get_demo_image(): from matplotlib.cbook import get_sample_data f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 - return z, (-3, 4, -4, 3) + return z, (-3,4,-4,3) + def get_rgb(): Z, extent = get_demo_image() - Z[Z < 0] = 0. - Z = Z / Z.max() + Z[Z<0] = 0. + Z = Z/Z.max() - R = Z[:13, :13] - G = Z[2:, 2:] - B = Z[:13, 2:] + R = Z[:13,:13] + G = Z[2:,2:] + B = Z[:13,2:] return R, G, B @@ -28,23 +28,24 @@ def get_rgb(): def make_cube(r, g, b): ny, nx = r.shape R = np.zeros([ny, nx, 3], dtype="d") - R[:, :, 0] = r + R[:,:,0] = r G = np.zeros_like(R) - G[:, :, 1] = g + G[:,:,1] = g B = np.zeros_like(R) - B[:, :, 2] = b + B[:,:,2] = b RGB = R + G + B return R, G, B, RGB + def demo_rgb(): 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) - # fig.add_axes(ax_b) + #fig.add_axes(ax_r) + #fig.add_axes(ax_g) + #fig.add_axes(ax_b) r, g, b = get_rgb() im_r, im_g, im_b, im_rgb = make_cube(r, g, b) @@ -55,11 +56,13 @@ def demo_rgb(): ax_b.imshow(im_b, **kwargs) + + def demo_rgb2(): fig = plt.figure(2) ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8], pad=0.0) - # fig.add_axes(ax) - # ax.add_RGB_to_figure() + #fig.add_axes(ax) + #ax.add_RGB_to_figure() r, g, b = get_rgb() kwargs = dict(origin="lower", interpolation="nearest") diff --git a/examples/axes_grid/demo_axisline_style.py b/examples/axes_grid/demo_axisline_style.py index 71a02797df7d..3d0b0d6f5dab 100644 --- a/examples/axes_grid/demo_axisline_style.py +++ b/examples/axes_grid/demo_axisline_style.py @@ -16,6 +16,6 @@ ax.axis[direction].set_visible(False) x = np.linspace(-0.5, 1., 100) - ax.plot(x, np.sin(x * np.pi)) + ax.plot(x, np.sin(x*np.pi)) plt.show() diff --git a/examples/axes_grid/demo_colorbar_with_inset_locator.py b/examples/axes_grid/demo_colorbar_with_inset_locator.py index 72a920b402c5..1085e45d95ee 100644 --- a/examples/axes_grid/demo_colorbar_with_inset_locator.py +++ b/examples/axes_grid/demo_colorbar_with_inset_locator.py @@ -5,17 +5,17 @@ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=[6, 3]) axins1 = inset_axes(ax1, - width="50%", # width = 10% of parent_bbox width - height="5%", # height : 50% + width="50%", # width = 10% of parent_bbox width + height="5%", # height : 50% loc=1) -im1 = ax1.imshow([[1, 2], [2, 3]]) -plt.colorbar(im1, cax=axins1, orientation="horizontal", ticks=[1, 2, 3]) +im1=ax1.imshow([[1,2],[2, 3]]) +plt.colorbar(im1, cax=axins1, orientation="horizontal", ticks=[1,2,3]) axins1.xaxis.set_ticks_position("bottom") axins = inset_axes(ax2, - width="5%", # width = 10% of parent_bbox width - height="50%", # height : 50% + width="5%", # width = 10% of parent_bbox width + height="50%", # height : 50% loc=3, bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax2.transAxes, @@ -26,8 +26,8 @@ # of the legend. you may want to play with the borderpad value and # the bbox_to_anchor coordinate. -im = ax2.imshow([[1, 2], [2, 3]]) -plt.colorbar(im, cax=axins, ticks=[1, 2, 3]) +im=ax2.imshow([[1,2],[2, 3]]) +plt.colorbar(im, cax=axins, ticks=[1,2,3]) plt.draw() plt.show() diff --git a/examples/axes_grid/demo_curvelinear_grid.py b/examples/axes_grid/demo_curvelinear_grid.py index 630efab87e8c..1a738b50d71d 100644 --- a/examples/axes_grid/demo_curvelinear_grid.py +++ b/examples/axes_grid/demo_curvelinear_grid.py @@ -4,11 +4,11 @@ import matplotlib.pyplot as plt import matplotlib.cbook as cbook -from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear +from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear from mpl_toolkits.axisartist import Subplot from mpl_toolkits.axisartist import SubplotHost, \ - ParasiteAxesAuxTrans + ParasiteAxesAuxTrans def curvelinear_test1(fig): @@ -18,11 +18,12 @@ def curvelinear_test1(fig): def tr(x, y): x, y = np.asarray(x), np.asarray(y) - return x, y - x + return x, y-x - def inv_tr(x, y): + def inv_tr(x,y): x, y = np.asarray(x), np.asarray(y) - return x, y + x + return x, y+x + grid_helper = GridHelperCurveLinear((tr, inv_tr)) @@ -41,16 +42,16 @@ def inv_tr(x, y): ax1.set_xlim(0, 10.) ax1.set_ylim(0, 10.) - ax1.axis["t"] = ax1.new_floating_axis(0, 3.) - ax1.axis["t2"] = ax1.new_floating_axis(1, 7.) + ax1.axis["t"]=ax1.new_floating_axis(0, 3.) + ax1.axis["t2"]=ax1.new_floating_axis(1, 7.) ax1.grid(True) -import mpl_toolkits.axisartist.angle_helper as angle_helper + +import mpl_toolkits.axisartist.angle_helper as angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D - def curvelinear_test2(fig): """ polar projection, but in a rectangular box. @@ -58,7 +59,7 @@ def curvelinear_test2(fig): # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree - tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() + tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes @@ -66,10 +67,10 @@ def curvelinear_test2(fig): # 20, 20 : number of sampling points along x, y direction extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, - lon_cycle=360, - lat_cycle=None, - lon_minmax=None, - lat_minmax=(0, np.inf), + lon_cycle = 360, + lat_cycle = None, + lon_minmax = None, + lat_minmax = (0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) @@ -88,6 +89,7 @@ def curvelinear_test2(fig): tick_formatter1=tick_formatter1 ) + ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper) # make ticklabels of right and top axis visible. @@ -95,12 +97,13 @@ def curvelinear_test2(fig): ax1.axis["top"].major_ticklabels.set_visible(True) # let right axis shows ticklabels for 1st coordinate (angle) - ax1.axis["right"].get_helper().nth_coord_ticks = 0 + ax1.axis["right"].get_helper().nth_coord_ticks=0 # let bottom axis shows ticklabels for 2nd coordinate (radius) - ax1.axis["bottom"].get_helper().nth_coord_ticks = 1 + ax1.axis["bottom"].get_helper().nth_coord_ticks=1 fig.add_subplot(ax1) + # A parasite axes with given transform ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") # note that ax2.transData == tr + ax1.transData @@ -125,3 +128,6 @@ def curvelinear_test2(fig): plt.draw() plt.show() + + + diff --git a/examples/axes_grid/demo_curvelinear_grid2.py b/examples/axes_grid/demo_curvelinear_grid2.py index 7db0c012757d..2d96044a2a70 100644 --- a/examples/axes_grid/demo_curvelinear_grid2.py +++ b/examples/axes_grid/demo_curvelinear_grid2.py @@ -3,11 +3,10 @@ import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid.grid_helper_curvelinear import GridHelperCurveLinear +from mpl_toolkits.axes_grid.grid_helper_curvelinear import GridHelperCurveLinear from mpl_toolkits.axes_grid.axislines import Subplot -import mpl_toolkits.axes_grid.angle_helper as angle_helper - +import mpl_toolkits.axes_grid.angle_helper as angle_helper def curvelinear_test1(fig): """ @@ -17,19 +16,18 @@ def curvelinear_test1(fig): def tr(x, y): sgn = np.sign(x) x, y = np.abs(np.asarray(x)), np.asarray(y) - return sgn * x ** .5, y + return sgn*x**.5, y - def inv_tr(x, y): + def inv_tr(x,y): sgn = np.sign(x) x, y = np.asarray(x), np.asarray(y) - return sgn * x ** 2, y + return sgn*x**2, y extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, - lon_cycle=None, - lat_cycle=None, - # (0, np.inf), - lon_minmax=None, - lat_minmax=None, + lon_cycle = None, + lat_cycle = None, + lon_minmax = None, #(0, np.inf), + lat_minmax = None, ) grid_helper = GridHelperCurveLinear((tr, inv_tr), @@ -43,8 +41,8 @@ def inv_tr(x, y): fig.add_subplot(ax1) - ax1.imshow(np.arange(25).reshape(5, 5), - vmax=50, cmap=plt.cm.gray_r, + ax1.imshow(np.arange(25).reshape(5,5), + vmax = 50, cmap=plt.cm.gray_r, interpolation="nearest", origin="lower") @@ -53,9 +51,13 @@ def inv_tr(x, y): grid_helper.grid_finder.grid_locator2._nbins = 6 + if 1: fig = plt.figure(1, figsize=(7, 4)) fig.clf() curvelinear_test1(fig) plt.show() + + + diff --git a/examples/axes_grid/demo_edge_colorbar.py b/examples/axes_grid/demo_edge_colorbar.py index 26f5a3017aa4..6e25d02a0d12 100644 --- a/examples/axes_grid/demo_edge_colorbar.py +++ b/examples/axes_grid/demo_edge_colorbar.py @@ -1,22 +1,21 @@ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import AxesGrid - def get_demo_image(): import numpy as np from matplotlib.cbook import get_sample_data f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 - return z, (-3, 4, -4, 3) + return z, (-3,4,-4,3) def demo_bottom_cbar(fig): """ A grid of 2x2 images with a colorbar for each column. """ - grid = AxesGrid(fig, 121, # similar to subplot(132) - nrows_ncols=(2, 2), + grid = AxesGrid(fig, 121, # similar to subplot(132) + nrows_ncols = (2, 2), axes_pad = 0.10, share_all=True, label_mode = "1", @@ -31,9 +30,9 @@ def demo_bottom_cbar(fig): cmaps = [plt.get_cmap("autumn"), plt.get_cmap("summer")] for i in range(4): im = grid[i].imshow(Z, extent=extent, interpolation="nearest", - cmap=cmaps[i // 2]) + cmap=cmaps[i//2]) if i % 2: - cbar = grid.cbar_axes[i // 2].colorbar(im) + cbar = grid.cbar_axes[i//2].colorbar(im) for cax in grid.cbar_axes: cax.toggle_label(True) @@ -49,8 +48,8 @@ def demo_right_cbar(fig): A grid of 2x2 images. Each row has its own colorbar. """ - grid = AxesGrid(F, 122, # similar to subplot(122) - nrows_ncols=(2, 2), + grid = AxesGrid(F, 122, # similar to subplot(122) + nrows_ncols = (2, 2), axes_pad = 0.10, label_mode = "1", share_all = True, @@ -63,9 +62,9 @@ def demo_right_cbar(fig): cmaps = [plt.get_cmap("spring"), plt.get_cmap("winter")] for i in range(4): im = grid[i].imshow(Z, extent=extent, interpolation="nearest", - cmap=cmaps[i // 2]) + cmap=cmaps[i//2]) if i % 2: - grid.cbar_axes[i // 2].colorbar(im) + grid.cbar_axes[i//2].colorbar(im) for cax in grid.cbar_axes: cax.toggle_label(True) @@ -76,6 +75,7 @@ def demo_right_cbar(fig): grid.axes_llc.set_yticks([-2, 0, 2]) + if 1: F = plt.figure(1, (5.5, 2.5)) @@ -86,3 +86,4 @@ def demo_right_cbar(fig): plt.draw() plt.show() + diff --git a/examples/axes_grid/demo_floating_axes.py b/examples/axes_grid/demo_floating_axes.py index d4a9de7a94a4..4ffb9ead058d 100644 --- a/examples/axes_grid/demo_floating_axes.py +++ b/examples/axes_grid/demo_floating_axes.py @@ -3,11 +3,10 @@ import mpl_toolkits.axisartist.floating_axes as floating_axes import numpy as np -import mpl_toolkits.axisartist.angle_helper as angle_helper +import mpl_toolkits.axisartist.angle_helper as angle_helper from matplotlib.projections import PolarAxes from mpl_toolkits.axisartist.grid_finder import FixedLocator, MaxNLocator, \ - DictFormatter - + DictFormatter def setup_axes1(fig, rect): """ @@ -15,8 +14,7 @@ def setup_axes1(fig, rect): """ tr = Affine2D().scale(2, 1).rotate_deg(30) - grid_helper = floating_axes.GridHelperCurveLinear( - tr, extremes=(0, 4, 0, 4)) + grid_helper = floating_axes.GridHelperCurveLinear(tr, extremes=(0, 4, 0, 4)) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) @@ -35,25 +33,26 @@ def setup_axes2(fig, rect): Note that the extreme values are swapped. """ + #tr_scale = Affine2D().scale(np.pi/180., 1.) + tr = PolarAxes.PolarTransform() pi = np.pi angle_ticks = [(0, r"$0$"), - (.25 * pi, r"$\frac{1}{4}\pi$"), - (.5 * pi, r"$\frac{1}{2}\pi$")] + (.25*pi, r"$\frac{1}{4}\pi$"), + (.5*pi, r"$\frac{1}{2}\pi$")] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(2) - grid_helper = floating_axes.GridHelperCurveLinear( - tr, - extremes=( - .5 * pi, 0, 2, 1), - grid_locator1=grid_locator1, - grid_locator2=grid_locator2, - tick_formatter1=tick_formatter1, - tick_formatter2=None) + grid_helper = floating_axes.GridHelperCurveLinear(tr, + extremes=(.5*pi, 0, 2, 1), + grid_locator1=grid_locator1, + grid_locator2=grid_locator2, + tick_formatter1=tick_formatter1, + tick_formatter2=None, + ) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) @@ -61,11 +60,11 @@ def setup_axes2(fig, rect): # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) - aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax - ax1.patch.zorder = 0.9 # but this has a side effect that the patch is - # drawn twice, and possibly over some other - # artists. So, we decrease the zorder a bit to - # prevent this. + aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax + ax1.patch.zorder=0.9 # but this has a side effect that the patch is + # drawn twice, and possibly over some other + # artists. So, we decrease the zorder a bit to + # prevent this. return ax1, aux_ax @@ -79,7 +78,7 @@ def setup_axes3(fig, rect): tr_rotate = Affine2D().translate(-95, 0) # scale degree to radians - tr_scale = Affine2D().scale(np.pi / 180., 1.) + tr_scale = Affine2D().scale(np.pi/180., 1.) tr = tr_rotate + tr_scale + PolarAxes.PolarTransform() @@ -88,16 +87,15 @@ def setup_axes3(fig, rect): grid_locator2 = MaxNLocator(3) - ra0, ra1 = 8. * 15, 14. * 15 + ra0, ra1 = 8.*15, 14.*15 cz0, cz1 = 0, 14000 grid_helper = floating_axes.GridHelperCurveLinear(tr, - extremes=( - ra0, ra1, cz0, cz1), - grid_locator1=grid_locator1, - grid_locator2=grid_locator2, - tick_formatter1=tick_formatter1, - tick_formatter2=None, - ) + extremes=(ra0, ra1, cz0, cz1), + grid_locator1=grid_locator1, + grid_locator2=grid_locator2, + tick_formatter1=tick_formatter1, + tick_formatter2=None, + ) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) @@ -115,18 +113,20 @@ def setup_axes3(fig, rect): ax1.axis["left"].label.set_text(r"cz [km$^{-1}$]") ax1.axis["top"].label.set_text(r"$\alpha_{1950}$") + # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) - aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax - ax1.patch.zorder = 0.9 # but this has a side effect that the patch is - # drawn twice, and possibly over some other - # artists. So, we decrease the zorder a bit to - # prevent this. + aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax + ax1.patch.zorder=0.9 # but this has a side effect that the patch is + # drawn twice, and possibly over some other + # artists. So, we decrease the zorder a bit to + # prevent this. return ax1, aux_ax + if 1: import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(8, 4)) @@ -134,21 +134,24 @@ def setup_axes3(fig, rect): ax1, aux_ax2 = setup_axes1(fig, 131) aux_ax2.bar([0, 1, 2, 3], [3, 2, 1, 3]) - - # theta = np.random.rand(10) #*.5*np.pi - # radius = np.random.rand(10) #+1. + + #theta = np.random.rand(10) #*.5*np.pi + #radius = np.random.rand(10) #+1. #aux_ax1.scatter(theta, radius) + ax2, aux_ax2 = setup_axes2(fig, 132) - theta = np.random.rand(10) * .5 * np.pi - radius = np.random.rand(10) + 1. + theta = np.random.rand(10)*.5*np.pi + radius = np.random.rand(10)+1. aux_ax2.scatter(theta, radius) + ax3, aux_ax3 = setup_axes3(fig, 133) - theta = (8 + np.random.rand(10) * (14 - 8)) * 15. # in degrees - radius = np.random.rand(10) * 14000. + theta = (8 + np.random.rand(10)*(14-8))*15. # in degrees + radius = np.random.rand(10)*14000. aux_ax3.scatter(theta, radius) plt.show() + diff --git a/examples/axes_grid/demo_floating_axis.py b/examples/axes_grid/demo_floating_axis.py index 4c823953e2a1..bc8dea6b2729 100644 --- a/examples/axes_grid/demo_floating_axis.py +++ b/examples/axes_grid/demo_floating_axis.py @@ -9,7 +9,7 @@ def curvelinear_test2(fig): """ global ax1 import numpy as np - import mpl_toolkits.axisartist.angle_helper as angle_helper + import mpl_toolkits.axisartist.angle_helper as angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D @@ -18,13 +18,13 @@ def curvelinear_test2(fig): from mpl_toolkits.axisartist import GridHelperCurveLinear # see demo_curvelinear_grid.py for details - tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() + tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform() extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, - lon_cycle=360, - lat_cycle=None, - lon_minmax=None, - lat_minmax=(0, np.inf), + lon_cycle = 360, + lat_cycle = None, + lon_minmax = None, + lat_minmax = (0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) @@ -37,6 +37,7 @@ def curvelinear_test2(fig): tick_formatter1=tick_formatter1 ) + ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) fig.add_subplot(ax1) @@ -66,3 +67,5 @@ def curvelinear_test2(fig): curvelinear_test2(fig) plt.show() + + diff --git a/examples/axes_grid/demo_imagegrid_aspect.py b/examples/axes_grid/demo_imagegrid_aspect.py index 79f7655753eb..5a4af10cd458 100644 --- a/examples/axes_grid/demo_imagegrid_aspect.py +++ b/examples/axes_grid/demo_imagegrid_aspect.py @@ -3,15 +3,15 @@ from mpl_toolkits.axes_grid1 import ImageGrid fig = plt.figure(1) -grid1 = ImageGrid(fig, 121, (2, 2), axes_pad=0.1, - aspect=True, share_all=True) +grid1 = ImageGrid(fig, 121, (2,2), axes_pad=0.1, + aspect=True, share_all=True) for i in [0, 1]: grid1[i].set_aspect(2) -grid2 = ImageGrid(fig, 122, (2, 2), axes_pad=0.1, - aspect=True, share_all=True) +grid2 = ImageGrid(fig, 122, (2,2), axes_pad=0.1, + aspect=True, share_all=True) for i in [1, 3]: diff --git a/examples/axes_grid/demo_parasite_axes2.py b/examples/axes_grid/demo_parasite_axes2.py index c7b187802221..2f73bb084cc0 100644 --- a/examples/axes_grid/demo_parasite_axes2.py +++ b/examples/axes_grid/demo_parasite_axes2.py @@ -15,9 +15,11 @@ par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) - + par2.axis["right"].toggle(all=True) + + host.set_xlim(0, 2) host.set_ylim(0, 2) @@ -42,4 +44,4 @@ plt.draw() plt.show() - # plt.savefig("Test") + #plt.savefig("Test") diff --git a/examples/axes_grid/inset_locator_demo.py b/examples/axes_grid/inset_locator_demo.py index 3fc9e975e23a..1a1f5d0e3784 100644 --- a/examples/axes_grid/inset_locator_demo.py +++ b/examples/axes_grid/inset_locator_demo.py @@ -5,13 +5,13 @@ def add_sizebar(ax, size): - asb = AnchoredSizeBar(ax.transData, - size, - str(size), - loc=8, - pad=0.1, borderpad=0.5, sep=5, - frameon=False) - ax.add_artist(asb) + asb = AnchoredSizeBar(ax.transData, + size, + str(size), + loc=8, + pad=0.1, borderpad=0.5, sep=5, + frameon=False) + ax.add_artist(asb) fig, (ax, ax2) = plt.subplots(1, 2, figsize=[5.5, 3]) @@ -20,8 +20,8 @@ def add_sizebar(ax, size): ax.set_aspect(1.) axins = inset_axes(ax, - width="30%", # width = 30% of parent_bbox - height=1., # height : 1 inch + width="30%", # width = 30% of parent_bbox + height=1., # height : 1 inch loc=3) plt.xticks(visible=False) @@ -31,7 +31,7 @@ def add_sizebar(ax, size): # second subplot ax2.set_aspect(1.) -axins = zoomed_inset_axes(ax2, 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) diff --git a/examples/axes_grid/inset_locator_demo2.py b/examples/axes_grid/inset_locator_demo2.py index 97e420694b64..211faa4bffd8 100644 --- a/examples/axes_grid/inset_locator_demo2.py +++ b/examples/axes_grid/inset_locator_demo2.py @@ -5,28 +5,27 @@ import numpy as np - def get_demo_image(): from matplotlib.cbook import get_sample_data import numpy as np f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 - return z, (-3, 4, -4, 3) + return z, (-3,4,-4,3) -fig, ax = plt.subplots(figsize=[5, 4]) +fig, ax = plt.subplots(figsize=[5,4]) # prepare the demo image Z, extent = get_demo_image() Z2 = np.zeros([150, 150], dtype="d") ny, nx = Z.shape -Z2[30:30 + ny, 30:30 + nx] = Z +Z2[30:30+ny, 30:30+nx] = Z # extent = [-3, 4, -4, 3] ax.imshow(Z2, extent=extent, interpolation="nearest", origin="lower") -axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6 +axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6 axins.imshow(Z2, extent=extent, interpolation="nearest", origin="lower") @@ -44,3 +43,4 @@ def get_demo_image(): plt.draw() plt.show() + diff --git a/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py b/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py index 053649c39c05..6a269a5c8f32 100644 --- a/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py +++ b/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py @@ -2,41 +2,42 @@ from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable -if __name__ == "__main__": +if __name__ == "__main__": + import matplotlib.pyplot as plt - def ex1(): plt.figure(1) - ax = plt.axes([0, 0, 1, 1]) + ax = plt.axes([0,0,1,1]) # ax = plt.subplot(111) ax.set_yticks([0.5]) ax.set_yticklabels(["very long label"]) make_axes_area_auto_adjustable(ax) + def ex2(): plt.figure(2) - ax1 = plt.axes([0, 0, 1, 0.5]) - ax2 = plt.axes([0, 0.5, 1, 0.5]) + ax1 = plt.axes([0,0,1,0.5]) + ax2 = plt.axes([0,0.5,1,0.5]) ax1.set_yticks([0.5]) ax1.set_yticklabels(["very long label"]) ax1.set_ylabel("Y label") - + ax2.set_title("Title") - make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2]) + make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2]) make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2]) def ex3(): fig = plt.figure(3) - ax1 = plt.axes([0, 0, 1, 1]) + ax1 = plt.axes([0,0,1,1]) divider = make_axes_locatable(ax1) - + ax2 = divider.new_horizontal("100%", pad=0.3, sharey=ax1) ax2.tick_params(labelleft="off") fig.add_axes(ax2) @@ -47,13 +48,13 @@ def ex3(): adjust_dirs=["right"]) divider.add_auto_adjustable_area(use_axes=[ax1, ax2], pad=0.1, adjust_dirs=["top", "bottom"]) - + ax1.set_yticks([0.5]) ax1.set_yticklabels(["very long label"]) ax2.set_title("Title") ax2.set_xlabel("X - Label") - + ex1() ex2() ex3() diff --git a/examples/axes_grid/parasite_simple2.py b/examples/axes_grid/parasite_simple2.py index a75b3600803b..136ffd2912bd 100644 --- a/examples/axes_grid/parasite_simple2.py +++ b/examples/axes_grid/parasite_simple2.py @@ -10,10 +10,10 @@ fig = plt.figure() -ax_kms = SubplotHost(fig, 1, 1, 1, aspect=1.) +ax_kms = SubplotHost(fig, 1,1,1, aspect=1.) # angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc -pm_to_kms = 1. / 206265. * 2300 * 3.085e18 / 3.15e7 / 1.e5 +pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5 aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.) ax_pm = ax_kms.twin(aux_trans) @@ -22,7 +22,7 @@ fig.add_subplot(ax_kms) for n, ds, dse, w, we in obs: - time = ((2007 + (10. + 4 / 30.) / 12) - 1988.5) + time = ((2007+(10. + 4/30.)/12)-1988.5) v = ds / time * pm_to_kms ve = dse / time * pm_to_kms ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k") diff --git a/examples/axes_grid/scatter_hist.py b/examples/axes_grid/scatter_hist.py index 6f0e1096668a..273ae5d9348c 100644 --- a/examples/axes_grid/scatter_hist.py +++ b/examples/axes_grid/scatter_hist.py @@ -7,7 +7,7 @@ y = np.random.randn(1000) -fig, axScatter = plt.subplots(figsize=(5.5, 5.5)) +fig, axScatter = plt.subplots(figsize=(5.5,5.5)) # the scatter plot: axScatter.scatter(x, y) @@ -26,8 +26,8 @@ # now determine nice limits by hand: binwidth = 0.25 -xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))]) -lim = (int(xymax / binwidth) + 1) * binwidth +xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] ) +lim = ( int(xymax/binwidth) + 1) * binwidth bins = np.arange(-lim, lim + binwidth, binwidth) axHistx.hist(x, bins=bins) @@ -37,12 +37,12 @@ # thus there is no need to manually adjust the xlim and ylim of these # axis. -# axHistx.axis["bottom"].major_ticklabels.set_visible(False) +#axHistx.axis["bottom"].major_ticklabels.set_visible(False) for tl in axHistx.get_xticklabels(): tl.set_visible(False) axHistx.set_yticks([0, 50, 100]) -# axHisty.axis["left"].major_ticklabels.set_visible(False) +#axHisty.axis["left"].major_ticklabels.set_visible(False) for tl in axHisty.get_yticklabels(): tl.set_visible(False) axHisty.set_xticks([0, 50, 100]) diff --git a/examples/axes_grid/simple_anchored_artists.py b/examples/axes_grid/simple_anchored_artists.py index 466f1a1730cb..8853534d23b3 100644 --- a/examples/axes_grid/simple_anchored_artists.py +++ b/examples/axes_grid/simple_anchored_artists.py @@ -17,8 +17,7 @@ def draw_text(ax): at2.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at2) - -def draw_circle(ax): # circle in the canvas coordinate +def draw_circle(ax): # circle in the canvas coordinate from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea from matplotlib.patches import Circle ada = AnchoredDrawingArea(20, 20, 0, 0, @@ -27,7 +26,6 @@ def draw_circle(ax): # circle in the canvas coordinate ada.da.add_artist(p) ax.add_artist(ada) - def draw_ellipse(ax): from mpl_toolkits.axes_grid1.anchored_artists import AnchoredEllipse # draw an ellipse of width=0.1, height=0.15 in the data coordinate @@ -36,12 +34,11 @@ def draw_ellipse(ax): ax.add_artist(ae) - def draw_sizebar(ax): from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar # draw a horizontal bar with length of 0.1 in Data coordinate # (ax.transData) with a label underneath. - asb = AnchoredSizeBar(ax.transData, + asb = AnchoredSizeBar(ax.transData, 0.1, r"1$^{\prime}$", loc=8, @@ -60,3 +57,5 @@ def draw_sizebar(ax): draw_sizebar(ax) plt.show() + + diff --git a/examples/axes_grid/simple_axesgrid.py b/examples/axes_grid/simple_axesgrid.py index b8c45f2aae6d..5038b4eee0b7 100644 --- a/examples/axes_grid/simple_axesgrid.py +++ b/examples/axes_grid/simple_axesgrid.py @@ -6,12 +6,12 @@ im.shape = 10, 10 fig = plt.figure(1, (4., 4.)) -grid = ImageGrid(fig, 111, # similar to subplot(111) - nrows_ncols=(2, 2), # creates 2x2 grid of axes - axes_pad=0.1, # pad between axes in inch. - ) +grid = ImageGrid(fig, 111, # similar to subplot(111) + nrows_ncols = (2, 2), # creates 2x2 grid of axes + axes_pad=0.1, # pad between axes in inch. + ) for i in range(4): - grid[i].imshow(im) # The AxesGrid object work as a list of axes. + grid[i].imshow(im) # The AxesGrid object work as a list of axes. plt.show() diff --git a/examples/axes_grid/simple_axesgrid2.py b/examples/axes_grid/simple_axesgrid2.py index f8b77b6b924b..efd7fb45a9bd 100644 --- a/examples/axes_grid/simple_axesgrid2.py +++ b/examples/axes_grid/simple_axesgrid2.py @@ -1,33 +1,31 @@ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid - def get_demo_image(): import numpy as np from matplotlib.cbook import get_sample_data f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 - return z, (-3, 4, -4, 3) + return z, (-3,4,-4,3) F = plt.figure(1, (5.5, 3.5)) -grid = ImageGrid(F, 111, # similar to subplot(111) - nrows_ncols=(1, 3), - axes_pad = 0.1, - add_all=True, - label_mode = "L", - ) +grid = ImageGrid(F, 111, # similar to subplot(111) + nrows_ncols = (1, 3), + axes_pad = 0.1, + add_all=True, + label_mode = "L", + ) -Z, extent = get_demo_image() # demo image +Z, extent = get_demo_image() # demo image -im1 = Z -im2 = Z[:, :10] -im3 = Z[:, 10:] +im1=Z +im2=Z[:,:10] +im3=Z[:,10:] vmin, vmax = Z.min(), Z.max() for i, im in enumerate([im1, im2, im3]): ax = grid[i] - ax.imshow(im, origin="lower", vmin=vmin, - vmax=vmax, interpolation="nearest") + ax.imshow(im, origin="lower", vmin=vmin, vmax=vmax, interpolation="nearest") plt.draw() plt.show() diff --git a/examples/axes_grid/simple_axisline4.py b/examples/axes_grid/simple_axisline4.py index 0fcfc5116bc9..3b2c675666b6 100644 --- a/examples/axes_grid/simple_axisline4.py +++ b/examples/axes_grid/simple_axisline4.py @@ -4,11 +4,11 @@ import numpy as np ax = host_subplot(111, axes_class=AA.Axes) -xx = np.arange(0, 2 * np.pi, 0.01) +xx = np.arange(0, 2*np.pi, 0.01) ax.plot(xx, np.sin(xx)) -ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis -ax2.set_xticks([0., .5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi]) +ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis +ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi]) ax2.set_xticklabels(["$0$", r"$\frac{1}{2}\pi$", r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"]) @@ -16,3 +16,4 @@ plt.draw() plt.show() + diff --git a/examples/color/color_cycle_demo.py b/examples/color/color_cycle_demo.py index c0bbc42e2fbb..b453de4c1aed 100644 --- a/examples/color/color_cycle_demo.py +++ b/examples/color/color_cycle_demo.py @@ -12,12 +12,12 @@ import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi) -offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False) +offsets = np.linspace(0, 2*np.pi, 4, endpoint=False) # Create array with shifted-sine curve along each column yy = np.transpose([np.sin(x + phi) for phi in offsets]) plt.rc('lines', linewidth=4) -fig, (ax0, ax1) = plt.subplots(nrows=2) +fig, (ax0, ax1) = plt.subplots(nrows=2) plt.rc('axes', color_cycle=['r', 'g', 'b', 'y']) ax0.plot(yy) @@ -30,3 +30,5 @@ # Tweak spacing between subplots to prevent labels from overlapping plt.subplots_adjust(hspace=0.3) plt.show() + + diff --git a/examples/color/colormaps_reference.py b/examples/color/colormaps_reference.py index 5bc4cb1cdd85..111201a7970b 100644 --- a/examples/color/colormaps_reference.py +++ b/examples/color/colormaps_reference.py @@ -59,7 +59,6 @@ gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) - def plot_color_gradients(cmap_category, cmap_list): fig, axes = plt.subplots(nrows=nrows) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99) @@ -69,7 +68,7 @@ def plot_color_gradients(cmap_category, cmap_list): ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 - y_text = pos[1] + pos[3] / 2. + y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10) # Turn off *all* ticks & spines, not just the ones with colormaps. diff --git a/examples/color/named_colors.py b/examples/color/named_colors.py index 14a1dde90371..8567c0907864 100644 --- a/examples/color/named_colors.py +++ b/examples/color/named_colors.py @@ -41,7 +41,7 @@ ncols = 3 nrows = int(np.ceil(1. * n / ncols)) -fig = plt.figure(figsize=(ncols * 5, nrows * 4)) +fig = plt.figure(figsize=(ncols*5, nrows*4)) for i, (name, color) in enumerate(sorted_colors): ax = fig.add_subplot(nrows, ncols, i + 1) ax.text(0.55, 0.5, name, fontsize=12, diff --git a/examples/pylab_examples/tricontour_demo.py b/examples/pylab_examples/tricontour_demo.py index 4d188c100265..c0c266c1ce51 100644 --- a/examples/pylab_examples/tricontour_demo.py +++ b/examples/pylab_examples/tricontour_demo.py @@ -45,7 +45,7 @@ # the three points that make up the triangle, ordered in either a clockwise or # anticlockwise manner. -xy = np.degrees([ +xy = np.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], [-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919], @@ -65,6 +65,8 @@ [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872], [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933], [-0.077, 0.990], [-0.059, 0.993]]) +x = xy[:, 0]*180/3.14159 +y = xy[:, 1]*180/3.14159 x0 = -5 y0 = 52 z = np.exp(-0.01*((x-x0)*(x-x0) + (y-y0)*(y-y0))) diff --git a/examples/pylab_examples/tripcolor_demo.py b/examples/pylab_examples/tripcolor_demo.py index c872714f78fa..c2e89e122373 100644 --- a/examples/pylab_examples/tripcolor_demo.py +++ b/examples/pylab_examples/tripcolor_demo.py @@ -52,7 +52,7 @@ # the three points that make up the triangle, ordered in either a clockwise or # anticlockwise manner. -xy = np.degrees([ +xy = np.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], [-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919], @@ -72,6 +72,8 @@ [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872], [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933], [-0.077, 0.990], [-0.059, 0.993]]) +x = xy[:, 0]*180/3.14159 +y = xy[:, 1]*180/3.14159 triangles = np.asarray([ [67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64], diff --git a/examples/pylab_examples/triplot_demo.py b/examples/pylab_examples/triplot_demo.py index f314d95dd51d..84dcb4a76b02 100644 --- a/examples/pylab_examples/triplot_demo.py +++ b/examples/pylab_examples/triplot_demo.py @@ -43,7 +43,7 @@ # the three points that make up the triangle, ordered in either a clockwise or # anticlockwise manner. -xy = np.degrees([ +xy = np.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], [-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919], @@ -63,6 +63,8 @@ [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872], [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933], [-0.077, 0.990], [-0.059, 0.993]]) +x = xy[:, 0]*180/3.14159 +y = xy[:, 1]*180/3.14159 triangles = np.asarray([ [67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64], diff --git a/examples/units/annotate_with_units.py b/examples/units/annotate_with_units.py index 15960f0b73af..19a99c3b2187 100644 --- a/examples/units/annotate_with_units.py +++ b/examples/units/annotate_with_units.py @@ -3,21 +3,22 @@ fig, ax = plt.subplots() -ax.annotate("Note 01", [0.5 * cm, 0.5 * cm]) +ax.annotate( "Note 01", [0.5*cm, 0.5*cm] ) # xy and text both unitized -ax.annotate('local max', xy=(3 * cm, 1 * cm), xycoords='data', - xytext=(0.8 * cm, 0.95 * cm), textcoords='data', +ax.annotate('local max', xy=(3*cm, 1*cm), xycoords='data', + xytext=(0.8*cm, 0.95*cm), textcoords='data', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='right', verticalalignment='top') # mixing units w/ nonunits -ax.annotate('local max', xy=(3 * cm, 1 * cm), xycoords='data', +ax.annotate('local max', xy=(3*cm, 1*cm), xycoords='data', xytext=(0.8, 0.95), textcoords='axes fraction', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='right', verticalalignment='top') -ax.set_xlim(0 * cm, 4 * cm) -ax.set_ylim(0 * cm, 4 * cm) +ax.set_xlim(0*cm, 4*cm) +ax.set_ylim(0*cm, 4*cm) plt.show() + diff --git a/examples/units/ellipse_with_units.py b/examples/units/ellipse_with_units.py index 6f033465a0b6..ab522b92ac00 100644 --- a/examples/units/ellipse_with_units.py +++ b/examples/units/ellipse_with_units.py @@ -12,11 +12,11 @@ width, height = 1e-1*cm, 3e-1*cm angle = -30 -theta = np.radians(np.arange(0.0, 360.0, 1.0)) +theta = np.arange(0.0, 360.0, 1.0)*np.pi/180.0 x = 0.5 * width * np.cos(theta) y = 0.5 * height * np.sin(theta) -rtheta = np.radians(angle) +rtheta = angle*np.pi/180. R = np.array([ [np.cos(rtheta), -np.sin(rtheta)], [np.sin(rtheta), np.cos(rtheta)], diff --git a/examples/user_interfaces/svg_histogram.py b/examples/user_interfaces/svg_histogram.py index 2f4bb37c84d3..d1097353a97b 100755 --- a/examples/user_interfaces/svg_histogram.py +++ b/examples/user_interfaces/svg_histogram.py @@ -40,10 +40,12 @@ plt.rcParams['svg.embed_char_paths'] = 'none' -# Apparently, this `register_namespace` method works only with +# Apparently, this `register_namespace` method works only with # python 2.7 and up and is necessary to avoid garbling the XML name # space with ns0. -ET.register_namespace("", "http://www.w3.org/2000/svg") +ET.register_namespace("","http://www.w3.org/2000/svg") + + # --- Create histogram, legend and title --- @@ -51,30 +53,30 @@ r = np.random.randn(100) r1 = r + 1 labels = ['Rabbits', 'Frogs'] -H = plt.hist([r, r1], label=labels) +H = plt.hist([r,r1], label=labels) containers = H[-1] leg = plt.legend(frameon=False) plt.title("""From a web browser, click on the legend marker to toggle the corresponding histogram.""") -# --- Add ids to the svg objects we'll modify +# --- Add ids to the svg objects we'll modify hist_patches = {} for ic, c in enumerate(containers): - hist_patches['hist_%d' % ic] = [] + hist_patches['hist_%d'%ic] = [] for il, element in enumerate(c): - element.set_gid('hist_%d_patch_%d' % (ic, il)) - hist_patches['hist_%d' % ic].append('hist_%d_patch_%d' % (ic, il)) + element.set_gid('hist_%d_patch_%d'%(ic, il)) + hist_patches['hist_%d'%ic].append('hist_%d_patch_%d'%(ic,il)) -# Set ids for the legend patches +# Set ids for the legend patches for i, t in enumerate(leg.get_patches()): - t.set_gid('leg_patch_%d' % i) + t.set_gid('leg_patch_%d'%i) # Set ids for the text patches for i, t in enumerate(leg.get_texts()): - t.set_gid('leg_text_%d' % i) - + t.set_gid('leg_text_%d'%i) + # Save SVG in a fake file object. f = StringIO() plt.savefig(f, format="svg") @@ -85,23 +87,23 @@ # --- Add interactivity --- -# Add attributes to the patch objects. +# Add attributes to the patch objects. for i, t in enumerate(leg.get_patches()): - el = xmlid['leg_patch_%d' % i] + el = xmlid['leg_patch_%d'%i] el.set('cursor', 'pointer') el.set('onclick', "toggle_hist(this)") - -# Add attributes to the text objects. + +# Add attributes to the text objects. for i, t in enumerate(leg.get_texts()): - el = xmlid['leg_text_%d' % i] + el = xmlid['leg_text_%d'%i] el.set('cursor', 'pointer') el.set('onclick', "toggle_hist(this)") - -# Create script defining the function `toggle_hist`. -# We create a global variable `container` that stores the patches id -# belonging to each histogram. Then a function "toggle_element" sets the + +# Create script defining the function `toggle_hist`. +# We create a global variable `container` that stores the patches id +# belonging to each histogram. Then a function "toggle_element" sets the # visibility attribute of all patches of each histogram and the opacity -# of the marker itself. +# of the marker itself. script = """ -""" % json.dumps(hist_patches) +"""%json.dumps(hist_patches) # Add a transition effect css = tree.getchildren()[0][0] -css.text = css.text + \ - "g {-webkit-transition:opacity 0.4s ease-out;-moz-transition:opacity 0.4s ease-out;}" - +css.text = css.text + "g {-webkit-transition:opacity 0.4s ease-out;-moz-transition:opacity 0.4s ease-out;}" + # Insert the script and save to file. tree.insert(0, ET.XML(script)) ET.ElementTree(tree).write("svg_histogram.svg") + + + diff --git a/examples/user_interfaces/svg_tooltip.py b/examples/user_interfaces/svg_tooltip.py index d45474b3d51c..6ec48307b4ab 100644 --- a/examples/user_interfaces/svg_tooltip.py +++ b/examples/user_interfaces/svg_tooltip.py @@ -26,47 +26,44 @@ import xml.etree.ElementTree as ET from StringIO import StringIO -ET.register_namespace("", "http://www.w3.org/2000/svg") +ET.register_namespace("","http://www.w3.org/2000/svg") fig, ax = plt.subplots() # Create patches to which tooltips will be assigned. -circle = plt.Circle((0, 0), 5, fc='blue') +circle = plt.Circle((0,0), 5, fc='blue') rect = plt.Rectangle((-5, 10), 10, 5, fc='green') ax.add_patch(circle) ax.add_patch(rect) # Create the tooltips -circle_tip = ax.annotate('This is a blue circle.', - xy=(0, 0), - xytext=(30, -30), - textcoords='offset points', - color='w', - ha='left', - bbox=dict( - boxstyle='round,pad=.5', fc=(.1, .1, .1, .92), - ec=(1., 1., 1.), lw=1, zorder=1), - ) - -rect_tip = ax.annotate('This is a green rectangle.', - xy=(-5, 10), - xytext=(30, 40), - textcoords='offset points', - color='w', - ha='left', - bbox=dict(boxstyle='round,pad=.5', fc=(.1, .1, .1, .92), - ec=(1., 1., 1.), lw=1, zorder=1), - ) - - -# Set id for the patches +circle_tip = ax.annotate('This is a blue circle.', + xy=(0,0), + xytext=(30,-30), + textcoords='offset points', + color='w', + ha='left', + bbox=dict(boxstyle='round,pad=.5', fc=(.1,.1,.1,.92), ec=(1.,1.,1.), lw=1, zorder=1), + ) + +rect_tip = ax.annotate('This is a green rectangle.', + xy=(-5,10), + xytext=(30,40), + textcoords='offset points', + color='w', + ha='left', + bbox=dict(boxstyle='round,pad=.5', fc=(.1,.1,.1,.92), ec=(1.,1.,1.), lw=1, zorder=1), + ) + + +# Set id for the patches for i, t in enumerate(ax.patches): - t.set_gid('patch_%d' % i) + t.set_gid('patch_%d'%i) # Set id for the annotations for i, t in enumerate(ax.texts): - t.set_gid('tooltip_%d' % i) + t.set_gid('tooltip_%d'%i) # Save the figure in a fake file object @@ -85,12 +82,12 @@ # Hide the tooltips for i, t in enumerate(ax.texts): - el = xmlid['tooltip_%d' % i] + el = xmlid['tooltip_%d'%i] el.set('visibility', 'hidden') -# Assign onmouseover and onmouseout callbacks to patches. +# Assign onmouseover and onmouseout callbacks to patches. for i, t in enumerate(ax.patches): - el = xmlid['patch_%d' % i] + el = xmlid['patch_%d'%i] el.set('onmouseover', "ShowTooltip(this)") el.set('onmouseout', "HideTooltip(this)") diff --git a/examples/user_interfaces/wxcursor_demo.py b/examples/user_interfaces/wxcursor_demo.py index ec48cb034a54..4d610ffc44d8 100644 --- a/examples/user_interfaces/wxcursor_demo.py +++ b/examples/user_interfaces/wxcursor_demo.py @@ -12,28 +12,26 @@ import wx - class CanvasFrame(wx.Frame): def __init__(self, ): - wx.Frame.__init__(self, None, -1, - 'CanvasFrame', size=(550, 350)) + wx.Frame.__init__(self,None,-1, + 'CanvasFrame',size=(550,350)) self.SetBackgroundColour(wx.NamedColour("WHITE")) self.figure = Figure() self.axes = self.figure.add_subplot(111) - t = arange(0.0, 3.0, 0.01) - s = sin(2 * pi * t) + t = arange(0.0,3.0,0.01) + s = sin(2*pi*t) - self.axes.plot(t, s) + self.axes.plot(t,s) self.axes.set_xlabel('t') self.axes.set_ylabel('sin(t)') self.figure_canvas = FigureCanvas(self, -1, self.figure) # Note that event is a MplEvent - self.figure_canvas.mpl_connect( - 'motion_notify_event', self.UpdateStatusBar) + self.figure_canvas.mpl_connect('motion_notify_event', self.UpdateStatusBar) self.figure_canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor) self.sizer = wx.BoxSizer(wx.VERTICAL) @@ -55,10 +53,9 @@ def ChangeCursor(self, event): def UpdateStatusBar(self, event): if event.inaxes: x, y = event.xdata, event.ydata - self.statusBar.SetStatusText(("x= " + str(x) + - " y=" + str(y)), - 0) - + self.statusBar.SetStatusText(( "x= " + str(x) + + " y=" +str(y) ), + 0) class App(wx.App): @@ -69,6 +66,6 @@ def OnInit(self): frame.Show(True) return True -if __name__ == '__main__': +if __name__=='__main__': app = App(0) app.MainLoop() diff --git a/examples/widgets/buttons.py b/examples/widgets/buttons.py index ada6debdd19b..d5695e6b9436 100644 --- a/examples/widgets/buttons.py +++ b/examples/widgets/buttons.py @@ -8,24 +8,23 @@ 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) +s = np.sin(2*np.pi*freqs[0]*t) l, = plt.plot(t, s, lw=2) class Index: ind = 0 - def next(self, event): self.ind += 1 i = self.ind % len(freqs) - ydata = np.sin(2 * np.pi * freqs[i] * t) + ydata = np.sin(2*np.pi*freqs[i]*t) l.set_ydata(ydata) plt.draw() def prev(self, event): self.ind -= 1 i = self.ind % len(freqs) - ydata = np.sin(2 * np.pi * freqs[i] * t) + ydata = np.sin(2*np.pi*freqs[i]*t) l.set_ydata(ydata) plt.draw() @@ -38,3 +37,4 @@ def prev(self, event): bprev.on_clicked(callback.prev) plt.show() + diff --git a/examples/widgets/check_buttons.py b/examples/widgets/check_buttons.py index f687b4a57c36..843bad9abd19 100644 --- a/examples/widgets/check_buttons.py +++ b/examples/widgets/check_buttons.py @@ -3,9 +3,9 @@ from matplotlib.widgets import CheckButtons t = np.arange(0.0, 2.0, 0.01) -s0 = np.sin(2 * np.pi * t) -s1 = np.sin(4 * np.pi * t) -s2 = np.sin(6 * np.pi * t) +s0 = np.sin(2*np.pi*t) +s1 = np.sin(4*np.pi*t) +s2 = np.sin(6*np.pi*t) fig, ax = plt.subplots() l0, = ax.plot(t, s0, visible=False, lw=2) @@ -16,14 +16,10 @@ rax = plt.axes([0.05, 0.4, 0.1, 0.15]) check = CheckButtons(rax, ('2 Hz', '4 Hz', '6 Hz'), (False, True, True)) - def func(label): - if label == '2 Hz': - l0.set_visible(not l0.get_visible()) - elif label == '4 Hz': - l1.set_visible(not l1.get_visible()) - elif label == '6 Hz': - l2.set_visible(not l2.get_visible()) + if label == '2 Hz': l0.set_visible(not l0.get_visible()) + elif label == '4 Hz': l1.set_visible(not l1.get_visible()) + elif label == '6 Hz': l2.set_visible(not l2.get_visible()) plt.draw() check.on_clicked(func) diff --git a/examples/widgets/cursor.py b/examples/widgets/cursor.py index 1e78c9a335a6..0e5d30e141e0 100644 --- a/examples/widgets/cursor.py +++ b/examples/widgets/cursor.py @@ -8,12 +8,12 @@ fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, axisbg='#FFFFCC') -x, y = 4 * (np.random.rand(2, 100) - .5) +x, y = 4*(np.random.rand(2, 100)-.5) ax.plot(x, y, 'o') ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) # set useblit = True on gtkagg for enhanced performance -cursor = Cursor(ax, useblit=True, color='red', linewidth=2) +cursor = Cursor(ax, useblit=True, color='red', linewidth=2 ) plt.show() diff --git a/examples/widgets/lasso_selector_demo.py b/examples/widgets/lasso_selector_demo.py index 4c0fd1558f16..b842d0093a58 100644 --- a/examples/widgets/lasso_selector_demo.py +++ b/examples/widgets/lasso_selector_demo.py @@ -13,7 +13,6 @@ class SelectFromCollection(object): - """Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool highlights @@ -35,7 +34,6 @@ class SelectFromCollection(object): To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to `alpha_other`. """ - def __init__(self, ax, collection, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection diff --git a/examples/widgets/menu.py b/examples/widgets/menu.py index a8e7ebc168de..062cd57cb061 100644 --- a/examples/widgets/menu.py +++ b/examples/widgets/menu.py @@ -10,7 +10,6 @@ class ItemProperties: - def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow', alpha=1.0): self.fontsize = fontsize @@ -21,12 +20,10 @@ def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow', self.labelcolor_rgb = colors.colorConverter.to_rgb(labelcolor) self.bgcolor_rgb = colors.colorConverter.to_rgb(bgcolor) - class MenuItem(artist.Artist): parser = mathtext.MathTextParser("Bitmap") padx = 5 pady = 5 - def __init__(self, fig, labelstr, props=None, hoverprops=None, on_select=None): artist.Artist.__init__(self) @@ -43,26 +40,28 @@ def __init__(self, fig, labelstr, props=None, hoverprops=None, self.props = props self.hoverprops = hoverprops + self.on_select = on_select x, self.depth = self.parser.to_mask( labelstr, fontsize=props.fontsize, dpi=fig.dpi) - if props.fontsize != hoverprops.fontsize: + if props.fontsize!=hoverprops.fontsize: raise NotImplementedError( - 'support for different font sizes not implemented') + 'support for different font sizes not implemented') + self.labelwidth = x.shape[1] self.labelheight = x.shape[0] self.labelArray = np.zeros((x.shape[0], x.shape[1], 4)) - self.labelArray[:, :, -1] = x / 255. + self.labelArray[:, :, -1] = x/255. self.label = image.FigureImage(fig, origin='upper') self.label.set_array(self.labelArray) # we'll update these later - self.rect = patches.Rectangle((0, 0), 1, 1) + self.rect = patches.Rectangle((0,0), 1,1) self.set_hover_props(False) @@ -83,8 +82,8 @@ def set_extent(self, x, y, w, h): self.rect.set_width(w) self.rect.set_height(h) - self.label.ox = x + self.padx - self.label.oy = y - self.depth + self.pady / 2. + self.label.ox = x+self.padx + self.label.oy = y-self.depth+self.pady/2. self.rect._update_patch_transform() self.hover = False @@ -108,17 +107,17 @@ def set_hover_props(self, b): def set_hover(self, event): 'check the hover status of event and return true if status is changed' - b, junk = self.rect.contains(event) + b,junk = self.rect.contains(event) changed = (b != self.hover) if changed: self.set_hover_props(b) + self.hover = b return changed - class Menu: def __init__(self, fig, menuitems): @@ -131,23 +130,27 @@ def __init__(self, fig, menuitems): maxw = max([item.labelwidth for item in menuitems]) maxh = max([item.labelheight for item in menuitems]) - totalh = self.numitems * maxh + (self.numitems + 1) * 2 * MenuItem.pady + + totalh = self.numitems*maxh + (self.numitems+1)*2*MenuItem.pady + x0 = 100 y0 = 400 - width = maxw + 2 * MenuItem.padx - height = maxh + MenuItem.pady + width = maxw + 2*MenuItem.padx + height = maxh+MenuItem.pady for item in menuitems: left = x0 - bottom = y0 - maxh - MenuItem.pady + bottom = y0-maxh-MenuItem.pady + item.set_extent(left, bottom, width, height) fig.artists.append(item) y0 -= maxh + MenuItem.pady + fig.canvas.mpl_connect('motion_notify_event', self.on_move) def on_move(self, event): diff --git a/examples/widgets/multicursor.py b/examples/widgets/multicursor.py index 7c48455b29e5..f6c5a36bff80 100644 --- a/examples/widgets/multicursor.py +++ b/examples/widgets/multicursor.py @@ -3,8 +3,8 @@ from matplotlib.widgets import MultiCursor t = np.arange(0.0, 2.0, 0.01) -s1 = np.sin(2 * np.pi * t) -s2 = np.sin(4 * np.pi * t) +s1 = np.sin(2*np.pi*t) +s2 = np.sin(4*np.pi*t) fig = plt.figure() ax1 = fig.add_subplot(211) ax1.plot(t, s1) diff --git a/examples/widgets/radio_buttons.py b/examples/widgets/radio_buttons.py index 97fc867dcc18..43c5e986b2d2 100644 --- a/examples/widgets/radio_buttons.py +++ b/examples/widgets/radio_buttons.py @@ -3,9 +3,9 @@ from matplotlib.widgets import RadioButtons t = np.arange(0.0, 2.0, 0.01) -s0 = np.sin(2 * np.pi * t) -s1 = np.sin(4 * np.pi * t) -s2 = np.sin(8 * np.pi * t) +s0 = np.sin(2*np.pi*t) +s1 = np.sin(4*np.pi*t) +s2 = np.sin(8*np.pi*t) fig, ax = plt.subplots() l, = ax.plot(t, s0, lw=2, color='red') @@ -14,10 +14,8 @@ axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.05, 0.7, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz')) - - def hzfunc(label): - hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2} + hzdict = {'2 Hz':s0, '4 Hz':s1, '8 Hz':s2} ydata = hzdict[label] l.set_ydata(ydata) plt.draw() @@ -25,8 +23,6 @@ def hzfunc(label): rax = plt.axes([0.05, 0.4, 0.15, 0.15], axisbg=axcolor) radio2 = RadioButtons(rax, ('red', 'blue', 'green')) - - def colorfunc(label): l.set_color(label) plt.draw() @@ -34,8 +30,6 @@ def colorfunc(label): rax = plt.axes([0.05, 0.1, 0.15, 0.15], axisbg=axcolor) radio3 = RadioButtons(rax, ('-', '--', '-.', 'steps', ':')) - - def stylefunc(label): l.set_linestyle(label) plt.draw() diff --git a/examples/widgets/rectangle_selector.py b/examples/widgets/rectangle_selector.py index 7ed0149aec14..fa21a30d23df 100644 --- a/examples/widgets/rectangle_selector.py +++ b/examples/widgets/rectangle_selector.py @@ -12,15 +12,12 @@ import numpy as np import matplotlib.pyplot as plt - def line_select_callback(eclick, erelease): 'eclick and erelease are the press and release events' x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print ("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2)) - print (" The button you used were: %s %s" % - (eclick.button, erelease.button)) - + print (" The button you used were: %s %s" % (eclick.button, erelease.button)) def toggle_selector(event): print (' Key pressed.') @@ -36,17 +33,16 @@ def toggle_selector(event): N = 100000 # If N is large one can see x = np.linspace(0.0, 10.0, N) # improvement by use blitting! -plt.plot(x, +np.sin(.2 * np.pi * x), lw=3.5, c='b', alpha=.7) # plot something -plt.plot(x, +np.cos(.2 * np.pi * x), lw=3.5, c='r', alpha=.5) -plt.plot(x, -np.sin(.2 * np.pi * x), lw=3.5, c='g', alpha=.3) +plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something +plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5) +plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3) print ("\n click --> release") # drawtype is 'box' or 'line' or 'none' toggle_selector.RS = RectangleSelector(current_ax, line_select_callback, drawtype='box', useblit=True, - # don't use middle button - button=[1, 3], + button=[1,3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels') plt.connect('key_press_event', toggle_selector) diff --git a/examples/widgets/slider_demo.py b/examples/widgets/slider_demo.py index 4755adba3c79..c75cf92681af 100644 --- a/examples/widgets/slider_demo.py +++ b/examples/widgets/slider_demo.py @@ -7,30 +7,27 @@ t = np.arange(0.0, 1.0, 0.001) a0 = 5 f0 = 3 -s = a0 * np.sin(2 * np.pi * f0 * t) -l, = plt.plot(t, s, lw=2, color='red') +s = a0*np.sin(2*np.pi*f0*t) +l, = plt.plot(t,s, lw=2, color='red') plt.axis([0, 1, -10, 10]) axcolor = 'lightgoldenrodyellow' axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) -axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) +axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0) samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0) - def update(val): amp = samp.val freq = sfreq.val - l.set_ydata(amp * np.sin(2 * np.pi * freq * t)) + l.set_ydata(amp*np.sin(2*np.pi*freq*t)) fig.canvas.draw_idle() sfreq.on_changed(update) samp.on_changed(update) resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') - - def reset(event): sfreq.reset() samp.reset() @@ -38,8 +35,6 @@ def reset(event): rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) - - def colorfunc(label): l.set_color(label) fig.canvas.draw_idle() diff --git a/examples/widgets/span_selector.py b/examples/widgets/span_selector.py index 7b43a51320d3..9ce64904e37f 100644 --- a/examples/widgets/span_selector.py +++ b/examples/widgets/span_selector.py @@ -7,14 +7,14 @@ import matplotlib.pyplot as plt from matplotlib.widgets import SpanSelector -fig = plt.figure(figsize=(8, 6)) +fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(211, axisbg='#FFFFCC') x = np.arange(0.0, 5.0, 0.01) -y = np.sin(2 * np.pi * x) + 0.5 * np.random.randn(len(x)) +y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x)) ax.plot(x, y, '-') -ax.set_ylim(-2, 2) +ax.set_ylim(-2,2) ax.set_title('Press left mouse button and drag to test') ax2 = fig.add_subplot(212, axisbg='#FFFFCC') @@ -23,7 +23,7 @@ def onselect(xmin, xmax): indmin, indmax = np.searchsorted(x, (xmin, xmax)) - indmax = min(len(x) - 1, indmax) + indmax = min(len(x)-1, indmax) thisx = x[indmin:indmax] thisy = y[indmin:indmax] @@ -34,7 +34,7 @@ def onselect(xmin, xmax): # set useblit True on gtkagg for enhanced performance span = SpanSelector(ax, onselect, 'horizontal', useblit=True, - rectprops=dict(alpha=0.5, facecolor='red')) + rectprops=dict(alpha=0.5, facecolor='red') ) plt.show()