diff --git a/.travis.yml b/.travis.yml index 669fe3a8d4de..e99ff6cb5bdc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,6 +34,7 @@ script: # Generate the font caches in a single process before starting the # multiple processes - python -c "from matplotlib import font_manager" + - if [[ $BUILD_DOCS == false ]]; then export MPL_REPO_DIR=$PWD; fi # pep8-conformance test of the examples - if [[ $BUILD_DOCS == false ]]; then mkdir ../tmp_test_dir; fi - if [[ $BUILD_DOCS == false ]]; then cd ../tmp_test_dir; fi - if [[ $BUILD_DOCS == false ]]; then python ../matplotlib/tests.py -sv --processes=8 --process-timeout=300 $TEST_ARGS; fi diff --git a/examples/animation/animate_decay.py b/examples/animation/animate_decay.py index a8694615e99b..9469ee22ab27 100644 --- a/examples/animation/animate_decay.py +++ b/examples/animation/animate_decay.py @@ -2,11 +2,12 @@ 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.) data_gen.t = 0 @@ -17,9 +18,11 @@ 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() @@ -32,5 +35,5 @@ def run(data): 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 82cfdc3e40fc..a0348f4a325a 100644 --- a/examples/animation/basic_example.py +++ b/examples/animation/basic_example.py @@ -2,8 +2,9 @@ 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() @@ -15,7 +16,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') fig2 = plt.figure() @@ -28,7 +29,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 fef958942621..6f3845dc3f46 100644 --- a/examples/animation/basic_example_writer.py +++ b/examples/animation/basic_example_writer.py @@ -7,8 +7,9 @@ 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 @@ -25,7 +26,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() @@ -38,5 +39,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 e3ba5a356a20..a05930562512 100644 --- a/examples/animation/bayes_update.py +++ b/examples/animation/bayes_update.py @@ -4,6 +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 @@ -43,5 +44,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 cae06d64cf1c..1cb05a2e3dea 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): @@ -22,7 +22,8 @@ def derivs(state, t): 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_) + + 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] @@ -46,19 +47,17 @@ def derivs(state, t): th2 = -10.0 w2 = 0.0 -rad = pi/180 - # initial state -state = np.array([th1, w1, th2, w2])*pi/180. +state = np.radians([th1, w1, th2, w2]) # 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)) @@ -68,21 +67,23 @@ 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 e25e66b0eb33..247bbc031ad9 100644 --- a/examples/animation/dynamic_image.py +++ b/examples/animation/dynamic_image.py @@ -8,6 +8,7 @@ fig = plt.figure() + def f(x, y): return np.sin(x) + np.cos(y) @@ -16,11 +17,12 @@ 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 832b688bda67..c4a29b3d00aa 100644 --- a/examples/animation/dynamic_image2.py +++ b/examples/animation/dynamic_image2.py @@ -8,6 +8,7 @@ fig = plt.figure() + def f(x, y): return np.sin(x) + np.cos(y) @@ -24,7 +25,7 @@ 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') diff --git a/examples/animation/histogram.py b/examples/animation/histogram.py index f81d4f397269..a8c4c13b8cf4 100644 --- a/examples/animation/histogram.py +++ b/examples/animation/histogram.py @@ -28,34 +28,36 @@ # 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 090de236813b..530bbd714f87 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,4 +29,3 @@ 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 21ed9710bbe5..ee3c7f72d773 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') @@ -42,7 +42,7 @@ def update(frame_number): # 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] = 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 c3044a3dee61..d468ffbfce4f 100644 --- a/examples/animation/random_data.py +++ b/examples/animation/random_data.py @@ -6,12 +6,15 @@ 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 74e918fdb9dd..fcfb822771b4 100644 --- a/examples/animation/simple_3danim.py +++ b/examples/animation/simple_3danim.py @@ -6,7 +6,8 @@ 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 @@ -15,7 +16,7 @@ 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] @@ -25,11 +26,12 @@ def Gen_RandLine(length, dims=2) : 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 @@ -57,6 +59,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 d19196337522..730ad926868e 100644 --- a/examples/animation/simple_anim.py +++ b/examples/animation/simple_anim.py @@ -7,18 +7,20 @@ fig, ax = plt.subplots() -x = np.arange(0, 2*np.pi, 0.01) # x-array +x = np.arange(0, 2*np.pi, 0.01) 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. + +# Init only required for blitting to give a clean slate. def init(): 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 2ca94cf5a1ac..6766d7e4b41a 100644 --- a/examples/animation/strip_chart_demo.py +++ b/examples/animation/strip_chart_demo.py @@ -7,6 +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 @@ -21,7 +22,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) @@ -48,7 +49,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 462549e658f8..210fb2dc39e2 100644 --- a/examples/animation/subplots.py +++ b/examples/animation/subplots.py @@ -3,11 +3,12 @@ from matplotlib.lines import Line2D import matplotlib.animation as animation -# This example uses subclassing, but there is no reason that the proper function -# couldn't be set up and then use FuncAnimation. The code is long, but not -# 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. + +# This example uses subclassing, but there is no reason that the proper +# function couldn't be set up and then use FuncAnimation. The code is long, but +# not 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() @@ -24,7 +25,8 @@ 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) @@ -36,7 +38,8 @@ 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) @@ -47,7 +50,8 @@ 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) @@ -75,16 +79,16 @@ 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([], []) diff --git a/examples/animation/unchained.py b/examples/animation/unchained.py index 0a41a6138429..71cb69aecd12 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/api/agg_oo.py b/examples/api/agg_oo.py index 94acbc119a32..76fb7665fa54 100644 --- a/examples/api/agg_oo.py +++ b/examples/api/agg_oo.py @@ -9,7 +9,7 @@ fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) -ax.plot([1,2,3]) +ax.plot([1, 2, 3]) ax.set_title('hi mom') ax.grid(True) ax.set_xlabel('time') diff --git a/examples/api/barchart_demo.py b/examples/api/barchart_demo.py index e3d89b417752..eceb5dc3aa09 100644 --- a/examples/api/barchart_demo.py +++ b/examples/api/barchart_demo.py @@ -6,7 +6,7 @@ N = 5 menMeans = (20, 35, 30, 35, 27) -menStd = (2, 3, 4, 1, 2) +menStd = (2, 3, 4, 1, 2) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars @@ -15,22 +15,24 @@ rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd) womenMeans = (25, 32, 34, 20, 25) -womenStd = (3, 5, 2, 3, 3) -rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd) +womenStd = (3, 5, 2, 3, 3) +rects2 = ax.bar(ind + width, womenMeans, width, color='y', yerr=womenStd) # add some text for labels, title and axes ticks ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') -ax.set_xticks(ind+width) -ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') ) +ax.set_xticks(ind + width) +ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) + +ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) -ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') ) def autolabel(rects): # attach some text labels for rect in rects: height = rect.get_height() - ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height), + ax.text(rect.get_x() + rect.get_width()/2., 1.05*height, + '%d' % int(height), ha='center', va='bottom') autolabel(rects1) diff --git a/examples/api/bbox_intersect.py b/examples/api/bbox_intersect.py index 9a495a2e2410..8fa33637b285 100644 --- a/examples/api/bbox_intersect.py +++ b/examples/api/bbox_intersect.py @@ -14,6 +14,6 @@ color = 'r' else: color = 'b' - plt.plot(vertices[:,0], vertices[:,1], color=color) + plt.plot(vertices[:, 0], vertices[:, 1], color=color) plt.show() diff --git a/examples/api/collections_demo.py b/examples/api/collections_demo.py index 243f1464fa47..90873f886d9b 100644 --- a/examples/api/collections_demo.py +++ b/examples/api/collections_demo.py @@ -26,11 +26,11 @@ npts = 100 # Make some spirals -r = np.array(range(nverts)) -theta = np.array(range(nverts)) * (2*np.pi)/(nverts-1) +r = np.arange(nverts) +theta = np.linspace(0, 2*np.pi, nverts) xx = r * np.sin(theta) yy = r * np.cos(theta) -spiral = list(zip(xx,yy)) +spiral = list(zip(xx, yy)) # Make some offsets rs = np.random.RandomState([12345678]) @@ -39,27 +39,28 @@ xyo = list(zip(xo, yo)) # 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')] +colors = [colorConverter.to_rgba(c) + for c in ('r', 'g', 'b', 'c', 'y', 'm', 'k')] -fig, axes = plt.subplots(2,2) -((ax1, ax2), (ax3, ax4)) = axes # unpack the axes +fig, axes = plt.subplots(2, 2) +((ax1, ax2), (ax3, ax4)) = axes # unpack the axes col = collections.LineCollection([spiral], offsets=xyo, - transOffset=ax1.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. +# 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. 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 'ax1.autoscale_view()' call below. +# 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 'ax1.autoscale_view()' call below. # Make a transform for the line segments such that their size is # given in points: @@ -71,7 +72,7 @@ # The same data as above, but fill the curves. col = collections.PolyCollection([spiral], offsets=xyo, - transOffset=ax2.transData) + transOffset=ax2.transData) trans = transforms.Affine2D().scale(fig.dpi/72.0) col.set_transform(trans) # the points to pixels transform ax2.add_collection(col, autolim=True) @@ -84,9 +85,9 @@ # 7-sided regular polygons col = collections.RegularPolyCollection(7, - sizes = np.fabs(xx)*10.0, offsets=xyo, + sizes=np.fabs(xx) * 10.0, offsets=xyo, transOffset=ax3.transData) -trans = transforms.Affine2D().scale(fig.dpi/72.0) +trans = transforms.Affine2D().scale(fig.dpi / 72.0) col.set_transform(trans) # the points to pixels transform ax3.add_collection(col, autolim=True) col.set_color(colors) @@ -104,7 +105,7 @@ yy = np.linspace(0, 2*np.pi, nverts) ym = np.amax(yy) -xx = (0.2 + (ym-yy)/ym)**2 * np.cos(yy-0.4) * 0.5 +xx = (0.2 + (ym - yy)/ym)**2 * np.cos(yy - 0.4)*0.5 segs = [] for i in range(ncurves): xxx = xx + 0.02*rs.randn(nverts) @@ -123,5 +124,3 @@ plt.show() - - diff --git a/examples/api/colorbar_only.py b/examples/api/colorbar_only.py index b270c2bf85c7..e2a2df61e23e 100644 --- a/examples/api/colorbar_only.py +++ b/examples/api/colorbar_only.py @@ -6,7 +6,7 @@ import matplotlib as mpl # Make a figure and axes with dimensions as desired. -fig = pyplot.figure(figsize=(8,3)) +fig = pyplot.figure(figsize=(8, 3)) ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15]) ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15]) ax3 = fig.add_axes([0.05, 0.15, 0.9, 0.15]) @@ -22,8 +22,8 @@ # following gives a basic continuous colorbar with ticks # and labels. cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, - norm=norm, - orientation='horizontal') + norm=norm, + orientation='horizontal') cb1.set_label('Some Units') # The second example illustrates the use of a ListedColormap, a @@ -39,36 +39,36 @@ bounds = [1, 2, 4, 7, 8] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, - norm=norm, - # to use 'extend', you must - # specify two extra boundaries: - boundaries=[0]+bounds+[13], - extend='both', - ticks=bounds, # optional - spacing='proportional', - orientation='horizontal') + norm=norm, + # to use 'extend', you must + # specify two extra boundaries: + boundaries=[0] + bounds + [13], + extend='both', + ticks=bounds, # optional + spacing='proportional', + orientation='horizontal') cb2.set_label('Discrete intervals, some other units') # The third example illustrates the use of custom length colorbar # extensions, used on a colorbar with discrete intervals. cmap = mpl.colors.ListedColormap([[0., .4, 1.], [0., .8, 1.], - [1., .8, 0.], [1., .4, 0.]]) + [1., .8, 0.], [1., .4, 0.]]) cmap.set_over((1., 0., 0.)) cmap.set_under((0., 0., 1.)) bounds = [-1., -.5, 0., .5, 1.] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) cb3 = mpl.colorbar.ColorbarBase(ax3, cmap=cmap, - norm=norm, - boundaries=[-10]+bounds+[10], - extend='both', - # Make the length of each extension - # the same as the length of the - # interior colors: - extendfrac='auto', - ticks=bounds, - spacing='uniform', - orientation='horizontal') + norm=norm, + boundaries=[-10] + bounds + [10], + extend='both', + # Make the length of each extension + # the same as the length of the + # interior colors: + extendfrac='auto', + ticks=bounds, + spacing='uniform', + orientation='horizontal') cb3.set_label('Custom extension lengths, some other units') pyplot.show() diff --git a/examples/api/compound_path.py b/examples/api/compound_path.py index ea52986c7c95..7783ec822e1d 100644 --- a/examples/api/compound_path.py +++ b/examples/api/compound_path.py @@ -13,10 +13,10 @@ codes = [] codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY] -vertices = [(1,1), (1,2), (2, 2), (2, 1), (0,0)] +vertices = [(1, 1), (1, 2), (2, 2), (2, 1), (0, 0)] codes += [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY] -vertices += [(4,4), (5,5), (5, 4), (0,0)] +vertices += [(4, 4), (5, 5), (5, 4), (0, 0)] vertices = np.array(vertices, float) path = Path(vertices, codes) diff --git a/examples/api/custom_projection_example.py b/examples/api/custom_projection_example.py index 31f55f6b523d..3389b77a4a28 100644 --- a/examples/api/custom_projection_example.py +++ b/examples/api/custom_projection_example.py @@ -18,6 +18,7 @@ # code used by a number of projections with similar characteristics # (see geo.py). + class HammerAxes(Axes): """ A custom class for the Aitoff-Hammer projection, an equal-area map @@ -40,7 +41,7 @@ def _init_axis(self): self.yaxis = maxis.YAxis(self) # Do not register xaxis or yaxis with spines -- as done in # Axes._init_axis() -- until HammerAxes.xaxis.cla() works. - # self.spines['hammer'].register_axis(self.yaxis) + #self.spines['hammer'].register_axis(self.yaxis) self._update_transScale() def cla(self): @@ -156,7 +157,7 @@ def _set_lim_and_transforms(self): # (1, ymax). The goal of these transforms is to go from that # space to display space. The tick labels will be offset 4 # pixels from the edge of the axes ellipse. - yaxis_stretch = Affine2D().scale(np.pi * 2.0, 1.0).translate(-np.pi, 0.0) + yaxis_stretch = Affine2D().scale(2*np.pi, 1.0).translate(-np.pi, 0.0) yaxis_space = Affine2D().scale(1.0, 1.1) self._yaxis_transform = \ yaxis_stretch + \ @@ -164,8 +165,8 @@ def _set_lim_and_transforms(self): yaxis_text_base = \ yaxis_stretch + \ self.transProjection + \ - (yaxis_space + \ - self.transAffine + \ + (yaxis_space + + self.transAffine + self.transAxes) self._yaxis_text1_transform = \ yaxis_text_base + \ @@ -174,12 +175,12 @@ def _set_lim_and_transforms(self): yaxis_text_base + \ Affine2D().translate(8.0, 0.0) - def get_xaxis_transform(self,which='grid'): + def get_xaxis_transform(self, which='grid'): """ Override this method to provide a transformation for the x-axis grid and ticks. """ - assert which in ['tick1','tick2','grid'] + assert which in ['tick1', 'tick2', 'grid'] return self._xaxis_transform def get_xaxis_text1_transform(self, pixelPad): @@ -200,12 +201,12 @@ def get_xaxis_text2_transform(self, pixelPad): """ return self._xaxis_text2_transform, 'top', 'center' - def get_yaxis_transform(self,which='grid'): + def get_yaxis_transform(self, which='grid'): """ Override this method to provide a transformation for the y-axis grid and ticks. """ - assert which in ['tick1','tick2','grid'] + assert which in ['tick1', 'tick2', 'grid'] return self._yaxis_transform def get_yaxis_text1_transform(self, pixelPad): @@ -238,8 +239,8 @@ def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): - return {'custom_hammer':mspines.Spine.circular_spine(self, - (0.5, 0.5), 0.5)} + return {'custom_hammer': mspines.Spine.circular_spine(self, + (0.5, 0.5), 0.5)} # Prevent the user from applying scales to one or both of the # axes. In this particular case, scaling the axes wouldn't make @@ -288,6 +289,7 @@ class DegreeFormatter(Formatter): This is a custom formatter that converts the native unit of radians into (truncated) degrees and adds a degree symbol. """ + def __init__(self, round_to=1.0): self._round_to = round_to @@ -369,10 +371,13 @@ def can_zoom(self): Return True if this axes support the zoom box """ return False + def start_pan(self, x, y, button): pass + def end_pan(self): pass + def drag_pan(self, button, key, x, y): pass @@ -388,13 +393,13 @@ class HammerTransform(Transform): def transform_non_affine(self, ll): """ - Override the transform_non_affine method to implement the custom + Override the transform_non_affine method to implement the custom transform. The input and output are Nx2 numpy arrays. """ longitude = ll[:, 0:1] - latitude = ll[:, 1:2] + latitude = ll[:, 1:2] # Pre-compute some values half_long = longitude / 2.0 @@ -417,13 +422,13 @@ def transform_path_non_affine(self, path): ipath = path.interpolated(path._interpolation_steps) return Path(self.transform(ipath.vertices), ipath.codes) transform_path_non_affine.__doc__ = \ - Transform.transform_path_non_affine.__doc__ + Transform.transform_path_non_affine.__doc__ if matplotlib.__version__ < '1.2': # Note: For compatibility with matplotlib v1.1 and older, you'll # need to explicitly implement a ``transform`` method as well. # Otherwise a ``NotImplementedError`` will be raised. This isn't - # necessary for v1.2 and newer, however. + # necessary for v1.2 and newer, however. transform = transform_non_affine # Similarly, we need to explicitly override ``transform_path`` if @@ -449,12 +454,12 @@ def transform_non_affine(self, xy): quarter_x = 0.25 * x half_y = 0.5 * y z = np.sqrt(1.0 - quarter_x*quarter_x - half_y*half_y) - longitude = 2 * np.arctan((z*x) / (2.0 * (2.0*z*z - 1.0))) + longitude = 2*np.arctan((z*x)/(2.0*(2.0*z*z - 1.0))) latitude = np.arcsin(y*z) return np.concatenate((longitude, latitude), 1) transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ - # As before, we need to implement the "transform" method for + # As before, we need to implement the "transform" method for # compatibility with matplotlib v1.1 and older. if matplotlib.__version__ < '1.2': transform = transform_non_affine @@ -476,4 +481,3 @@ def inverted(self): plt.grid(True) plt.show() - diff --git a/examples/api/custom_scale_example.py b/examples/api/custom_scale_example.py index 6b3e3caba50b..9bb94e402841 100644 --- a/examples/api/custom_scale_example.py +++ b/examples/api/custom_scale_example.py @@ -32,7 +32,6 @@ class MercatorLatitudeScale(mscale.ScaleBase): # scale. name = 'mercator' - def __init__(self, axis, **kwargs): """ Any keyword arguments passed to ``set_xscale`` and @@ -77,7 +76,7 @@ def __call__(self, x, pos=None): deg2rad = np.pi / 180.0 axis.set_major_locator(FixedLocator( - np.arange(-90, 90, 10) * deg2rad)) + np.arange(-90, 90, 10) * deg2rad)) axis.set_major_formatter(DegreeFormatter()) axis.set_minor_formatter(DegreeFormatter()) @@ -133,7 +132,8 @@ def inverted(self): Override this method so matplotlib knows how to get the inverse transform for this transform. """ - return MercatorLatitudeScale.InvertedMercatorLatitudeTransform(self.thresh) + return MercatorLatitudeScale.InvertedMercatorLatitudeTransform( + self.thresh) class InvertedMercatorLatitudeTransform(mtransforms.Transform): input_dims = 1 @@ -170,4 +170,3 @@ def inverted(self): plt.grid(True) plt.show() - diff --git a/examples/api/date_demo.py b/examples/api/date_demo.py index 1de554387718..220c230cfcc0 100644 --- a/examples/api/date_demo.py +++ b/examples/api/date_demo.py @@ -17,8 +17,8 @@ import matplotlib.dates as mdates import matplotlib.cbook as cbook -years = mdates.YearLocator() # every year -months = mdates.MonthLocator() # every month +years = mdates.YearLocator() # every year +months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y') # load a numpy record array from yahoo csv data with fields date, @@ -38,11 +38,13 @@ ax.xaxis.set_minor_locator(months) datemin = datetime.date(r.date.min().year, 1, 1) -datemax = datetime.date(r.date.max().year+1, 1, 1) +datemax = datetime.date(r.date.max().year + 1, 1, 1) ax.set_xlim(datemin, datemax) + # format the coords message box -def price(x): return '$%1.2f'%x +def price(x): + return '$%1.2f' % x ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') ax.format_ydata = price ax.grid(True) diff --git a/examples/api/date_index_formatter.py b/examples/api/date_index_formatter.py index 691e4a1e66fd..6008ac9953d1 100644 --- a/examples/api/date_index_formatter.py +++ b/examples/api/date_index_formatter.py @@ -27,8 +27,9 @@ N = len(r) ind = np.arange(N) # the evenly spaced plot indices + def format_date(x, pos=None): - thisind = np.clip(int(x+0.5), 0, N-1) + thisind = np.clip(int(x + 0.5), 0, N - 1) return r.date[thisind].strftime('%Y-%m-%d') fig, ax = plt.subplots() diff --git a/examples/api/demo_affine_image.py b/examples/api/demo_affine_image.py index 036f4a526898..3b5ed23b1fb9 100644 --- a/examples/api/demo_affine_image.py +++ b/examples/api/demo_affine_image.py @@ -13,15 +13,17 @@ import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms + def get_image(): delta = 0.25 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) - Z = Z2-Z1 # difference of Gaussians + Z = Z2 - Z1 # difference of Gaussians return Z + def imshow_affine(ax, z, *kl, **kwargs): im = ax.imshow(z, *kl, **kwargs) x1, x2, y1, y2 = im.get_extent() @@ -33,7 +35,7 @@ def imshow_affine(ax, z, *kl, **kwargs): # image rotation - fig, (ax1, ax2) = plt.subplots(1,2) + fig, (ax1, ax2) = plt.subplots(1, 2) Z = get_image() im1 = imshow_affine(ax1, Z, interpolation='none', cmap=cm.jet, origin='lower', @@ -52,7 +54,6 @@ def imshow_affine(ax, z, *kl, **kwargs): ax1.set_xlim(-3, 5) ax1.set_ylim(-4, 4) - # image skew im2 = ax2.imshow(Z, interpolation='none', cmap=cm.jet, @@ -60,6 +61,5 @@ def imshow_affine(ax, z, *kl, **kwargs): extent=[-2, 4, -3, 2], clip_on=True) im2._image_skew_coordinate = (3, -2) - plt.show() #plt.savefig("demo_affine_image") diff --git a/examples/api/donut_demo.py b/examples/api/donut_demo.py index b36b0e7f3291..ed99b0229246 100644 --- a/examples/api/donut_demo.py +++ b/examples/api/donut_demo.py @@ -3,12 +3,14 @@ import matplotlib.patches as mpatches import matplotlib.pyplot as plt + def wise(v): if v == 1: return "CCW" else: return "CW" + def make_circle(r): t = np.arange(0, np.pi * 2.0, 0.01) t = t.reshape((len(t), 1)) @@ -22,7 +24,8 @@ def make_circle(r): inside_vertices = make_circle(0.5) outside_vertices = make_circle(1.0) -codes = np.ones(len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO +codes = np.ones( + len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO codes[0] = mpath.Path.MOVETO for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))): @@ -44,10 +47,8 @@ def make_circle(r): ax.annotate("Outside %s,\nInside %s" % (wise(outside), wise(inside)), (i * 2.5, -1.5), va="top", ha="center") -ax.set_xlim(-2,10) -ax.set_ylim(-3,2) +ax.set_xlim(-2, 10) +ax.set_ylim(-3, 2) ax.set_title('Mmm, donuts!') ax.set_aspect(1.0) plt.show() - - diff --git a/examples/api/engineering_formatter.py b/examples/api/engineering_formatter.py index e70803885269..a2c5d3003b16 100644 --- a/examples/api/engineering_formatter.py +++ b/examples/api/engineering_formatter.py @@ -13,7 +13,7 @@ ax.xaxis.set_major_formatter(formatter) xs = np.logspace(1, 9, 100) -ys = (0.8 + 0.4 * np.random.uniform(size=100)) * np.log10(xs)**2 +ys = (0.8 + 0.4*np.random.uniform(size=100))*np.log10(xs)**2 ax.plot(xs, ys) plt.show() diff --git a/examples/api/font_family_rc.py b/examples/api/font_family_rc.py index d3b2d4acca37..c505adf132b4 100644 --- a/examples/api/font_family_rc.py +++ b/examples/api/font_family_rc.py @@ -11,7 +11,8 @@ and for the font.family you set a list of font styles to try to find in order:: - rcParams['font.sans-serif'] = ['Tahoma', 'Bitstream Vera Sans', 'Lucida Grande', 'Verdana'] + rcParams['font.sans-serif'] = ['Tahoma', 'Bitstream Vera Sans', + 'Lucida Grande', 'Verdana'] """ @@ -23,8 +24,7 @@ import matplotlib.pyplot as plt fig, ax = plt.subplots() -ax.plot([1,2,3], label='test') +ax.plot([1, 2, 3], label='test') ax.legend() plt.show() - diff --git a/examples/api/font_file.py b/examples/api/font_file.py index e5f4127d1c9d..9f321afeded4 100644 --- a/examples/api/font_file.py +++ b/examples/api/font_file.py @@ -12,17 +12,17 @@ import matplotlib.pyplot as plt fig, ax = plt.subplots() -ax.plot([1,2,3]) +ax.plot([1, 2, 3]) if sys.platform == 'win32': fpath = 'C:\\Windows\\Fonts\\Tahoma.ttf' elif sys.platform.startswith('linux'): - fonts = ['/usr/share/fonts/truetype/freefont/FreeSansBoldOblique.ttf', - '/usr/share/fonts/truetype/ttf-liberation/LiberationSans-BoldItalic.ttf', - '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf', - ] + basedir = '/usr/share/fonts/truetype' + fonts = ['freefont/FreeSansBoldOblique.ttf', + 'ttf-liberation/LiberationSans-BoldItalic.ttf', + 'msttcorefonts/Comic_Sans_MS.ttf'] for fpath in fonts: - if os.path.exists(fpath): + if os.path.exists(os.path.join(basedir, fpath)): break else: fpath = '/Library/Fonts/Tahoma.ttf' @@ -36,4 +36,3 @@ ax.set_xlabel('This is the default font') plt.show() - diff --git a/examples/api/histogram_path_demo.py b/examples/api/histogram_path_demo.py index 0789264b7bca..a7b1bd3e8106 100644 --- a/examples/api/histogram_path_demo.py +++ b/examples/api/histogram_path_demo.py @@ -30,13 +30,14 @@ # we need a (numrects x numsides x 2) numpy array for the path helper # function to build a compound path -XY = np.array([[left,left,right,right], [bottom,top,top,bottom]]).T +XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T # get the Path object barpath = path.Path.make_compound_path_from_polys(XY) # make a patch out of it -patch = patches.PathPatch(barpath, facecolor='blue', edgecolor='gray', alpha=0.8) +patch = patches.PathPatch( + barpath, facecolor='blue', edgecolor='gray', alpha=0.8) ax.add_patch(patch) # update the view limits diff --git a/examples/api/image_zcoord.py b/examples/api/image_zcoord.py index 69b40135075f..38f6fbb3083c 100644 --- a/examples/api/image_zcoord.py +++ b/examples/api/image_zcoord.py @@ -6,21 +6,22 @@ import matplotlib.pyplot as plt import matplotlib.cm as cm -X = 10*np.random.rand(5,3) +X = 10*np.random.rand(5, 3) fig, ax = plt.subplots() ax.imshow(X, cmap=cm.jet, interpolation='nearest') numrows, numcols = X.shape + + def format_coord(x, y): - col = int(x+0.5) - row = int(y+0.5) - if col>=0 and col=0 and row= 0 and col < numcols and row >= 0 and row < numrows: + z = X[row, col] + return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x, y, z) else: - return 'x=%1.4f, y=%1.4f'%(x, y) + return 'x=%1.4f, y=%1.4f' % (x, y) ax.format_coord = format_coord plt.show() - diff --git a/examples/api/joinstyle.py b/examples/api/joinstyle.py index ce3847da79f9..b4e3c5e0dfd2 100644 --- a/examples/api/joinstyle.py +++ b/examples/api/joinstyle.py @@ -6,24 +6,25 @@ import numpy as np import matplotlib.pyplot as plt + def plot_angle(ax, x, y, angle, style): phi = angle/180*np.pi - xx = [x+.5,x,x+.5*np.cos(phi)] - yy = [y,y,y+.5*np.sin(phi)] + xx = [x + .5, x, x + .5*np.cos(phi)] + yy = [y, y, y + .5*np.sin(phi)] ax.plot(xx, yy, lw=8, color='blue', solid_joinstyle=style) ax.plot(xx[1:], yy[1:], lw=1, color='black') ax.plot(xx[1::-1], yy[1::-1], lw=1, color='black') ax.plot(xx[1:2], yy[1:2], 'o', color='red', markersize=3) - ax.text(x,y+.2,'%.0f degrees' % angle) + ax.text(x, y + .2, '%.0f degrees' % angle) fig, ax = plt.subplots() ax.set_title('Join style') -for x,style in enumerate((('miter', 'round', 'bevel'))): +for x, style in enumerate((('miter', 'round', 'bevel'))): ax.text(x, 5, style) for i in range(5): - plot_angle(ax, x, i, pow(2.0,3+i), style) + plot_angle(ax, x, i, pow(2.0, 3 + i), style) -ax.set_xlim(-.5,2.75) -ax.set_ylim(-.5,5.5) +ax.set_xlim(-.5, 2.75) +ax.set_ylim(-.5, 5.5) plt.show() diff --git a/examples/api/legend_demo.py b/examples/api/legend_demo.py index 26c0f8062f29..6c0bcae3e242 100644 --- a/examples/api/legend_demo.py +++ b/examples/api/legend_demo.py @@ -2,14 +2,14 @@ import matplotlib.pyplot as plt # Make some fake data. -a = b = np.arange(0,3, .02) +a = b = np.arange(0, 3, .02) c = np.exp(a) d = c[::-1] # Create plots with pre-defined labels. plt.plot(a, c, 'k--', label='Model length') plt.plot(a, d, 'k:', label='Data length') -plt.plot(a, c+d, 'k', label='Total message length') +plt.plot(a, c + d, 'k', label='Total message length') legend = plt.legend(loc='upper center', shadow=True, fontsize='x-large') diff --git a/examples/api/line_with_text.py b/examples/api/line_with_text.py index 6c72aa2dfac0..f5e4bd383331 100644 --- a/examples/api/line_with_text.py +++ b/examples/api/line_with_text.py @@ -10,44 +10,39 @@ class MyLine(lines.Line2D): - - def __init__(self, *args, **kwargs): - # we'll update the position when the line data is set - self.text = mtext.Text(0, 0, '') - lines.Line2D.__init__(self, *args, **kwargs) - - # we can't access the label attr until *after* the line is - # inited - self.text.set_text(self.get_label()) - - def set_figure(self, figure): - self.text.set_figure(figure) - lines.Line2D.set_figure(self, figure) - - def set_axes(self, axes): - self.text.set_axes(axes) - lines.Line2D.set_axes(self, axes) - - def set_transform(self, transform): - # 2 pixel offset - texttrans = transform + mtransforms.Affine2D().translate(2, 2) - self.text.set_transform(texttrans) - lines.Line2D.set_transform(self, transform) - - - def set_data(self, x, y): - if len(x): - self.text.set_position((x[-1], y[-1])) - - lines.Line2D.set_data(self, x, y) - - def draw(self, renderer): - # draw my label at the end of the line with 2 pixel offset - lines.Line2D.draw(self, renderer) - self.text.draw(renderer) - - - + def __init__(self, *args, **kwargs): + # we'll update the position when the line data is set + self.text = mtext.Text(0, 0, '') + lines.Line2D.__init__(self, *args, **kwargs) + + # we can't access the label attr until *after* the line is + # inited + self.text.set_text(self.get_label()) + + def set_figure(self, figure): + self.text.set_figure(figure) + lines.Line2D.set_figure(self, figure) + + def set_axes(self, axes): + self.text.set_axes(axes) + lines.Line2D.set_axes(self, axes) + + def set_transform(self, transform): + # 2 pixel offset + texttrans = transform + mtransforms.Affine2D().translate(2, 2) + self.text.set_transform(texttrans) + lines.Line2D.set_transform(self, transform) + + def set_data(self, x, y): + if len(x): + self.text.set_position((x[-1], y[-1])) + + lines.Line2D.set_data(self, x, y) + + def draw(self, renderer): + # draw my label at the end of the line with 2 pixel offset + lines.Line2D.draw(self, renderer) + self.text.draw(renderer) fig, ax = plt.subplots() diff --git a/examples/api/logo2.py b/examples/api/logo2.py index cadaea4f3f89..d67bda4c3ac9 100644 --- a/examples/api/logo2.py +++ b/examples/api/logo2.py @@ -16,7 +16,7 @@ #figcolor = '#EFEFEF' figcolor = 'white' dpi = 80 -fig = plt.figure(figsize=(6, 1.1),dpi=dpi) +fig = plt.figure(figsize=(6, 1.1), dpi=dpi) fig.figurePatch.set_edgecolor(figcolor) fig.figurePatch.set_facecolor(figcolor) @@ -25,29 +25,37 @@ def add_math_background(): ax = fig.add_axes([0., 0., 1., 1.]) text = [] - text.append((r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$", (0.7, 0.2), 20)) - text.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$", - (0.35, 0.9), 20)) + text.append( + (r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = " + r"U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2}" + r"\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 " + r"\left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - " + r"\alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} " + r"}{U^{0\beta}_{\rho_1 \sigma_2}}\right]$", (0.7, 0.2), 20)) + text.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} " + r"= -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$", + (0.35, 0.9), 20)) text.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$", - (0.15, 0.3), 25)) + (0.15, 0.3), 25)) #text.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$", # (0.7, 0.42), 30)) text.append((r"$F_G = G\frac{m_1m_2}{r^2}$", - (0.85, 0.7), 30)) + (0.85, 0.7), 30)) for eq, (x, y), size in text: - ax.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=0.25, - transform=ax.transAxes, fontsize=size) + ax.text(x, y, eq, ha='center', va='center', color="#11557c", + alpha=0.25, transform=ax.transAxes, fontsize=size) ax.set_axis_off() return ax + def add_matplotlib_text(ax): ax.text(0.95, 0.5, 'matplotlib', color='#11557c', fontsize=65, - ha='right', va='center', alpha=1.0, transform=ax.transAxes) + ha='right', va='center', alpha=1.0, transform=ax.transAxes) + def add_polar_bar(): ax = fig.add_axes([0.025, 0.075, 0.2, 0.85], polar=True) - ax.axesPatch.set_alpha(axalpha) ax.set_axisbelow(True) N = 7 diff --git a/examples/api/mathtext_asarray.py b/examples/api/mathtext_asarray.py index 049184ffa574..8f41cdb35030 100644 --- a/examples/api/mathtext_asarray.py +++ b/examples/api/mathtext_asarray.py @@ -2,20 +2,20 @@ Load a mathtext image as numpy array """ -import numpy as np import matplotlib.mathtext as mathtext import matplotlib.pyplot as plt import matplotlib matplotlib.rc('image', origin='upper') parser = mathtext.MathTextParser("Bitmap") - - -parser.to_png('test2.png', r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$', color='green', fontsize=14, dpi=100) - - -rgba1, depth1 = parser.to_rgba(r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200) -rgba2, depth2 = parser.to_rgba(r'some other string', color='red', fontsize=20, dpi=200) +parser.to_png('test2.png', + r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} ' + r'y\right)\right]$', color='green', fontsize=14, dpi=100) + +rgba1, depth1 = parser.to_rgba( + r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200) +rgba2, depth2 = parser.to_rgba( + r'some other string', color='red', fontsize=20, dpi=200) fig = plt.figure() fig.figimage(rgba1.astype(float)/255., 100, 100) diff --git a/examples/api/patch_collection.py b/examples/api/patch_collection.py index 98b4ca4f6b58..85a3ab39e6cb 100644 --- a/examples/api/patch_collection.py +++ b/examples/api/patch_collection.py @@ -7,35 +7,35 @@ fig, ax = plt.subplots() -resolution = 50 # the number of vertices +resolution = 50 # the number of vertices N = 3 -x = np.random.rand(N) -y = np.random.rand(N) -radii = 0.1*np.random.rand(N) +x = np.random.rand(N) +y = np.random.rand(N) +radii = 0.1*np.random.rand(N) patches = [] -for x1,y1,r in zip(x, y, radii): - circle = Circle((x1,y1), r) +for x1, y1, r in zip(x, y, radii): + circle = Circle((x1, y1), r) patches.append(circle) -x = np.random.rand(N) -y = np.random.rand(N) -radii = 0.1*np.random.rand(N) -theta1 = 360.0*np.random.rand(N) -theta2 = 360.0*np.random.rand(N) -for x1,y1,r,t1,t2 in zip(x, y, radii, theta1, theta2): - wedge = Wedge((x1,y1), r, t1, t2) +x = np.random.rand(N) +y = np.random.rand(N) +radii = 0.1*np.random.rand(N) +theta1 = 360.0*np.random.rand(N) +theta2 = 360.0*np.random.rand(N) +for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2): + wedge = Wedge((x1, y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedge patches += [ - Wedge((.3,.7), .1, 0, 360), # Full circle - Wedge((.7,.8), .2, 0, 360, width=0.05), # Full ring - Wedge((.8,.3), .2, 0, 45), # Full sector - Wedge((.8,.3), .2, 45, 90, width=0.10), # Ring sector + Wedge((.3, .7), .1, 0, 360), # Full circle + Wedge((.7, .8), .2, 0, 360, width=0.05), # Full ring + Wedge((.8, .3), .2, 0, 45), # Full sector + Wedge((.8, .3), .2, 45, 90, width=0.10), # Ring sector ] for i in range(N): - polygon = Polygon(np.random.rand(N,2), True) + polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) colors = 100*np.random.rand(len(patches)) diff --git a/examples/api/power_norm_demo.py b/examples/api/power_norm_demo.py index 76cde1bf0c5d..9aa9aa3f15b4 100644 --- a/examples/api/power_norm_demo.py +++ b/examples/api/power_norm_demo.py @@ -5,9 +5,9 @@ import numpy as np from numpy.random import multivariate_normal -data = np.vstack([multivariate_normal([10, 10], [[3, 5],[4, 2]], size=100000), - multivariate_normal([30, 20], [[2, 3],[1, 3]], size=1000) - ]) +data = np.vstack([multivariate_normal([10, 10], [[3, 5], [4, 2]], size=100000), + multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000) + ]) gammas = [0.8, 0.5, 0.3] xgrid = np.floor((len(gammas) + 1.) / 2) @@ -15,7 +15,7 @@ plt.subplot(xgrid, ygrid, 1) plt.title('Linear normalization') -plt.hist2d(data[:,0], data[:,1], bins=100) +plt.hist2d(data[:, 0], data[:, 1], bins=100) for i, gamma in enumerate(gammas): plt.subplot(xgrid, ygrid, i + 2) diff --git a/examples/api/quad_bezier.py b/examples/api/quad_bezier.py index 07e85d479e3c..0816bb0a8d8e 100644 --- a/examples/api/quad_bezier.py +++ b/examples/api/quad_bezier.py @@ -15,4 +15,3 @@ ax.set_title('The red point should be on the path') plt.show() - diff --git a/examples/api/radar_chart.py b/examples/api/radar_chart.py index 23df848b8a47..7f8d24b1cb76 100644 --- a/examples/api/radar_chart.py +++ b/examples/api/radar_chart.py @@ -32,7 +32,7 @@ def radar_factory(num_vars, frame='circle'): """ # calculate evenly-spaced axis angles - theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars) + theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False) # rotate theta such that the first axis is at the top theta += np.pi/2 @@ -76,7 +76,7 @@ def _close_line(self, line): line.set_data(x, y) def set_varlabels(self, labels): - self.set_thetagrids(theta * 180/np.pi, labels) + self.set_thetagrids(theta*180/np.pi, labels) def _gen_axes_patch(self): return self.draw_patch() @@ -113,13 +113,14 @@ def unit_poly_verts(theta): def example_data(): - #The following data is from the Denver Aerosol Sources and Health study. - #See doi:10.1016/j.atmosenv.2008.12.017 + # The following data is from the Denver Aerosol Sources and Health study. + # See doi:10.1016/j.atmosenv.2008.12.017 # - #The data are pollution source profile estimates for five modeled pollution - #sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical species. - #The radar charts are experimented with here to see if we can nicely - #visualize how the modeled source profiles change across four scenarios: + # The data are pollution source profile estimates for five modeled + # pollution sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical + # species. The radar charts are experimented with here to see if we can + # nicely visualize how the modeled source profiles change across four + # scenarios: # 1) No gas-phase species present, just seven particulate counts on # Sulfate # Nitrate @@ -175,7 +176,7 @@ def example_data(): colors = ['b', 'r', 'g', 'm', 'y'] # Plot the four cases from the example data on separate axes for n, title in enumerate(data.keys()): - ax = fig.add_subplot(2, 2, n+1, projection='radar') + ax = fig.add_subplot(2, 2, n + 1, projection='radar') plt.rgrids([0.2, 0.4, 0.6, 0.8]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') diff --git a/examples/api/sankey_demo_basics.py b/examples/api/sankey_demo_basics.py index 2e84b51fee49..842bd5c60bee 100644 --- a/examples/api/sankey_demo_basics.py +++ b/examples/api/sankey_demo_basics.py @@ -37,13 +37,13 @@ sankey = Sankey(ax=ax, scale=0.01, offset=0.2, head_angle=180, format='%.0f', unit='%') sankey.add(flows=[25, 0, 60, -10, -20, -5, -15, -10, -40], - labels = ['', '', '', 'First', 'Second', 'Third', 'Fourth', - 'Fifth', 'Hurray!'], + labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', + 'Fifth', 'Hurray!'], orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0], - pathlengths = [0.25, 0.25, 0.25, 0.25, 0.25, 0.6, 0.25, 0.25, - 0.25], + pathlengths=[0.25, 0.25, 0.25, 0.25, 0.25, 0.6, 0.25, 0.25, + 0.25], patchlabel="Widget\nA", - alpha=0.2, lw=2.0) # Arguments to matplotlib.patches.PathPatch() + alpha=0.2, lw=2.0) # Arguments to matplotlib.patches.PathPatch() diagrams = sankey.finish() diagrams[0].patch.set_facecolor('#37c959') diagrams[0].texts[-1].set_color('r') diff --git a/examples/api/sankey_demo_links.py b/examples/api/sankey_demo_links.py index 064931c9dbe6..ed2e755dbf27 100644 --- a/examples/api/sankey_demo_links.py +++ b/examples/api/sankey_demo_links.py @@ -15,11 +15,11 @@ def side(sankey, n=1): colors = cycle(['orange', 'b', 'g', 'r', 'c', 'm', 'y']) for i in range(0, 2*n, 2): sankey.add(flows=[1, -1], orientations=[-1, -1], - patchlabel=str(prior+i), facecolor=next(colors), - prior=prior+i-1, connect=(1, 0), alpha=0.5) + patchlabel=str(prior + i), facecolor=next(colors), + prior=prior + i - 1, connect=(1, 0), alpha=0.5) sankey.add(flows=[1, -1], orientations=[1, 1], - patchlabel=str(prior+i+1), facecolor=next(colors), - prior=prior+i, connect=(1, 0), alpha=0.5) + patchlabel=str(prior + i + 1), facecolor=next(colors), + prior=prior + i, connect=(1, 0), alpha=0.5) def corner(sankey): @@ -27,7 +27,7 @@ def corner(sankey): prior = len(sankey.diagrams) sankey.add(flows=[1, -1], orientations=[0, 1], patchlabel=str(prior), facecolor='k', - prior=prior-1, connect=(1, 0), alpha=0.5) + prior=prior - 1, connect=(1, 0), alpha=0.5) fig = plt.figure() diff --git a/examples/api/sankey_demo_old.py b/examples/api/sankey_demo_old.py index f8b73696bc76..90494e5a1ff8 100755 --- a/examples/api/sankey_demo_old.py +++ b/examples/api/sankey_demo_old.py @@ -43,58 +43,63 @@ def sankey(ax, assert sum(ins) == 100, "Inputs don't sum up to 100%" def add_output(path, loss, sign=1): - h = (loss/2 + w)*np.tan(outangle/180. * np.pi) # Arrow tip height + # Arrow tip height + h = (loss/2 + w) * np.tan(outangle/180.*np.pi) move, (x, y) = path[-1] # Use last point as reference if sign == 0: # Final loss (horizontal) - path.extend([(Path.LINETO, [x+dx, y]), - (Path.LINETO, [x+dx, y+w]), - (Path.LINETO, [x+dx+h, y-loss/2]), # Tip - (Path.LINETO, [x+dx, y-loss-w]), - (Path.LINETO, [x+dx, y-loss])]) + path.extend([(Path.LINETO, [x + dx, y]), + (Path.LINETO, [x + dx, y + w]), + (Path.LINETO, [x + dx + h, y - loss/2]), # Tip + (Path.LINETO, [x + dx, y - loss - w]), + (Path.LINETO, [x + dx, y - loss])]) outtips.append((sign, path[-3][1])) else: # Intermediate loss (vertical) - path.extend([(Path.CURVE4, [x+dx/2, y]), - (Path.CURVE4, [x+dx, y]), - (Path.CURVE4, [x+dx, y+sign*dy]), - (Path.LINETO, [x+dx-w, y+sign*dy]), - (Path.LINETO, [x+dx+loss/2, y+sign*(dy+h)]), # Tip - (Path.LINETO, [x+dx+loss+w, y+sign*dy]), - (Path.LINETO, [x+dx+loss, y+sign*dy]), - (Path.CURVE3, [x+dx+loss, y-sign*loss]), - (Path.CURVE3, [x+dx/2+loss, y-sign*loss])]) + path.extend([(Path.CURVE4, [x + dx/2, y]), + (Path.CURVE4, [x + dx, y]), + (Path.CURVE4, [x + dx, y + sign*dy]), + (Path.LINETO, [x + dx - w, y + sign*dy]), + # Tip + (Path.LINETO, [ + x + dx + loss/2, y + sign*(dy + h)]), + (Path.LINETO, [x + dx + loss + w, y + sign*dy]), + (Path.LINETO, [x + dx + loss, y + sign*dy]), + (Path.CURVE3, [x + dx + loss, y - sign*loss]), + (Path.CURVE3, [x + dx/2 + loss, y - sign*loss])]) outtips.append((sign, path[-5][1])) def add_input(path, gain, sign=1): - h = (gain/2)*np.tan(inangle/180. * np.pi) # Dip depth + h = (gain / 2) * np.tan(inangle / 180. * np.pi) # Dip depth move, (x, y) = path[-1] # Use last point as reference if sign == 0: # First gain (horizontal) - path.extend([(Path.LINETO, [x-dx, y]), - (Path.LINETO, [x-dx+h, y+gain/2]), # Dip - (Path.LINETO, [x-dx, y+gain])]) + path.extend([(Path.LINETO, [x - dx, y]), + (Path.LINETO, [x - dx + h, y + gain/2]), # Dip + (Path.LINETO, [x - dx, y + gain])]) xd, yd = path[-2][1] # Dip position - indips.append((sign, [xd-h, yd])) + indips.append((sign, [xd - h, yd])) else: # Intermediate gain (vertical) - path.extend([(Path.CURVE4, [x-dx/2, y]), - (Path.CURVE4, [x-dx, y]), - (Path.CURVE4, [x-dx, y+sign*dy]), - (Path.LINETO, [x-dx-gain/2, y+sign*(dy-h)]), # Dip - (Path.LINETO, [x-dx-gain, y+sign*dy]), - (Path.CURVE3, [x-dx-gain, y-sign*gain]), - (Path.CURVE3, [x-dx/2-gain, y-sign*gain])]) + path.extend([(Path.CURVE4, [x - dx/2, y]), + (Path.CURVE4, [x - dx, y]), + (Path.CURVE4, [x - dx, y + sign*dy]), + # Dip + (Path.LINETO, [ + x - dx - gain / 2, y + sign*(dy - h)]), + (Path.LINETO, [x - dx - gain, y + sign*dy]), + (Path.CURVE3, [x - dx - gain, y - sign*gain]), + (Path.CURVE3, [x - dx/2 - gain, y - sign*gain])]) xd, yd = path[-4][1] # Dip position - indips.append((sign, [xd, yd+sign*h])) + indips.append((sign, [xd, yd + sign*h])) outtips = [] # Output arrow tip dir. and positions urpath = [(Path.MOVETO, [0, 100])] # 1st point of upper right path lrpath = [(Path.LINETO, [0, 0])] # 1st point of lower right path for loss, sign in zip(outs, outsigns): - add_output(sign>=0 and urpath or lrpath, loss, sign=sign) + add_output(sign >= 0 and urpath or lrpath, loss, sign=sign) indips = [] # Input arrow tip dir. and positions llpath = [(Path.LINETO, [0, 0])] # 1st point of lower left path ulpath = [(Path.MOVETO, [0, 100])] # 1st point of upper left path for gain, sign in reversed(list(zip(ins, insigns))): - add_input(sign<=0 and llpath or ulpath, gain, sign=sign) + add_input(sign <= 0 and llpath or ulpath, gain, sign=sign) def revert(path): """A path is not just revertable by path[::-1] because of Bezier @@ -144,12 +149,12 @@ def put_labels(labels, positions, output=True): for i, label in enumerate(lbls): s, (x, y) = positions[i] # Label direction and position if s == 0: - t = ax.text(x+offset, y, label, + t = ax.text(x + offset, y, label, ha=output and 'left' or 'right', va='center') elif s > 0: - t = ax.text(x, y+offset, label, ha='center', va='bottom') + t = ax.text(x, y + offset, label, ha='center', va='bottom') else: - t = ax.text(x, y-offset, label, ha='center', va='top') + t = ax.text(x, y - offset, label, ha='center', va='top') texts.append(t) return texts @@ -160,20 +165,20 @@ def put_labels(labels, positions, output=True): intexts = put_labels(inlabels, indips, output=False) # Axes management - ax.set_xlim(verts[:, 0].min()-dx, verts[:, 0].max()+dx) - ax.set_ylim(verts[:, 1].min()-dy, verts[:, 1].max()+dy) + ax.set_xlim(verts[:, 0].min() - dx, verts[:, 0].max() + dx) + ax.set_ylim(verts[:, 1].min() - dy, verts[:, 1].max() + dy) ax.set_aspect('equal', adjustable='datalim') return patch, [intexts, outtexts] -if __name__=='__main__': +if __name__ == '__main__': import matplotlib.pyplot as plt outputs = [10., -20., 5., 15., -10., 40.] outlabels = ['First', 'Second', 'Third', 'Fourth', 'Fifth', 'Hurray!'] - outlabels = [s+'\n%d%%' % abs(l) for l, s in zip(outputs, outlabels)] + outlabels = [s + '\n%d%%' % abs(l) for l, s in zip(outputs, outlabels)] inputs = [60., -25., 15.] diff --git a/examples/api/sankey_demo_rankine.py b/examples/api/sankey_demo_rankine.py index b334acf51754..ccf1ccc4a1c9 100644 --- a/examples/api/sankey_demo_rankine.py +++ b/examples/api/sankey_demo_rankine.py @@ -1,18 +1,20 @@ -"""Demonstrate the Sankey class with a practicle example of a Rankine power cycle. +"""Demonstrate the Sankey class with a practicle example of a Rankine power +cycle. + """ -import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey fig = plt.figure(figsize=(8, 9)) ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], - title="Rankine Power Cycle: Example 8.6 from Moran and Shapiro\n" - + "\x22Fundamentals of Engineering Thermodynamics\x22, 6th ed., 2008") + title="Rankine Power Cycle: Example 8.6 from Moran and " + "Shapiro\n\x22Fundamentals of Engineering Thermodynamics " + "\x22, 6th ed., 2008") Hdot = [260.431, 35.078, 180.794, 221.115, 22.700, 142.361, 10.193, 10.210, 43.670, 44.312, 68.631, 10.758, 10.758, 0.017, 0.642, - 232.121, 44.559, 100.613, 132.168] # MW + 232.121, 44.559, 100.613, 132.168] # MW sankey = Sankey(ax=ax, format='%.3G', unit=' MW', gap=0.5, scale=1.0/Hdot[0]) sankey.add(patchlabel='\n\nPump 1', rotation=90, facecolor='#37c959', flows=[Hdot[13], Hdot[6], -Hdot[7]], diff --git a/examples/api/scatter_piecharts.py b/examples/api/scatter_piecharts.py index 424fa70411a2..71ce385fe0be 100644 --- a/examples/api/scatter_piecharts.py +++ b/examples/api/scatter_piecharts.py @@ -9,10 +9,10 @@ # first define the ratios r1 = 0.2 # 20% -r2 = r1 + 0.4 # 40% +r2 = r1 + 0.4 # 40% # define some sizes of the scatter marker -sizes = [60,80,120] +sizes = [60, 80, 120] # calculate the points of the first pie marker # @@ -20,20 +20,21 @@ # some points on a circle cos,sin x = [0] + np.cos(np.linspace(0, 2*math.pi*r1, 10)).tolist() y = [0] + np.sin(np.linspace(0, 2*math.pi*r1, 10)).tolist() -xy1 = list(zip(x,y)) +xy1 = list(zip(x, y)) # ... x = [0] + np.cos(np.linspace(2*math.pi*r1, 2*math.pi*r2, 10)).tolist() y = [0] + np.sin(np.linspace(2*math.pi*r1, 2*math.pi*r2, 10)).tolist() -xy2 = list(zip(x,y)) +xy2 = list(zip(x, y)) x = [0] + np.cos(np.linspace(2*math.pi*r2, 2*math.pi, 10)).tolist() y = [0] + np.sin(np.linspace(2*math.pi*r2, 2*math.pi, 10)).tolist() -xy3 = list(zip(x,y)) +xy3 = list(zip(x, y)) 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' ) +d = np.arange(3) +ax.scatter(d, d, marker=(xy1, 0), s=sizes, facecolor='blue') +ax.scatter(d, d, marker=(xy2, 0), s=sizes, facecolor='green') +ax.scatter(d, d, marker=(xy3, 0), s=sizes, facecolor='red') plt.show() diff --git a/examples/api/skewt.py b/examples/api/skewt.py index f05bcd6766b4..ce9e23fef157 100644 --- a/examples/api/skewt.py +++ b/examples/api/skewt.py @@ -18,9 +18,12 @@ # The sole purpose of this class is to look at the upper, lower, or total # interval as appropriate and see what parts of the tick to draw, if any. + + class SkewXTick(maxis.XTick): def draw(self, renderer): - if not self.get_visible(): return + if not self.get_visible(): + return renderer.open_group(self.__name__) lower_interval = self.axes.xaxis.lower_interval @@ -76,7 +79,7 @@ def _adjust_location(self): left = trans.transform_point((0.0, yloc))[0] right = trans.transform_point((1.0, yloc))[0] - pts = self._path.vertices + pts = self._path.vertices pts[0, 0] = left pts[1, 0] = right self.axis.upper_interval = (left, right) @@ -92,7 +95,7 @@ class SkewXAxes(Axes): name = 'skewx' def _init_axis(self): - #Taken from Axes and modified to use our modified X-axis + # Taken from Axes and modified to use our modified X-axis self.xaxis = SkewXAxis(self) self.spines['top'].register_axis(self.xaxis) self.spines['bottom'].register_axis(self.xaxis) @@ -101,10 +104,10 @@ def _init_axis(self): self.spines['right'].register_axis(self.yaxis) def _gen_axes_spines(self): - spines = {'top':SkewSpine.linear_spine(self, 'top'), - 'bottom':mspines.Spine.linear_spine(self, 'bottom'), - 'left':mspines.Spine.linear_spine(self, 'left'), - 'right':mspines.Spine.linear_spine(self, 'right')} + spines = {'top': SkewSpine.linear_spine(self, 'top'), + 'bottom': mspines.Spine.linear_spine(self, 'bottom'), + 'left': mspines.Spine.linear_spine(self, 'left'), + 'right': mspines.Spine.linear_spine(self, 'right')} return spines def _set_lim_and_transforms(self): @@ -114,7 +117,7 @@ def _set_lim_and_transforms(self): """ rot = 30 - #Get the standard transform setup from the Axes base class + # Get the standard transform setup from the Axes base class Axes._set_lim_and_transforms(self) # Need to put the skew in the middle, after the scale and limits, @@ -122,8 +125,8 @@ def _set_lim_and_transforms(self): # coordinates thus performing the transform around the proper origin # We keep the pre-transAxes transform around for other users, like the # spines for finding bounds - self.transDataToAxes = self.transScale + (self.transLimits + - transforms.Affine2D().skew_deg(rot, 0)) + self.transDataToAxes = self.transScale + \ + self.transLimits + transforms.Affine2D().skew_deg(rot, 0) # Create the full transform from Data to Pixels self.transData = self.transDataToAxes + self.transAxes @@ -131,9 +134,9 @@ def _set_lim_and_transforms(self): # Blended transforms like this need to have the skewing applied using # both axes, in axes coords like before. self._xaxis_transform = (transforms.blended_transform_factory( - self.transScale + self.transLimits, - transforms.IdentityTransform()) + - transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes + self.transScale + self.transLimits, + transforms.IdentityTransform()) + + transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes # Now register the projection with matplotlib so the user can select # it. @@ -142,12 +145,11 @@ def _set_lim_and_transforms(self): if __name__ == '__main__': # Now make a simple example using the custom projection. from matplotlib.ticker import ScalarFormatter, MultipleLocator - from matplotlib.collections import LineCollection import matplotlib.pyplot as plt from StringIO import StringIO import numpy as np - #Some examples data + # Some examples data data_txt = ''' 978.0 345 7.8 0.8 61 4.16 325 14 282.7 294.6 283.4 971.0 404 7.2 0.2 61 4.01 327 17 282.7 294.2 283.4 @@ -221,11 +223,12 @@ def _set_lim_and_transforms(self): 107.8 15850 -64.1 -75.1 21 0.01 265 58 395.0 395.1 395.0 105.0 16010 -64.7 -75.7 21 0.01 272 50 396.9 396.9 396.9 103.0 16128 -62.9 -73.9 21 0.02 277 45 402.5 402.6 402.5 - 100.0 16310 -62.5 -73.5 21 0.02 285 36 406.7 406.8 406.7''' + 100.0 16310 -62.5 -73.5 21 0.02 285 36 406.7 406.8 406.7 + ''' # Parse the data sound_data = StringIO(data_txt) - p,h,T,Td = np.loadtxt(sound_data, usecols=range(0,4), unpack=True) + p, h, T, Td = np.loadtxt(sound_data, usecols=range(0, 4), unpack=True) # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(6.5875, 6.2125)) @@ -243,10 +246,10 @@ def _set_lim_and_transforms(self): # Disables the log-formatting that comes with semilogy ax.yaxis.set_major_formatter(ScalarFormatter()) - ax.set_yticks(np.linspace(100,1000,10)) - ax.set_ylim(1050,100) + ax.set_yticks(np.linspace(100, 1000, 10)) + ax.set_ylim(1050, 100) ax.xaxis.set_major_locator(MultipleLocator(10)) - ax.set_xlim(-50,50) + ax.set_xlim(-50, 50) plt.show() diff --git a/examples/api/span_regions.py b/examples/api/span_regions.py index 1cfbdcf3dd10..bf23ffb07379 100644 --- a/examples/api/span_regions.py +++ b/examples/api/span_regions.py @@ -20,18 +20,12 @@ ax.axhline(0, color='black', lw=2) collection = collections.BrokenBarHCollection.span_where( - t, ymin=0, ymax=1, where=s1>0, facecolor='green', alpha=0.5) + t, ymin=0, ymax=1, where=s1 > 0, facecolor='green', alpha=0.5) ax.add_collection(collection) collection = collections.BrokenBarHCollection.span_where( - t, ymin=-1, ymax=0, where=s1<0, facecolor='red', alpha=0.5) + t, ymin=-1, ymax=0, where=s1 < 0, facecolor='red', alpha=0.5) ax.add_collection(collection) - plt.show() - - - - - diff --git a/examples/api/two_scales.py b/examples/api/two_scales.py index 356c81336905..5ff253d44954 100644 --- a/examples/api/two_scales.py +++ b/examples/api/two_scales.py @@ -42,4 +42,3 @@ for tl in ax2.get_yticklabels(): tl.set_color('r') plt.show() - diff --git a/examples/api/watermark_image.py b/examples/api/watermark_image.py index 9b6425070ea5..9e9421b7ab3d 100644 --- a/examples/api/watermark_image.py +++ b/examples/api/watermark_image.py @@ -10,7 +10,7 @@ datafile = cbook.get_sample_data('logo2.png', asfileobj=False) print ('loading %s' % datafile) im = image.imread(datafile) -im[:,:,-1] = 0.5 # set the alpha channel +im[:, :, -1] = 0.5 # set the alpha channel fig, ax = plt.subplots() diff --git a/examples/axes_grid/demo_axes_divider.py b/examples/axes_grid/demo_axes_divider.py index df56d9f3f532..d69b1d745dc2 100644 --- a/examples/axes_grid/demo_axes_divider.py +++ b/examples/axes_grid/demo_axes_divider.py @@ -1,12 +1,13 @@ 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): @@ -20,7 +21,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) @@ -30,9 +31,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)] @@ -96,27 +97,25 @@ def demo(): fig1 = plt.figure(1, (6, 6)) fig1.clf() - ## PLOT 1 + # PLOT 1 # simple image & colorbar ax = fig1.add_subplot(2, 2, 1) demo_simple_image(ax) - ## PLOT 2 + # PLOT 2 # image and colorbar whose location is adjusted in the drawing time. # a hard way demo_locatable_axes_hard(fig1) - - ## PLOT 3 + # PLOT 3 # image and colorbar whose location is adjusted in the drawing time. # a easy way ax = fig1.add_subplot(2, 2, 3) demo_locatable_axes_easy(ax) - - ## PLOT 4 + # PLOT 4 # two images side by side with fixed padding. ax = fig1.add_subplot(2, 2, 4) diff --git a/examples/axes_grid/demo_axes_grid.py b/examples/axes_grid/demo_axes_grid.py index add8f29f7d72..11683228f3b3 100644 --- a/examples/axes_grid/demo_axes_grid.py +++ b/examples/axes_grid/demo_axes_grid.py @@ -1,30 +1,33 @@ 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), - axes_pad = 0.05, - label_mode = "1", + grid = AxesGrid(fig, 141, # similar to subplot(141) + nrows_ncols=(2, 2), + axes_pad=0.05, + label_mode="1", ) Z, extent = get_demo_image() 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]) @@ -33,12 +36,12 @@ 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), - axes_pad = 0.0, + grid = AxesGrid(fig, 142, # similar to subplot(142) + nrows_ncols=(2, 2), + axes_pad=0.0, share_all=True, - label_mode = "L", - cbar_location = "top", + label_mode="L", + cbar_location="top", cbar_mode="single", ) @@ -50,7 +53,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]) @@ -61,11 +64,11 @@ 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), - axes_pad = 0.1, - label_mode = "1", - share_all = True, + grid = AxesGrid(F, 143, # similar to subplot(143) + nrows_ncols=(2, 2), + axes_pad=0.1, + label_mode="1", + share_all=True, cbar_location="top", cbar_mode="each", cbar_size="7%", @@ -83,16 +86,17 @@ 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), - label_mode = "1", - share_all = True, + 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", cbar_mode="each", cbar_size="7%", @@ -100,15 +104,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]) @@ -127,4 +131,3 @@ 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 41c8b5ef23aa..029a812b1cc6 100644 --- a/examples/axes_grid/demo_axes_grid2.py +++ b/examples/axes_grid/demo_axes_grid2.py @@ -2,12 +2,13 @@ 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): @@ -28,27 +29,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)] + 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"]): @@ -69,11 +70,10 @@ 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 f63061ac45e7..692ca8454c3e 100644 --- a/examples/axes_grid/demo_axes_hbox_divider.py +++ b/examples/axes_grid/demo_axes_hbox_divider.py @@ -3,9 +3,10 @@ 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) @@ -16,23 +17,22 @@ 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,4 +47,3 @@ 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 b7374c2766d6..c5569b52de98 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 < 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,18 +28,17 @@ 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) @@ -56,8 +55,6 @@ 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) diff --git a/examples/axes_grid/demo_colorbar_with_inset_locator.py b/examples/axes_grid/demo_colorbar_with_inset_locator.py index 1085e45d95ee..72a920b402c5 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 1a738b50d71d..4080aaadc974 100644 --- a/examples/axes_grid/demo_curvelinear_grid.py +++ b/examples/axes_grid/demo_curvelinear_grid.py @@ -1,14 +1,13 @@ import numpy as np -#from matplotlib.path import Path import matplotlib.pyplot as plt import matplotlib.cbook as cbook -from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear from mpl_toolkits.axisartist import Subplot - from mpl_toolkits.axisartist import SubplotHost, \ - ParasiteAxesAuxTrans + ParasiteAxesAuxTrans +from mpl_toolkits.axisartist.grid_helper_curvelinear import \ + GridHelperCurveLinear def curvelinear_test1(fig): @@ -18,12 +17,11 @@ 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)) @@ -42,16 +40,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. @@ -67,10 +65,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) @@ -89,7 +87,6 @@ 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. @@ -97,13 +94,12 @@ 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 @@ -128,6 +124,3 @@ 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 2d96044a2a70..a1b105cefdf3 100644 --- a/examples/axes_grid/demo_curvelinear_grid2.py +++ b/examples/axes_grid/demo_curvelinear_grid2.py @@ -1,12 +1,12 @@ import numpy as np -#from matplotlib.path import Path - 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): """ @@ -18,16 +18,17 @@ def tr(x, y): x, y = np.abs(np.asarray(x)), np.asarray(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 extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, - lon_cycle = None, - lat_cycle = None, - lon_minmax = None, #(0, np.inf), - lat_minmax = None, + lon_cycle=None, + lat_cycle=None, + # (0, np.inf), + lon_minmax=None, + lat_minmax=None, ) grid_helper = GridHelperCurveLinear((tr, inv_tr), @@ -41,8 +42,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") @@ -51,13 +52,9 @@ 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 6e25d02a0d12..667483366b66 100644 --- a/examples/axes_grid/demo_edge_colorbar.py +++ b/examples/axes_grid/demo_edge_colorbar.py @@ -1,21 +1,22 @@ 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", @@ -30,7 +31,7 @@ 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) @@ -48,8 +49,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, @@ -62,7 +63,7 @@ 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) @@ -75,7 +76,6 @@ def demo_right_cbar(fig): grid.axes_llc.set_yticks([-2, 0, 2]) - if 1: F = plt.figure(1, (5.5, 2.5)) @@ -86,4 +86,3 @@ 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 4ffb9ead058d..51bc391fdfd2 100644 --- a/examples/axes_grid/demo_floating_axes.py +++ b/examples/axes_grid/demo_floating_axes.py @@ -3,10 +3,11 @@ 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): """ @@ -14,7 +15,8 @@ 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) @@ -32,9 +34,6 @@ def setup_axes2(fig, rect): With custom locator and formatter. Note that the extreme values are swapped. """ - - #tr_scale = Affine2D().scale(np.pi/180., 1.) - tr = PolarAxes.PolarTransform() pi = np.pi @@ -46,13 +45,12 @@ def setup_axes2(fig, rect): 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) @@ -60,11 +58,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 @@ -89,13 +87,12 @@ def setup_axes3(fig, rect): 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, - ) + 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) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) @@ -113,20 +110,18 @@ 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,24 +129,21 @@ 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. #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)*np.pi/2 + 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 + 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 bc8dea6b2729..f907105807c5 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 @@ -21,10 +21,10 @@ def curvelinear_test2(fig): 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,7 +37,6 @@ def curvelinear_test2(fig): tick_formatter1=tick_formatter1 ) - ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) fig.add_subplot(ax1) @@ -67,5 +66,3 @@ 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 5a4af10cd458..79f7655753eb 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 2f73bb084cc0..10f57698a58f 100644 --- a/examples/axes_grid/demo_parasite_axes2.py +++ b/examples/axes_grid/demo_parasite_axes2.py @@ -15,10 +15,8 @@ par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) - - par2.axis["right"].toggle(all=True) - + par2.axis["right"].toggle(all=True) host.set_xlim(0, 2) host.set_ylim(0, 2) diff --git a/examples/axes_grid/inset_locator_demo.py b/examples/axes_grid/inset_locator_demo.py index 1a1f5d0e3784..3fc9e975e23a 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 211faa4bffd8..97e420694b64 100644 --- a/examples/axes_grid/inset_locator_demo2.py +++ b/examples/axes_grid/inset_locator_demo2.py @@ -5,27 +5,28 @@ 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") @@ -43,4 +44,3 @@ 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 6a269a5c8f32..fb609105a9da 100644 --- a/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py +++ b/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py @@ -2,42 +2,41 @@ from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable - if __name__ == "__main__": - + import matplotlib.pyplot as plt + def ex1(): plt.figure(1) - ax = plt.axes([0,0,1,1]) - # ax = plt.subplot(111) + 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) @@ -48,13 +47,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 136ffd2912bd..643a722cd7a1 100644 --- a/examples/axes_grid/parasite_simple2.py +++ b/examples/axes_grid/parasite_simple2.py @@ -10,7 +10,7 @@ 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 @@ -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 273ae5d9348c..ff6e1412c1fc 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) diff --git a/examples/axes_grid/simple_anchored_artists.py b/examples/axes_grid/simple_anchored_artists.py index 8853534d23b3..466f1a1730cb 100644 --- a/examples/axes_grid/simple_anchored_artists.py +++ b/examples/axes_grid/simple_anchored_artists.py @@ -17,7 +17,8 @@ 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, @@ -26,6 +27,7 @@ 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 @@ -34,11 +36,12 @@ 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, @@ -57,5 +60,3 @@ 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 5038b4eee0b7..b8c45f2aae6d 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 efd7fb45a9bd..0eac5461613a 100644 --- a/examples/axes_grid/simple_axesgrid2.py +++ b/examples/axes_grid/simple_axesgrid2.py @@ -1,31 +1,33 @@ 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 3b2c675666b6..0998189ae7b3 100644 --- a/examples/axes_grid/simple_axisline4.py +++ b/examples/axes_grid/simple_axisline4.py @@ -7,7 +7,7 @@ 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 = 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,4 +16,3 @@ plt.draw() plt.show() - diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index 3c63cd0c4a24..d3139fa81df3 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -1,11 +1,8 @@ from __future__ import (absolute_import, division, print_function, unicode_literals) -import six - from fnmatch import fnmatch import os -import sys from nose.tools import assert_equal from nose.plugins.skip import SkipTest @@ -20,24 +17,6 @@ import matplotlib -EXTRA_EXCLUDE_FILE = os.path.join(os.path.dirname(__file__), - '.pep8_test_exclude.txt') -EXCLUDE_FILES = ['_delaunay.py', - '_image.py', - '_tri.py', - '_backend_agg.py', - '_tkagg.py', - 'ft2font.py', - '_cntr.py', - '_png.py', - '_path.py', - 'ttconv.py', - '_gtkagg.py', - '_backend_gdk.py', - 'pyparsing*', - '_qhull.py', - '_macosx.py'] - PEP8_ADDITIONAL_IGNORE = ['E111', 'E112', 'E113', @@ -53,102 +32,14 @@ 'E131', 'E265'] -EXPECTED_BAD_FILES = ['*/matplotlib/__init__.py', - '*/matplotlib/_cm.py', - '*/matplotlib/_mathtext_data.py', - '*/matplotlib/_pylab_helpers.py', - '*/matplotlib/afm.py', - '*/matplotlib/artist.py', - '*/matplotlib/axis.py', - '*/matplotlib/backend_bases.py', - '*/matplotlib/bezier.py', - '*/matplotlib/cbook.py', - '*/matplotlib/collections.py', - '*/matplotlib/dviread.py', - '*/matplotlib/font_manager.py', - '*/matplotlib/fontconfig_pattern.py', - '*/matplotlib/gridspec.py', - '*/matplotlib/legend.py', - '*/matplotlib/legend_handler.py', - '*/matplotlib/mathtext.py', - '*/matplotlib/mlab.py', - '*/matplotlib/path.py', - '*/matplotlib/patheffects.py', - '*/matplotlib/pylab.py', - '*/matplotlib/pyplot.py', - '*/matplotlib/rcsetup.py', - '*/matplotlib/stackplot.py', - '*/matplotlib/texmanager.py', - '*/matplotlib/transforms.py', - '*/matplotlib/type1font.py', - '*/matplotlib/widgets.py', - '*/matplotlib/testing/decorators.py', - '*/matplotlib/testing/image_util.py', - '*/matplotlib/testing/noseclasses.py', - '*/matplotlib/testing/jpl_units/Duration.py', - '*/matplotlib/testing/jpl_units/Epoch.py', - '*/matplotlib/testing/jpl_units/EpochConverter.py', - '*/matplotlib/testing/jpl_units/StrConverter.py', - '*/matplotlib/testing/jpl_units/UnitDbl.py', - '*/matplotlib/testing/jpl_units/UnitDblConverter.py', - '*/matplotlib/testing/jpl_units/UnitDblFormatter.py', - '*/matplotlib/testing/jpl_units/__init__.py', - '*/matplotlib/tri/triinterpolate.py', - '*/matplotlib/tests/test_axes.py', - '*/matplotlib/tests/test_bbox_tight.py', - '*/matplotlib/tests/test_dates.py', - '*/matplotlib/tests/test_delaunay.py', - '*/matplotlib/tests/test_dviread.py', - '*/matplotlib/tests/test_image.py', - '*/matplotlib/tests/test_legend.py', - '*/matplotlib/tests/test_lines.py', - '*/matplotlib/tests/test_mathtext.py', - '*/matplotlib/tests/test_rcparams.py', - '*/matplotlib/tests/test_simplification.py', - '*/matplotlib/tests/test_spines.py', - '*/matplotlib/tests/test_streamplot.py', - '*/matplotlib/tests/test_subplots.py', - '*/matplotlib/tests/test_text.py', - '*/matplotlib/tests/test_tightlayout.py', - '*/matplotlib/tests/test_transforms.py', - '*/matplotlib/tests/test_triangulation.py', - '*/matplotlib/compat/subprocess.py', - '*/matplotlib/backends/__init__.py', - '*/matplotlib/backends/backend_agg.py', - '*/matplotlib/backends/backend_cairo.py', - '*/matplotlib/backends/backend_cocoaagg.py', - '*/matplotlib/backends/backend_gdk.py', - '*/matplotlib/backends/backend_gtk.py', - '*/matplotlib/backends/backend_gtk3.py', - '*/matplotlib/backends/backend_gtk3cairo.py', - '*/matplotlib/backends/backend_gtkagg.py', - '*/matplotlib/backends/backend_gtkcairo.py', - '*/matplotlib/backends/backend_macosx.py', - '*/matplotlib/backends/backend_mixed.py', - '*/matplotlib/backends/backend_pgf.py', - '*/matplotlib/backends/backend_ps.py', - '*/matplotlib/backends/backend_svg.py', - '*/matplotlib/backends/backend_template.py', - '*/matplotlib/backends/backend_tkagg.py', - '*/matplotlib/backends/backend_wx.py', - '*/matplotlib/backends/backend_wxagg.py', - '*/matplotlib/backends/tkagg.py', - '*/matplotlib/backends/windowing.py', - '*/matplotlib/backends/qt_editor/formlayout.py', - '*/matplotlib/sphinxext/ipython_console_highlighting.py', - '*/matplotlib/sphinxext/ipython_directive.py', - '*/matplotlib/sphinxext/mathmpl.py', - '*/matplotlib/sphinxext/only_directives.py', - '*/matplotlib/sphinxext/plot_directive.py', - '*/matplotlib/projections/__init__.py', - '*/matplotlib/projections/geo.py', - '*/matplotlib/projections/polar.py'] +EXTRA_EXCLUDE_FILE = os.path.join(os.path.dirname(__file__), + '.pep8_test_exclude.txt') if HAS_PEP8: class StandardReportWithExclusions(pep8.StandardReport): - #; A class attribute to store the exception exclusion file patterns. - expected_bad_files = EXPECTED_BAD_FILES + #: A class attribute to store the exception exclusion file patterns. + expected_bad_files = [] #: A class attribute to store the lines of failing tests. _global_deferred_print = [] @@ -191,9 +82,11 @@ def get_file_results(self): return self.file_errors -def assert_pep8_conformance(module=matplotlib, exclude_files=EXCLUDE_FILES, +def assert_pep8_conformance(module=matplotlib, exclude_files=None, extra_exclude_file=EXTRA_EXCLUDE_FILE, - pep8_additional_ignore=PEP8_ADDITIONAL_IGNORE): + pep8_additional_ignore=PEP8_ADDITIONAL_IGNORE, + dirname=None, expected_bad_files=None, + extra_exclude_directories=None): """ Tests the matplotlib codebase against the "pep8" tool. @@ -213,6 +106,9 @@ def assert_pep8_conformance(module=matplotlib, exclude_files=EXCLUDE_FILES, reporter=StandardReportWithExclusions) reporter = pep8style.options.reporter + if expected_bad_files is not None: + reporter.expected_bad_files = expected_bad_files + # Extend the number of PEP8 guidelines which are not checked. pep8style.options.ignore = (pep8style.options.ignore + tuple(pep8_additional_ignore)) @@ -220,7 +116,8 @@ def assert_pep8_conformance(module=matplotlib, exclude_files=EXCLUDE_FILES, # Support for egg shared object wrappers, which are not PEP8 compliant, # nor part of the matplotlib repository. # DO NOT ADD FILES *IN* THE REPOSITORY TO THIS LIST. - pep8style.options.exclude.extend(exclude_files) + if exclude_files is not None: + pep8style.options.exclude.extend(exclude_files) # Allow users to add their own exclude list. if extra_exclude_file is not None and os.path.exists(extra_exclude_file): @@ -228,7 +125,12 @@ def assert_pep8_conformance(module=matplotlib, exclude_files=EXCLUDE_FILES, extra_exclude = [line.strip() for line in fh if line.strip()] pep8style.options.exclude.extend(extra_exclude) - result = pep8style.check_files([os.path.dirname(module.__file__)]) + if extra_exclude_directories: + pep8style.options.exclude.extend(extra_exclude_directories) + + if dirname is None: + dirname = os.path.dirname(module.__file__) + result = pep8style.check_files([dirname]) if reporter is StandardReportWithExclusions: msg = ("Found code syntax errors (and warnings):\n" "{0}".format('\n'.join(reporter._global_deferred_print))) @@ -249,8 +151,146 @@ def assert_pep8_conformance(module=matplotlib, exclude_files=EXCLUDE_FILES, '{}'.format('\n '.join(unexpectedly_good))) -def test_pep8_conformance(): - assert_pep8_conformance() +def test_pep8_conformance_installed_files(): + exclude_files = ['_delaunay.py', + '_image.py', + '_tri.py', + '_backend_agg.py', + '_tkagg.py', + 'ft2font.py', + '_cntr.py', + '_png.py', + '_path.py', + 'ttconv.py', + '_gtkagg.py', + '_backend_gdk.py', + 'pyparsing*', + '_qhull.py', + '_macosx.py'] + + expected_bad_files = ['__init__.py', + '_cm.py', + '_mathtext_data.py', + '_pylab_helpers.py', + 'afm.py', + 'artist.py', + 'axis.py', + 'backend_bases.py', + 'bezier.py', + 'cbook.py', + 'collections.py', + 'dviread.py', + 'font_manager.py', + 'fontconfig_pattern.py', + 'gridspec.py', + 'legend.py', + 'legend_handler.py', + 'mathtext.py', + 'mlab.py', + 'path.py', + 'patheffects.py', + 'pylab.py', + 'pyplot.py', + 'rcsetup.py', + 'stackplot.py', + 'texmanager.py', + 'transforms.py', + 'type1font.py', + 'widgets.py', + 'testing/decorators.py', + 'testing/image_util.py', + 'testing/noseclasses.py', + 'testing/jpl_units/Duration.py', + 'testing/jpl_units/Epoch.py', + 'testing/jpl_units/EpochConverter.py', + 'testing/jpl_units/StrConverter.py', + 'testing/jpl_units/UnitDbl.py', + 'testing/jpl_units/UnitDblConverter.py', + 'testing/jpl_units/UnitDblFormatter.py', + 'testing/jpl_units/__init__.py', + 'tri/triinterpolate.py', + 'tests/test_axes.py', + 'tests/test_bbox_tight.py', + 'tests/test_dates.py', + 'tests/test_delaunay.py', + 'tests/test_dviread.py', + 'tests/test_image.py', + 'tests/test_legend.py', + 'tests/test_lines.py', + 'tests/test_mathtext.py', + 'tests/test_rcparams.py', + 'tests/test_simplification.py', + 'tests/test_spines.py', + 'tests/test_streamplot.py', + 'tests/test_subplots.py', + 'tests/test_text.py', + 'tests/test_tightlayout.py', + 'tests/test_transforms.py', + 'tests/test_triangulation.py', + 'compat/subprocess.py', + 'backends/__init__.py', + 'backends/backend_agg.py', + 'backends/backend_cairo.py', + 'backends/backend_cocoaagg.py', + 'backends/backend_gdk.py', + 'backends/backend_gtk.py', + 'backends/backend_gtk3.py', + 'backends/backend_gtk3cairo.py', + 'backends/backend_gtkagg.py', + 'backends/backend_gtkcairo.py', + 'backends/backend_macosx.py', + 'backends/backend_mixed.py', + 'backends/backend_pgf.py', + 'backends/backend_ps.py', + 'backends/backend_svg.py', + 'backends/backend_template.py', + 'backends/backend_tkagg.py', + 'backends/backend_wx.py', + 'backends/backend_wxagg.py', + 'backends/tkagg.py', + 'backends/windowing.py', + 'backends/qt_editor/formlayout.py', + 'sphinxext/ipython_console_highlighting.py', + 'sphinxext/ipython_directive.py', + 'sphinxext/mathmpl.py', + 'sphinxext/only_directives.py', + 'sphinxext/plot_directive.py', + 'projections/__init__.py', + 'projections/geo.py', + 'projections/polar.py'] + expected_bad_files = ['*/matplotlib/' + s for s in expected_bad_files] + assert_pep8_conformance(module=matplotlib, + exclude_files=exclude_files, + expected_bad_files=expected_bad_files) + + +def test_pep8_conformance_examples(): + mpldirdefault = os.path.join(os.getcwd(), '..', '..', '..') + mpldir = os.environ.get('MPL_REPO_DIR', mpldirdefault) + exdir = os.path.join(mpldir, 'examples') + blacklist = ['color', + 'event_handling', + 'images_contours_and_fields', + 'lines_bars_and_markers', + 'misc', + 'mplot3d', + 'pie_and_polar_charts', + 'pylab_examples', + 'shapes_and_collections', + 'showcase', + 'specialty_plots', + 'statistics', + 'style_sheets', + 'subplots_axes_and_figures', + 'tests', + 'text_labels_and_annotations', + 'ticks_and_spines', + 'units', + 'user_interfaces', + 'widgets'] + assert_pep8_conformance(dirname=exdir, + extra_exclude_directories=blacklist, + expected_bad_files=[]) if __name__ == '__main__':