From 705c4f99600c3ba4079df1d2d2bc921ccb7e1aee Mon Sep 17 00:00:00 2001 From: Thomas Hisch Date: Wed, 2 Jul 2014 21:35:37 +0200 Subject: [PATCH 1/2] run autopep8 in examples/api --- examples/api/agg_oo.py | 2 +- examples/api/barchart_demo.py | 19 +++--- examples/api/bbox_intersect.py | 2 +- examples/api/collections_demo.py | 33 +++++----- examples/api/colorbar_only.py | 44 ++++++------- examples/api/compound_path.py | 8 +-- examples/api/custom_projection_example.py | 42 +++++++----- examples/api/custom_scale_example.py | 6 +- examples/api/date_demo.py | 11 ++-- examples/api/date_index_formatter.py | 3 +- examples/api/demo_affine_image.py | 10 +-- examples/api/donut_demo.py | 11 ++-- examples/api/engineering_formatter.py | 2 +- examples/api/font_family_rc.py | 3 +- examples/api/font_file.py | 9 ++- examples/api/histogram_path_demo.py | 5 +- examples/api/image_zcoord.py | 17 ++--- examples/api/joinstyle.py | 17 ++--- examples/api/legend_demo.py | 4 +- examples/api/line_with_text.py | 70 ++++++++++---------- examples/api/logo2.py | 28 ++++---- examples/api/mathtext_asarray.py | 14 ++-- examples/api/patch_collection.py | 38 +++++------ examples/api/power_norm_demo.py | 8 +-- examples/api/quad_bezier.py | 1 - examples/api/radar_chart.py | 66 +++++++++---------- examples/api/sankey_demo_basics.py | 10 +-- examples/api/sankey_demo_links.py | 12 ++-- examples/api/sankey_demo_old.py | 78 ++++++++++++----------- examples/api/sankey_demo_rankine.py | 4 +- examples/api/scatter_piecharts.py | 31 +++++---- examples/api/skewt.py | 42 ++++++------ examples/api/span_regions.py | 14 ++-- examples/api/two_scales.py | 3 +- examples/api/unicode_minus.py | 2 +- examples/api/watermark_image.py | 2 +- examples/api/watermark_text.py | 2 +- 37 files changed, 349 insertions(+), 324 deletions(-) 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..55fc903d99a8 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,23 +15,26 @@ 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), - ha='center', va='bottom') + ax.text( + rect.get_x() + rect.get_width() / + 2., 1.05 * height, '%d' % int(height), + ha='center', va='bottom') autolabel(rects1) autolabel(rects2) 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..88ee5d8d3294 100644 --- a/examples/api/collections_demo.py +++ b/examples/api/collections_demo.py @@ -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) 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,15 +39,16 @@ 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) -trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0) + 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 @@ -71,8 +72,8 @@ # The same data as above, but fill the curves. col = collections.PolyCollection([spiral], offsets=xyo, - transOffset=ax2.transData) -trans = transforms.Affine2D().scale(fig.dpi/72.0) + 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) col.set_color(colors) @@ -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) @@ -102,13 +103,13 @@ ncurves = 20 offs = (0.1, 0.0) -yy = np.linspace(0, 2*np.pi, nverts) +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) - curve = list(zip(xxx, yy*100)) + xxx = xx + 0.02 * rs.randn(nverts) + curve = list(zip(xxx, yy * 100)) segs.append(curve) col = collections.LineCollection(segs, offsets=offs) @@ -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..57ee77502df8 100644 --- a/examples/api/compound_path.py +++ b/examples/api/compound_path.py @@ -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)] +codes += [Path.MOVETO] + [Path.LINETO] * 2 + [Path.CLOSEPOLY] +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..4f4c02fb8b50 100644 --- a/examples/api/custom_projection_example.py +++ b/examples/api/custom_projection_example.py @@ -18,7 +18,9 @@ # 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 projection. @@ -156,7 +158,8 @@ 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( + np.pi * 2.0, 1.0).translate(-np.pi, 0.0) yaxis_space = Affine2D().scale(1.0, 1.1) self._yaxis_transform = \ yaxis_stretch + \ @@ -164,8 +167,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 +177,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 +203,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 +241,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 @@ -284,10 +287,12 @@ def format_coord(self, lon, lat): return '%f\u00b0%s, %f\u00b0%s' % (abs(lat), ns, abs(lon), ew) 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,16 +374,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): + """ The base Hammer transform. """ @@ -394,7 +403,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 @@ -417,13 +426,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 @@ -448,13 +457,13 @@ 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))) - latitude = np.arcsin(y*z) + 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))) + 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 +485,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..492339d57ecb 100644 --- a/examples/api/custom_scale_example.py +++ b/examples/api/custom_scale_example.py @@ -8,6 +8,7 @@ class MercatorLatitudeScale(mscale.ScaleBase): + """ Scales data in range -pi/2 to pi/2 (-90 to 90 degrees) using the system used to scale latitudes in a Mercator projection. @@ -32,7 +33,6 @@ class MercatorLatitudeScale(mscale.ScaleBase): # scale. name = 'mercator' - def __init__(self, axis, **kwargs): """ Any keyword arguments passed to ``set_xscale`` and @@ -71,13 +71,14 @@ def set_default_locators_and_formatters(self, axis): value:: """ class DegreeFormatter(Formatter): + def __call__(self, x, pos=None): # \u00b0 : degree symbol return "%d\u00b0" % ((x / np.pi) * 180.0) 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()) @@ -170,4 +171,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..daee303b2772 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,14 @@ 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..8ef7964e05a5 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") + # plt.savefig("demo_affine_image") diff --git a/examples/api/donut_demo.py b/examples/api/donut_demo.py index b36b0e7f3291..3d937c51e8f1 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..4e9b4877eb32 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..5a54abb24634 100644 --- a/examples/api/font_family_rc.py +++ b/examples/api/font_family_rc.py @@ -23,8 +23,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..ce010eefbd66 100644 --- a/examples/api/font_file.py +++ b/examples/api/font_file.py @@ -12,15 +12,15 @@ 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', - ] + '/usr/share/fonts/truetype/ttf-liberation/LiberationSans-BoldItalic.ttf', + '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf', + ] for fpath in fonts: if os.path.exists(fpath): break @@ -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..363441c03c66 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..2d92723acc87 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)] + phi = angle / 180 * np.pi + 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..045be80bb384 100644 --- a/examples/api/line_with_text.py +++ b/examples/api/line_with_text.py @@ -11,43 +11,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..38be45826a0b 100644 --- a/examples/api/logo2.py +++ b/examples/api/logo2.py @@ -13,10 +13,10 @@ axalpha = 0.05 -#figcolor = '#EFEFEF' +# 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,39 +25,43 @@ 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} = 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"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$", (0.15, 0.3), 25)) - #text.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$", + # 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)) 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 arc = 2. * np.pi - theta = np.arange(0.0, arc, arc/N) + theta = np.arange(0.0, arc, arc / N) radii = 10 * np.array([0.2, 0.6, 0.8, 0.7, 0.4, 0.5, 0.8]) width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3]) bars = ax.bar(theta, radii, width=width, bottom=0.0) for r, bar in zip(radii, bars): - bar.set_facecolor(cm.jet(r/10.)) + bar.set_facecolor(cm.jet(r / 10.)) bar.set_alpha(0.6) for label in ax.get_xticklabels() + ax.get_yticklabels(): diff --git a/examples/api/mathtext_asarray.py b/examples/api/mathtext_asarray.py index 049184ffa574..eb92e57cc75c 100644 --- a/examples/api/mathtext_asarray.py +++ b/examples/api/mathtext_asarray.py @@ -11,14 +11,18 @@ 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) +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) +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) -fig.figimage(rgba2.astype(float)/255., 100, 300) +fig.figimage(rgba1.astype(float) / 255., 100, 100) +fig.figimage(rgba2.astype(float) / 255., 100, 300) plt.show() diff --git a/examples/api/patch_collection.py b/examples/api/patch_collection.py index 98b4ca4f6b58..49cb5d1feef6 100644 --- a/examples/api/patch_collection.py +++ b/examples/api/patch_collection.py @@ -7,38 +7,38 @@ 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)) +colors = 100 * np.random.rand(len(patches)) p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4) p.set_array(np.array(colors)) ax.add_collection(p) 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..ebcdfdd06f74 100644 --- a/examples/api/radar_chart.py +++ b/examples/api/radar_chart.py @@ -32,9 +32,9 @@ 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 = 2 * np.pi * np.linspace(0, 1 - 1. / num_vars, num_vars) # rotate theta such that the first axis is at the top - theta += np.pi/2 + theta += np.pi / 2 def draw_poly_patch(self): verts = unit_poly_verts(theta) @@ -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() @@ -108,18 +108,18 @@ def unit_poly_verts(theta): This polygon is circumscribed by a unit circle centered at (0.5, 0.5) """ x0, y0, r = [0.5] * 3 - verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] + verts = [(r * np.cos(t) + x0, r * np.sin(t) + y0) for t in theta] return verts 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 @@ -133,32 +133,32 @@ def example_data(): # 4)Inclusion of both gas-phase speciesis present... data = { 'column names': - ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', - 'O3'], + ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', + 'O3'], 'Basecase': - [[0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00], - [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00], - [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00], - [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00], - [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]], + [[0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00], + [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00], + [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00], + [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00], + [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]], 'With CO': - [[0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00], - [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00], - [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00], - [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00], - [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]], + [[0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00], + [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00], + [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00], + [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00], + [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]], 'With O3': - [[0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03], - [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00], - [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00], - [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95], - [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]], + [[0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03], + [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00], + [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00], + [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95], + [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]], 'CO & O3': - [[0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01], - [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00], - [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00], - [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88], - [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]]} + [[0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01], + [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00], + [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00], + [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88], + [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]]} return data @@ -175,7 +175,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..7c35f098b52d 100644 --- a/examples/api/sankey_demo_links.py +++ b/examples/api/sankey_demo_links.py @@ -13,13 +13,13 @@ def side(sankey, n=1): """Generate a side chain.""" prior = len(sankey.diagrams) colors = cycle(['orange', 'b', 'g', 'r', 'c', 'm', 'y']) - for i in range(0, 2*n, 2): + 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..d57de69ec9c0 100755 --- a/examples/api/sankey_demo_old.py +++ b/examples/api/sankey_demo_old.py @@ -43,58 +43,62 @@ 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 +148,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 +164,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..7d65f96d5166 100644 --- a/examples/api/sankey_demo_rankine.py +++ b/examples/api/sankey_demo_rankine.py @@ -12,8 +12,8 @@ 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 -sankey = Sankey(ax=ax, format='%.3G', unit=' MW', gap=0.5, scale=1.0/Hdot[0]) + 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]], labels=['Shaft power', '', None], diff --git a/examples/api/scatter_piecharts.py b/examples/api/scatter_piecharts.py index 424fa70411a2..4c7a27dc6bab 100644 --- a/examples/api/scatter_piecharts.py +++ b/examples/api/scatter_piecharts.py @@ -9,31 +9,34 @@ # 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 # # these are just the origin (0,0) + # 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)) +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)) # ... -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)) +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)) -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)) +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)) 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' ) +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') plt.show() diff --git a/examples/api/skewt.py b/examples/api/skewt.py index f05bcd6766b4..c1e0c575c711 100644 --- a/examples/api/skewt.py +++ b/examples/api/skewt.py @@ -18,9 +18,13 @@ # 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 @@ -48,6 +52,7 @@ def draw(self, renderer): # This class exists to provide two separate sets of intervals to the tick, # as well as create instances of the custom tick class SkewXAxis(maxis.XAxis): + def __init__(self, *args, **kwargs): maxis.XAxis.__init__(self, *args, **kwargs) self.upper_interval = 0.0, 1.0 @@ -67,6 +72,7 @@ def get_view_interval(self): # upper X-axis and draw the spine there. It also provides this range # to the X-axis artist for ticking and gridlines class SkewSpine(mspines.Spine): + def _adjust_location(self): trans = self.axes.transDataToAxes.inverted() if self.spine_type == 'top': @@ -76,7 +82,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 +98,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 +107,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 +120,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 +128,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 +137,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. @@ -147,7 +153,7 @@ def _set_lim_and_transforms(self): 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 @@ -225,7 +231,7 @@ def _set_lim_and_transforms(self): # 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 +249,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..0038de7a2585 100644 --- a/examples/api/span_regions.py +++ b/examples/api/span_regions.py @@ -10,8 +10,8 @@ t = np.arange(0.0, 2, 0.01) -s1 = np.sin(2*np.pi*t) -s2 = 1.2*np.sin(4*np.pi*t) +s1 = np.sin(2 * np.pi * t) +s2 = 1.2 * np.sin(4 * np.pi * t) fig, ax = plt.subplots() @@ -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..917c38b52069 100644 --- a/examples/api/two_scales.py +++ b/examples/api/two_scales.py @@ -36,10 +36,9 @@ ax2 = ax1.twinx() -s2 = np.sin(2*np.pi*t) +s2 = np.sin(2 * np.pi * t) ax2.plot(t, s2, 'r.') ax2.set_ylabel('sin', color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') plt.show() - diff --git a/examples/api/unicode_minus.py b/examples/api/unicode_minus.py index d84fb04f5b03..4947e52eebf1 100644 --- a/examples/api/unicode_minus.py +++ b/examples/api/unicode_minus.py @@ -12,6 +12,6 @@ matplotlib.rcParams['axes.unicode_minus'] = False fig, ax = plt.subplots() -ax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o') +ax.plot(10 * np.random.randn(100), 10 * np.random.randn(100), 'o') ax.set_title('Using hypen instead of unicode minus') plt.show() diff --git a/examples/api/watermark_image.py b/examples/api/watermark_image.py index 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/api/watermark_text.py b/examples/api/watermark_text.py index 0d09141050a9..3efa5000f1f9 100644 --- a/examples/api/watermark_text.py +++ b/examples/api/watermark_text.py @@ -3,7 +3,7 @@ """ import numpy as np #import matplotlib -#matplotlib.use('Agg') +# matplotlib.use('Agg') import matplotlib.pyplot as plt From 33b10ba67338145d84968762e9056307d2c81f93 Mon Sep 17 00:00:00 2001 From: Thomas Hisch Date: Wed, 2 Jul 2014 21:49:41 +0200 Subject: [PATCH 2/2] use np.radians/np.degrees in examples/api where appropriate --- examples/api/custom_projection_example.py | 8 ++++---- examples/api/custom_scale_example.py | 7 +++---- examples/api/joinstyle.py | 2 +- examples/api/radar_chart.py | 2 +- examples/api/sankey_demo_old.py | 4 ++-- 5 files changed, 11 insertions(+), 12 deletions(-) diff --git a/examples/api/custom_projection_example.py b/examples/api/custom_projection_example.py index 4f4c02fb8b50..7a88f526d9d5 100644 --- a/examples/api/custom_projection_example.py +++ b/examples/api/custom_projection_example.py @@ -273,8 +273,8 @@ def format_coord(self, lon, lat): In this case, we want them to be displayed in degrees N/S/E/W. """ - lon = lon * (180.0 / np.pi) - lat = lat * (180.0 / np.pi) + lon = np.degrees(lon) + lat = np.degrees(lat) if lat >= 0.0: ns = 'N' else: @@ -297,7 +297,7 @@ def __init__(self, round_to=1.0): self._round_to = round_to def __call__(self, x, pos=None): - degrees = (x / np.pi) * 180.0 + degrees = np.degrees(x) degrees = round(degrees / self._round_to) * self._round_to # \u00b0 : degree symbol return "%d\u00b0" % degrees @@ -350,7 +350,7 @@ def set_longitude_grid_ends(self, degrees): class -- it provides an interface to something that has no analogy in the base Axes class. """ - longitude_cap = degrees * (np.pi / 180.0) + longitude_cap = np.radians(degrees) # Change the xaxis gridlines transform so that it draws from # -degrees to degrees, rather than -pi to pi. self._xaxis_pretransform \ diff --git a/examples/api/custom_scale_example.py b/examples/api/custom_scale_example.py index 492339d57ecb..9f45caabf34b 100644 --- a/examples/api/custom_scale_example.py +++ b/examples/api/custom_scale_example.py @@ -42,7 +42,7 @@ def __init__(self, axis, **kwargs): thresh: The degree above which to crop the data. """ mscale.ScaleBase.__init__(self) - thresh = kwargs.pop("thresh", (85 / 180.0) * np.pi) + thresh = kwargs.pop("thresh", np.radians(85)) if thresh >= np.pi / 2.0: raise ValueError("thresh must be less than pi/2") self.thresh = thresh @@ -74,11 +74,10 @@ class DegreeFormatter(Formatter): def __call__(self, x, pos=None): # \u00b0 : degree symbol - return "%d\u00b0" % ((x / np.pi) * 180.0) + return "%d\u00b0" % np.degrees(x) - deg2rad = np.pi / 180.0 axis.set_major_locator(FixedLocator( - np.arange(-90, 90, 10) * deg2rad)) + np.radians(np.arange(-90, 90, 10)))) axis.set_major_formatter(DegreeFormatter()) axis.set_minor_formatter(DegreeFormatter()) diff --git a/examples/api/joinstyle.py b/examples/api/joinstyle.py index 2d92723acc87..07ebaa277e1b 100644 --- a/examples/api/joinstyle.py +++ b/examples/api/joinstyle.py @@ -8,7 +8,7 @@ def plot_angle(ax, x, y, angle, style): - phi = angle / 180 * np.pi + phi = np.radians(angle) 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) diff --git a/examples/api/radar_chart.py b/examples/api/radar_chart.py index ebcdfdd06f74..c2d55a0e482a 100644 --- a/examples/api/radar_chart.py +++ b/examples/api/radar_chart.py @@ -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(np.degrees(theta), labels) def _gen_axes_patch(self): return self.draw_patch() diff --git a/examples/api/sankey_demo_old.py b/examples/api/sankey_demo_old.py index d57de69ec9c0..d1da9e768e01 100755 --- a/examples/api/sankey_demo_old.py +++ b/examples/api/sankey_demo_old.py @@ -44,7 +44,7 @@ def sankey(ax, def add_output(path, loss, sign=1): # Arrow tip height - h = (loss / 2 + w) * np.tan(outangle / 180. * np.pi) + h = (loss / 2 + w) * np.tan(np.radians(outangle)) move, (x, y) = path[-1] # Use last point as reference if sign == 0: # Final loss (horizontal) path.extend([(Path.LINETO, [x + dx, y]), @@ -67,7 +67,7 @@ def add_output(path, loss, sign=1): 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(np.radians(inangle)) # 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]),