Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Pep8ify examples #3425

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Sep 9, 2014
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
pep8ify: examples/api
Signed-off-by: Thomas Hisch <t.hisch@gmail.com>
  • Loading branch information
twmr committed Aug 27, 2014
commit 1c37e78b228bc55ba8f19529a200c473441ec6bd
2 changes: 1 addition & 1 deletion 2 examples/api/agg_oo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
15 changes: 8 additions & 7 deletions 15 examples/api/barchart_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -15,22 +15,23 @@
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)
Expand Down
2 changes: 1 addition & 1 deletion 2 examples/api/bbox_intersect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
43 changes: 21 additions & 22 deletions 43 examples/api/collections_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@

# Make some spirals
r = np.array(range(nverts))
theta = np.array(range(nverts)) * (2*np.pi)/(nverts-1)
theta = np.array(range(nverts))*2*np.pi/(nverts - 1)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you put the () back? I think they add clarity here.

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])
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -123,5 +124,3 @@


plt.show()


44 changes: 22 additions & 22 deletions 44 examples/api/colorbar_only.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand All @@ -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
Expand All @@ -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()
6 changes: 3 additions & 3 deletions 6 examples/api/compound_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
vertices = []
codes = []

codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY]
vertices = [(1,1), (1,2), (2, 2), (2, 1), (0,0)]
codes = [Path.MOVETO] + [Path.LINETO]* 3 + [Path.CLOSEPOLY]
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)
Expand Down
37 changes: 22 additions & 15 deletions 37 examples/api/custom_projection_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
# code used by a number of projections with similar characteristics
# (see geo.py).


class HammerAxes(Axes):

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uh, definitely don't want space between the class declaration and its docstring

"""
A custom class for the Aitoff-Hammer projection, an equal-area map
projection.
Expand Down Expand Up @@ -156,16 +158,16 @@ 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 + \
self.transData
yaxis_text_base = \
yaxis_stretch + \
self.transProjection + \
(yaxis_space + \
self.transAffine + \
(yaxis_space +
self.transAffine +
self.transAxes)
self._yaxis_text1_transform = \
yaxis_text_base + \
Expand All @@ -174,12 +176,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):
Expand All @@ -200,12 +202,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):
Expand Down Expand Up @@ -238,8 +240,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)}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this still under 80 characters (can't tell with the github viewer)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes: 78 chars

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW, the line length of the examples gets checked in the test_coding_standards unit test

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, good.


# Prevent the user from applying scales to one or both of the
# axes. In this particular case, scaling the axes wouldn't make
Expand Down Expand Up @@ -284,10 +286,12 @@ def format_coord(self, lon, lat):
return '%f\u00b0%s, %f\u00b0%s' % (abs(lat), ns, abs(lon), ew)

class DegreeFormatter(Formatter):

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blank line between class and its docstring

"""
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

Expand Down Expand Up @@ -369,16 +373,20 @@ 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

# Now, the transforms themselves.

class HammerTransform(Transform):

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

spurious blank line

"""
The base Hammer transform.
"""
Expand All @@ -394,7 +402,7 @@ def transform_non_affine(self, ll):
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
Expand All @@ -417,13 +425,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
Expand All @@ -449,12 +457,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
Expand All @@ -476,4 +484,3 @@ def inverted(self):
plt.grid(True)

plt.show()

Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.