From ea9250d92045b56c899bbdb7eee7d7ff07ae1029 Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Tue, 21 Mar 2017 23:27:12 +0530 Subject: [PATCH 01/18] numpydocstring added --- lib/matplotlib/axes/_axes.py | 164 ++++++++++++++++++----------------- 1 file changed, 83 insertions(+), 81 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 882a3965d7c6..d8a49bf0992c 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -14,7 +14,7 @@ import matplotlib from matplotlib import _preprocess_data - + import matplotlib.cbook as cbook from matplotlib.cbook import (mplDeprecation, STEP_LOOKUP_MAP, iterable, is_string_like, @@ -57,7 +57,7 @@ 'markeredgecolor': ['mec'], 'markeredgewidth': ['mew'], 'markersize': ['ms'], - } + } def _plot_args_replacer(args, data): @@ -1064,7 +1064,7 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', verts = [((thisx, thisymin), (thisx, thisymax)) for thisx, thisymin, thisymax in zip(x, ymin, ymax)] - #print 'creating line collection' + # print 'creating line collection' lines = mcoll.LineCollection(verts, colors=colors, linestyles=linestyles, label=label) self.add_collection(lines, autolim=False) @@ -1083,9 +1083,9 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', return lines @_preprocess_data(replace_names=["positions", "lineoffsets", - "linelengths", "linewidths", - "colors", "linestyles"], - label_namer=None) + "linelengths", "linewidths", + "colors", "linestyles"], + label_namer=None) @docstring.dedent_interpd def eventplot(self, positions, orientation='horizontal', lineoffsets=1, linelengths=1, linewidths=None, colors=None, @@ -1227,7 +1227,7 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1, colls = [] for position, lineoffset, linelength, linewidth, color, linestyle in \ zip(positions, lineoffsets, linelengths, linewidths, - colors, linestyles): + colors, linestyles): coll = mcoll.EventCollection(position, orientation=orientation, lineoffset=lineoffset, @@ -1264,8 +1264,8 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1, # ### Basic plotting # The label_naming happens in `matplotlib.axes._base._plot_args` @_preprocess_data(replace_names=["x", "y"], - positional_parameter_names=_plot_args_replacer, - label_namer=None) + positional_parameter_names=_plot_args_replacer, + label_namer=None) @docstring.dedent_interpd def plot(self, *args, **kwargs): """ @@ -1858,10 +1858,10 @@ def step(self, x, y, *args, **kwargs): return self.plot(x, y, *args, **kwargs) @_preprocess_data(replace_names=["left", "height", "width", "bottom", - "color", "edgecolor", "linewidth", - "tick_label", "xerr", "yerr", - "ecolor"], - label_namer=None) + "color", "edgecolor", "linewidth", + "tick_label", "xerr", "yerr", + "ecolor"], + label_namer=None) @docstring.dedent_interpd def bar(self, left, height, width=0.8, bottom=None, **kwargs): """ @@ -2470,14 +2470,13 @@ def stem(self, *args, **kwargs): return stem_container @_preprocess_data(replace_names=['x', 'explode', 'labels', 'colors'], - label_namer=None) + label_namer=None) def pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False): - r""" - Plot a pie chart. + r"""Plot a pie chart. Make a pie chart of array *x*. The fractional area of each wedge is given by x/sum(x). If sum(x) <= 1, then the values @@ -2485,90 +2484,94 @@ def pie(self, x, explode=None, labels=None, colors=None, be normalized. The wedges are plotted counterclockwise, by default starting from the x-axis. - Keyword arguments: + Parameters + ---------- + x : array + The input array used to make the pie chart. - *explode*: [ *None* | len(x) sequence ] + explode: None or array If not *None*, is a ``len(x)`` array which specifies the fraction of the radius with which to offset each wedge. - *colors*: [ *None* | color sequence ] + colors: None or array A sequence of matplotlib color args through which the pie chart will cycle. If `None`, will use the colors in the currently active cycle. - *labels*: [ *None* | len(x) sequence of strings ] + labels: None or list A sequence of strings providing the labels for each wedge - *autopct*: [ *None* | format string | format function ] + autopct: None or string or function If not *None*, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be ``fmt%pct``. If it is a function, it will be called. - *pctdistance*: scalar + pctdistance: float The ratio between the center of each pie slice and the start of the text generated by *autopct*. Ignored if *autopct* is *None*; default is 0.6. - *labeldistance*: scalar + labeldistance: float The radial distance at which the pie labels are drawn - *shadow*: [ *False* | *True* ] + shadow: bool Draw a shadow beneath the pie. - *startangle*: [ *None* | Offset angle ] + startangle: None or Offset angle If not *None*, rotates the start of the pie chart by *angle* degrees counterclockwise from the x-axis. - *radius*: [ *None* | scalar ] + radius: None or float The radius of the pie, if *radius* is *None* it will be set to 1. - *counterclock*: [ *False* | *True* ] + counterclock: bool Specify fractions direction, clockwise or counterclockwise. - *wedgeprops*: [ *None* | dict of key value pairs ] + wedgeprops: None or dict Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = { 'linewidth' : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default `clip_on=False`. - *textprops*: [ *None* | dict of key value pairs ] + textprops: None or dict Dict of arguments to pass to the text objects. - *center*: [ (0,0) | sequence of 2 scalars ] - Center position of the chart. + center: list of int + Center position of the chart. Takes value (0,0) or is a sequence + of 2 scalars. - *frame*: [ *False* | *True* ] - Plot axes frame with the chart. + frame: bool + Plot axes frame with the chart if true. - *rotatelabels*: [ *False* | *True* ] - Rotate each label to the angle of the corresponding slice. + rotatelabels: bool + Rotate each label to the angle of the corresponding slice if true. - The pie chart will probably look best if the figure and axes are - square, or the Axes aspect is equal. e.g.:: - - figure(figsize=(8,8)) - ax = axes([0.1, 0.1, 0.8, 0.8]) + Returns + ------- + patches: list + A sequence of :class:`matplotlib.patches.Wedge` instances - or:: + texts: list + A is a list of the label :class:`matplotlib.text.Text` instances. - axes(aspect=1) + autotexts: list + A is a list of :class:`~matplotlib.text.Text` instances for the + numeric labels. Is returned only is if parameter *autopct* is + not *None*. If *autopct* is *None*, the tuple returned + is (patches, texts). - Return value: - If *autopct* is *None*, return the tuple (*patches*, *texts*): + Examples + -------- + The pie chart will probably look best if the figure and axes are + square, or the Axes aspect is equal. - - *patches* is a sequence of - :class:`matplotlib.patches.Wedge` instances + >>> figure(figsize=(8,8)) + >>> ax = axes([0.1, 0.1, 0.8, 0.8]) - - *texts* is a list of the label - :class:`matplotlib.text.Text` instances. + >>> axes(aspect=1) - If *autopct* is not *None*, return the tuple (*patches*, - *texts*, *autotexts*), where *patches* and *texts* are as - above, and *autotexts* is a list of - :class:`~matplotlib.text.Text` instances for the numeric - labels. """ x = np.array(x, np.float32) @@ -2624,9 +2627,9 @@ def get_next_color(): y += expl * math.sin(thetam) w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2), - 360. * max(theta1, theta2), - facecolor=get_next_color(), - **wedgeprops) + 360. * max(theta1, theta2), + facecolor=get_next_color(), + **wedgeprops) slices.append(w) self.add_patch(w) w.set_label(label) @@ -2683,9 +2686,9 @@ def get_next_color(): self.set_frame_on(False) self.set_xlim((-1.25 + center[0], - 1.25 + center[0])) + 1.25 + center[0])) self.set_ylim((-1.25 + center[1], - 1.25 + center[1])) + 1.25 + center[1])) self.set_xticks([]) self.set_yticks([]) @@ -2695,7 +2698,7 @@ def get_next_color(): return slices, texts, autotexts @_preprocess_data(replace_names=["x", "y", "xerr", "yerr"], - label_namer="y") + label_namer="y") @docstring.dedent_interpd def errorbar(self, x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, @@ -3306,7 +3309,8 @@ def _update_dict(dictionary, rc_name, properties): dictionary = dict() for prop_dict in properties: dictionary.setdefault(prop_dict, - rcParams[rc_str.format(rc_name, prop_dict)]) + rcParams[rc_str.format(rc_name, + prop_dict)]) return dictionary # Common property dictionnaries loading from rc @@ -3316,7 +3320,7 @@ def _update_dict(dictionary, rc_name, properties): boxprops = _update_dict(boxprops, 'boxprops', default_props) whiskerprops = _update_dict(whiskerprops, 'whiskerprops', - default_props) + default_props) capprops = _update_dict(capprops, 'capprops', default_props) medianprops = _update_dict(medianprops, 'medianprops', default_props) meanprops = _update_dict(meanprops, 'meanprops', default_props) @@ -3808,9 +3812,9 @@ def dopatch(xs, ys, **kwargs): medians=medians, fliers=fliers, means=means) @_preprocess_data(replace_names=["x", "y", "s", "linewidths", - "edgecolors", "c", 'facecolor', - 'facecolors', 'color'], - label_namer="y") + "edgecolors", "c", 'facecolor', + 'facecolors', 'color'], + label_namer="y") def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, @@ -4614,7 +4618,7 @@ def stackplot(self, x, *args, **kwargs): stackplot.__doc__ = mstack.stackplot.__doc__ @_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"], - label_namer=None) + label_namer=None) def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, zorder=None, @@ -4714,7 +4718,7 @@ def fill(self, *args, **kwargs): return patches @_preprocess_data(replace_names=["x", "y1", "y2", "where"], - label_namer=None) + label_namer=None) @docstring.dedent_interpd def fill_between(self, x, y1, y2=0, where=None, interpolate=False, step=None, @@ -4883,7 +4887,7 @@ def get_interp_point(ind): return collection @_preprocess_data(replace_names=["y", "x1", "x2", "where"], - label_namer=None) + label_namer=None) @docstring.dedent_interpd def fill_betweenx(self, y, x1, x2=0, where=None, step=None, interpolate=False, **kwargs): @@ -5182,7 +5186,7 @@ def imshow(self, X, cmap=None, norm=None, aspect=None, if im.get_clip_path() is None: # image does not already have clipping set, clip to axes patch im.set_clip_path(self.patch) - #if norm is None and shape is None: + # if norm is None and shape is None: # im.set_clim(vmin, vmax) if vmin is not None or vmax is not None: im.set_clim(vmin, vmax) @@ -5242,7 +5246,7 @@ def _pcolorargs(funcname, *args, **kw): if X.shape != Y.shape: raise TypeError( 'Incompatible X, Y inputs to %s; see help(%s)' % ( - funcname, funcname)) + funcname, funcname)) if allmatch: if not (Nx == numCols and Ny == numRows): raise TypeError('Dimensions of C %s are incompatible with' @@ -5494,7 +5498,7 @@ def pcolor(self, *args, **kwargs): # Transform from native to data coordinates? t = collection._transform if (not isinstance(t, mtransforms.Transform) and - hasattr(t, '_as_mpl_transform')): + hasattr(t, '_as_mpl_transform')): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): @@ -5646,7 +5650,7 @@ def pcolormesh(self, *args, **kwargs): # Transform from native to data coordinates? t = collection._transform if (not isinstance(t, mtransforms.Transform) and - hasattr(t, '_as_mpl_transform')): + hasattr(t, '_as_mpl_transform')): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): @@ -7345,7 +7349,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None, nr, nc = Z.shape extent = [-0.5, nc - 0.5, nr - 0.5, -0.5] ret = self.imshow(mask, interpolation='nearest', aspect=aspect, - extent=extent, origin=origin, **kwargs) + extent=extent, origin=origin, **kwargs) else: if hasattr(Z, 'tocoo'): c = Z.tocoo() @@ -7365,7 +7369,8 @@ def spy(self, Z, precision=0, marker=None, markersize=None, if markersize is None: markersize = 10 marks = mlines.Line2D(x, y, linestyle='None', - marker=marker, markersize=markersize, **kwargs) + marker=marker, markersize=markersize, + **kwargs) self.add_line(marks) nr, nc = Z.shape self.set_xlim(xmin=-0.5, xmax=nc - 0.5) @@ -7376,11 +7381,9 @@ def spy(self, Z, precision=0, marker=None, markersize=None, self.xaxis.tick_top() self.xaxis.set_ticks_position('both') self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], - integer=True)) + steps=[1, 2, 5, 10], integer=True)) self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], - integer=True)) + steps=[1, 2, 5, 10], integer=True)) return ret def matshow(self, Z, **kwargs): @@ -7425,11 +7428,10 @@ def matshow(self, Z, **kwargs): self.xaxis.tick_top() self.xaxis.set_ticks_position('both') self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], - integer=True)) + steps=[1, 2, 5, 10], integer=True)) self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], - integer=True)) + steps=[1, 2, 5, 10], + integer=True)) return im @_preprocess_data(replace_names=["dataset"], label_namer=None) From d4d912b8cff5a5e424a12d6152cdb623bcf1ab8f Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Tue, 21 Mar 2017 23:37:52 +0530 Subject: [PATCH 02/18] . --- lib/matplotlib/axes/_axes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index d8a49bf0992c..e14c1af9fa66 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -14,7 +14,7 @@ import matplotlib from matplotlib import _preprocess_data - + import matplotlib.cbook as cbook from matplotlib.cbook import (mplDeprecation, STEP_LOOKUP_MAP, iterable, is_string_like, From 492b0ac6f498caf6684aafaad8d349e776974ad6 Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Wed, 22 Mar 2017 09:29:17 +0530 Subject: [PATCH 03/18] Revert "numpydocstring added" This reverts commit ea9250d92045b56c899bbdb7eee7d7ff07ae1029. --- lib/matplotlib/axes/_axes.py | 162 +++++++++++++++++------------------ 1 file changed, 80 insertions(+), 82 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 08bb3b7fb5b1..76dc174e2f53 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -56,7 +56,7 @@ 'markeredgecolor': ['mec'], 'markeredgewidth': ['mew'], 'markersize': ['ms'], - } + } def _plot_args_replacer(args, data): @@ -1063,7 +1063,7 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', verts = [((thisx, thisymin), (thisx, thisymax)) for thisx, thisymin, thisymax in zip(x, ymin, ymax)] - # print 'creating line collection' + #print 'creating line collection' lines = mcoll.LineCollection(verts, colors=colors, linestyles=linestyles, label=label) self.add_collection(lines, autolim=False) @@ -1082,9 +1082,9 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', return lines @_preprocess_data(replace_names=["positions", "lineoffsets", - "linelengths", "linewidths", - "colors", "linestyles"], - label_namer=None) + "linelengths", "linewidths", + "colors", "linestyles"], + label_namer=None) @docstring.dedent_interpd def eventplot(self, positions, orientation='horizontal', lineoffsets=1, linelengths=1, linewidths=None, colors=None, @@ -1226,7 +1226,7 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1, colls = [] for position, lineoffset, linelength, linewidth, color, linestyle in \ zip(positions, lineoffsets, linelengths, linewidths, - colors, linestyles): + colors, linestyles): coll = mcoll.EventCollection(position, orientation=orientation, lineoffset=lineoffset, @@ -1263,8 +1263,8 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1, # ### Basic plotting # The label_naming happens in `matplotlib.axes._base._plot_args` @_preprocess_data(replace_names=["x", "y"], - positional_parameter_names=_plot_args_replacer, - label_namer=None) + positional_parameter_names=_plot_args_replacer, + label_namer=None) @docstring.dedent_interpd def plot(self, *args, **kwargs): """ @@ -1857,10 +1857,10 @@ def step(self, x, y, *args, **kwargs): return self.plot(x, y, *args, **kwargs) @_preprocess_data(replace_names=["left", "height", "width", "bottom", - "color", "edgecolor", "linewidth", - "tick_label", "xerr", "yerr", - "ecolor"], - label_namer=None) + "color", "edgecolor", "linewidth", + "tick_label", "xerr", "yerr", + "ecolor"], + label_namer=None) @docstring.dedent_interpd def bar(self, left, height, width=0.8, bottom=None, **kwargs): """ @@ -2469,13 +2469,14 @@ def stem(self, *args, **kwargs): return stem_container @_preprocess_data(replace_names=['x', 'explode', 'labels', 'colors'], - label_namer=None) + label_namer=None) def pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False): - r"""Plot a pie chart. + r""" + Plot a pie chart. Make a pie chart of array *x*. The fractional area of each wedge is given by x/sum(x). If sum(x) <= 1, then the values @@ -2483,94 +2484,90 @@ def pie(self, x, explode=None, labels=None, colors=None, be normalized. The wedges are plotted counterclockwise, by default starting from the x-axis. - Parameters - ---------- - x : array - The input array used to make the pie chart. + Keyword arguments: - explode: None or array + *explode*: [ *None* | len(x) sequence ] If not *None*, is a ``len(x)`` array which specifies the fraction of the radius with which to offset each wedge. - colors: None or array + *colors*: [ *None* | color sequence ] A sequence of matplotlib color args through which the pie chart will cycle. If `None`, will use the colors in the currently active cycle. - labels: None or list + *labels*: [ *None* | len(x) sequence of strings ] A sequence of strings providing the labels for each wedge - autopct: None or string or function + *autopct*: [ *None* | format string | format function ] If not *None*, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be ``fmt%pct``. If it is a function, it will be called. - pctdistance: float + *pctdistance*: scalar The ratio between the center of each pie slice and the start of the text generated by *autopct*. Ignored if *autopct* is *None*; default is 0.6. - labeldistance: float + *labeldistance*: scalar The radial distance at which the pie labels are drawn - shadow: bool + *shadow*: [ *False* | *True* ] Draw a shadow beneath the pie. - startangle: None or Offset angle + *startangle*: [ *None* | Offset angle ] If not *None*, rotates the start of the pie chart by *angle* degrees counterclockwise from the x-axis. - radius: None or float + *radius*: [ *None* | scalar ] The radius of the pie, if *radius* is *None* it will be set to 1. - counterclock: bool + *counterclock*: [ *False* | *True* ] Specify fractions direction, clockwise or counterclockwise. - wedgeprops: None or dict + *wedgeprops*: [ *None* | dict of key value pairs ] Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = { 'linewidth' : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default `clip_on=False`. - textprops: None or dict + *textprops*: [ *None* | dict of key value pairs ] Dict of arguments to pass to the text objects. - center: list of int - Center position of the chart. Takes value (0,0) or is a sequence - of 2 scalars. + *center*: [ (0,0) | sequence of 2 scalars ] + Center position of the chart. - frame: bool - Plot axes frame with the chart if true. + *frame*: [ *False* | *True* ] + Plot axes frame with the chart. - rotatelabels: bool - Rotate each label to the angle of the corresponding slice if true. + *rotatelabels*: [ *False* | *True* ] + Rotate each label to the angle of the corresponding slice. - Returns - ------- - patches: list - A sequence of :class:`matplotlib.patches.Wedge` instances + The pie chart will probably look best if the figure and axes are + square, or the Axes aspect is equal. e.g.:: - texts: list - A is a list of the label :class:`matplotlib.text.Text` instances. + figure(figsize=(8,8)) + ax = axes([0.1, 0.1, 0.8, 0.8]) - autotexts: list - A is a list of :class:`~matplotlib.text.Text` instances for the - numeric labels. Is returned only is if parameter *autopct* is - not *None*. If *autopct* is *None*, the tuple returned - is (patches, texts). + or:: - Examples - -------- - The pie chart will probably look best if the figure and axes are - square, or the Axes aspect is equal. + axes(aspect=1) + + Return value: + If *autopct* is *None*, return the tuple (*patches*, *texts*): - >>> figure(figsize=(8,8)) - >>> ax = axes([0.1, 0.1, 0.8, 0.8]) + - *patches* is a sequence of + :class:`matplotlib.patches.Wedge` instances - >>> axes(aspect=1) + - *texts* is a list of the label + :class:`matplotlib.text.Text` instances. + If *autopct* is not *None*, return the tuple (*patches*, + *texts*, *autotexts*), where *patches* and *texts* are as + above, and *autotexts* is a list of + :class:`~matplotlib.text.Text` instances for the numeric + labels. """ x = np.array(x, np.float32) @@ -2626,9 +2623,9 @@ def get_next_color(): y += expl * math.sin(thetam) w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2), - 360. * max(theta1, theta2), - facecolor=get_next_color(), - **wedgeprops) + 360. * max(theta1, theta2), + facecolor=get_next_color(), + **wedgeprops) slices.append(w) self.add_patch(w) w.set_label(label) @@ -2685,9 +2682,9 @@ def get_next_color(): self.set_frame_on(False) self.set_xlim((-1.25 + center[0], - 1.25 + center[0])) + 1.25 + center[0])) self.set_ylim((-1.25 + center[1], - 1.25 + center[1])) + 1.25 + center[1])) self.set_xticks([]) self.set_yticks([]) @@ -2697,7 +2694,7 @@ def get_next_color(): return slices, texts, autotexts @_preprocess_data(replace_names=["x", "y", "xerr", "yerr"], - label_namer="y") + label_namer="y") @docstring.dedent_interpd def errorbar(self, x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, @@ -3308,8 +3305,7 @@ def _update_dict(dictionary, rc_name, properties): dictionary = dict() for prop_dict in properties: dictionary.setdefault(prop_dict, - rcParams[rc_str.format(rc_name, - prop_dict)]) + rcParams[rc_str.format(rc_name, prop_dict)]) return dictionary # Common property dictionnaries loading from rc @@ -3319,7 +3315,7 @@ def _update_dict(dictionary, rc_name, properties): boxprops = _update_dict(boxprops, 'boxprops', default_props) whiskerprops = _update_dict(whiskerprops, 'whiskerprops', - default_props) + default_props) capprops = _update_dict(capprops, 'capprops', default_props) medianprops = _update_dict(medianprops, 'medianprops', default_props) meanprops = _update_dict(meanprops, 'meanprops', default_props) @@ -3811,9 +3807,9 @@ def dopatch(xs, ys, **kwargs): medians=medians, fliers=fliers, means=means) @_preprocess_data(replace_names=["x", "y", "s", "linewidths", - "edgecolors", "c", 'facecolor', - 'facecolors', 'color'], - label_namer="y") + "edgecolors", "c", 'facecolor', + 'facecolors', 'color'], + label_namer="y") def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, @@ -4617,7 +4613,7 @@ def stackplot(self, x, *args, **kwargs): stackplot.__doc__ = mstack.stackplot.__doc__ @_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"], - label_namer=None) + label_namer=None) def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, zorder=None, @@ -4717,7 +4713,7 @@ def fill(self, *args, **kwargs): return patches @_preprocess_data(replace_names=["x", "y1", "y2", "where"], - label_namer=None) + label_namer=None) @docstring.dedent_interpd def fill_between(self, x, y1, y2=0, where=None, interpolate=False, step=None, @@ -4886,7 +4882,7 @@ def get_interp_point(ind): return collection @_preprocess_data(replace_names=["y", "x1", "x2", "where"], - label_namer=None) + label_namer=None) @docstring.dedent_interpd def fill_betweenx(self, y, x1, x2=0, where=None, step=None, interpolate=False, **kwargs): @@ -5185,7 +5181,7 @@ def imshow(self, X, cmap=None, norm=None, aspect=None, if im.get_clip_path() is None: # image does not already have clipping set, clip to axes patch im.set_clip_path(self.patch) - # if norm is None and shape is None: + #if norm is None and shape is None: # im.set_clim(vmin, vmax) if vmin is not None or vmax is not None: im.set_clim(vmin, vmax) @@ -5245,7 +5241,7 @@ def _pcolorargs(funcname, *args, **kw): if X.shape != Y.shape: raise TypeError( 'Incompatible X, Y inputs to %s; see help(%s)' % ( - funcname, funcname)) + funcname, funcname)) if allmatch: if not (Nx == numCols and Ny == numRows): raise TypeError('Dimensions of C %s are incompatible with' @@ -5497,7 +5493,7 @@ def pcolor(self, *args, **kwargs): # Transform from native to data coordinates? t = collection._transform if (not isinstance(t, mtransforms.Transform) and - hasattr(t, '_as_mpl_transform')): + hasattr(t, '_as_mpl_transform')): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): @@ -5649,7 +5645,7 @@ def pcolormesh(self, *args, **kwargs): # Transform from native to data coordinates? t = collection._transform if (not isinstance(t, mtransforms.Transform) and - hasattr(t, '_as_mpl_transform')): + hasattr(t, '_as_mpl_transform')): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): @@ -7348,7 +7344,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None, nr, nc = Z.shape extent = [-0.5, nc - 0.5, nr - 0.5, -0.5] ret = self.imshow(mask, interpolation='nearest', aspect=aspect, - extent=extent, origin=origin, **kwargs) + extent=extent, origin=origin, **kwargs) else: if hasattr(Z, 'tocoo'): c = Z.tocoo() @@ -7368,8 +7364,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None, if markersize is None: markersize = 10 marks = mlines.Line2D(x, y, linestyle='None', - marker=marker, markersize=markersize, - **kwargs) + marker=marker, markersize=markersize, **kwargs) self.add_line(marks) nr, nc = Z.shape self.set_xlim(xmin=-0.5, xmax=nc - 0.5) @@ -7380,9 +7375,11 @@ def spy(self, Z, precision=0, marker=None, markersize=None, self.xaxis.tick_top() self.xaxis.set_ticks_position('both') self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], integer=True)) + steps=[1, 2, 5, 10], + integer=True)) self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], integer=True)) + steps=[1, 2, 5, 10], + integer=True)) return ret def matshow(self, Z, **kwargs): @@ -7427,10 +7424,11 @@ def matshow(self, Z, **kwargs): self.xaxis.tick_top() self.xaxis.set_ticks_position('both') self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], integer=True)) + steps=[1, 2, 5, 10], + integer=True)) self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], - integer=True)) + steps=[1, 2, 5, 10], + integer=True)) return im @_preprocess_data(replace_names=["dataset"], label_namer=None) From 50aa3ffc63b7ca9ef17ea11b8f472fe87eed13a8 Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Wed, 22 Mar 2017 11:09:56 +0530 Subject: [PATCH 04/18] Docstring to Numpydoc Converts the docstring of pie() function in _ axes.py into numpydoc --- lib/matplotlib/axes/_axes.py | 81 +++++++++++++++++++----------------- 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 76dc174e2f53..bd62835d9afa 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -2475,8 +2475,7 @@ def pie(self, x, explode=None, labels=None, colors=None, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False): - r""" - Plot a pie chart. + r"""Plot a pie chart. Make a pie chart of array *x*. The fractional area of each wedge is given by x/sum(x). If sum(x) <= 1, then the values @@ -2484,90 +2483,94 @@ def pie(self, x, explode=None, labels=None, colors=None, be normalized. The wedges are plotted counterclockwise, by default starting from the x-axis. - Keyword arguments: + Parameters + ---------- + x : array + The input array used to make the pie chart. - *explode*: [ *None* | len(x) sequence ] + explode: None or array If not *None*, is a ``len(x)`` array which specifies the fraction of the radius with which to offset each wedge. - *colors*: [ *None* | color sequence ] + colors: None or array A sequence of matplotlib color args through which the pie chart will cycle. If `None`, will use the colors in the currently active cycle. - *labels*: [ *None* | len(x) sequence of strings ] + labels: None or list A sequence of strings providing the labels for each wedge - *autopct*: [ *None* | format string | format function ] + autopct: None or string or function If not *None*, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be ``fmt%pct``. If it is a function, it will be called. - *pctdistance*: scalar + pctdistance: float The ratio between the center of each pie slice and the start of the text generated by *autopct*. Ignored if *autopct* is *None*; default is 0.6. - *labeldistance*: scalar + labeldistance: float The radial distance at which the pie labels are drawn - *shadow*: [ *False* | *True* ] + shadow: bool Draw a shadow beneath the pie. - *startangle*: [ *None* | Offset angle ] + startangle: None or Offset angle If not *None*, rotates the start of the pie chart by *angle* degrees counterclockwise from the x-axis. - *radius*: [ *None* | scalar ] + radius: None or float The radius of the pie, if *radius* is *None* it will be set to 1. - *counterclock*: [ *False* | *True* ] + counterclock: bool Specify fractions direction, clockwise or counterclockwise. - *wedgeprops*: [ *None* | dict of key value pairs ] + wedgeprops: None or dict Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = { 'linewidth' : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default `clip_on=False`. - *textprops*: [ *None* | dict of key value pairs ] + textprops: None or dict Dict of arguments to pass to the text objects. - *center*: [ (0,0) | sequence of 2 scalars ] - Center position of the chart. - - *frame*: [ *False* | *True* ] - Plot axes frame with the chart. + center: list of int + Center position of the chart. Takes value (0,0) or is a sequence + of 2 scalars. - *rotatelabels*: [ *False* | *True* ] - Rotate each label to the angle of the corresponding slice. + frame: bool + Plot axes frame with the chart if true. - The pie chart will probably look best if the figure and axes are - square, or the Axes aspect is equal. e.g.:: + rotatelabels: bool + Rotate each label to the angle of the corresponding slice if true. - figure(figsize=(8,8)) - ax = axes([0.1, 0.1, 0.8, 0.8]) + Returns + ------- + patches: list + A sequence of :class:`matplotlib.patches.Wedge` instances - or:: + texts: list + A is a list of the label :class:`matplotlib.text.Text` instances. - axes(aspect=1) + autotexts: list + A is a list of :class:`~matplotlib.text.Text` instances for the + numeric labels. Is returned only is if parameter *autopct* is + not *None*. If *autopct* is *None*, the tuple returned + is (patches, texts). - Return value: - If *autopct* is *None*, return the tuple (*patches*, *texts*): + Notes + -------- + The pie chart will probably look best if the figure and axes are + square, or the Axes aspect is equal. - - *patches* is a sequence of - :class:`matplotlib.patches.Wedge` instances + >>> figure(figsize=(8,8)) + >>> ax = axes([0.1, 0.1, 0.8, 0.8]) - - *texts* is a list of the label - :class:`matplotlib.text.Text` instances. + >>> axes(aspect=1) - If *autopct* is not *None*, return the tuple (*patches*, - *texts*, *autotexts*), where *patches* and *texts* are as - above, and *autotexts* is a list of - :class:`~matplotlib.text.Text` instances for the numeric - labels. """ x = np.array(x, np.float32) From 8df19bdc55a9669b9b1d0eb74970bb06ed6ef682 Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Wed, 22 Mar 2017 11:52:01 +0530 Subject: [PATCH 05/18] FIX small nitpicks # Conflicts: # lib/matplotlib/tests/test_backend_pgf.py --- lib/matplotlib/tests/test_backend_pgf.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/matplotlib/tests/test_backend_pgf.py b/lib/matplotlib/tests/test_backend_pgf.py index 52151256f71a..36120aa785cf 100644 --- a/lib/matplotlib/tests/test_backend_pgf.py +++ b/lib/matplotlib/tests/test_backend_pgf.py @@ -81,9 +81,13 @@ def create_figure(): # test compiling a figure to pdf with xelatex +<<<<<<< HEAD @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_xelatex(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -93,9 +97,13 @@ def test_xelatex(): # test compiling a figure to pdf with pdflatex +<<<<<<< HEAD @needs_pdflatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_pdflatex(): import os if os.environ.get('APPVEYOR', False): @@ -113,10 +121,14 @@ def test_pdflatex(): # test updating the rc parameters for each figure +<<<<<<< HEAD @needs_xelatex @needs_pdflatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_rcupdate(): rc_sets = [] rc_sets.append({'font.family': 'sans-serif', @@ -145,9 +157,13 @@ def test_rcupdate(): # test backend-side clipping, since large numbers are not supported by TeX +<<<<<<< HEAD @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_pathclip(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -162,9 +178,13 @@ def test_pathclip(): # test mixed mode rendering +<<<<<<< HEAD @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_mixedmode(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -177,9 +197,13 @@ def test_mixedmode(): # test bbox_inches clipping +<<<<<<< HEAD @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_bbox_inches(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} From f57097820685041fce215a19150c5833a4826e57 Mon Sep 17 00:00:00 2001 From: sindunuragarp Date: Thu, 16 Mar 2017 18:30:06 +0100 Subject: [PATCH 06/18] removed duplicate matplotlib.transforms import --- lib/matplotlib/axes/_axes.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index e14c1af9fa66..08bb3b7fb5b1 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -40,7 +40,6 @@ import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.tri as mtri -import matplotlib.transforms as mtrans from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer from matplotlib.axes._base import _AxesBase from matplotlib.axes._base import _process_plot_format @@ -4255,8 +4254,8 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None, ymin, ymax = (np.min(y), np.max(y)) if len(y) else (0, 1) # to avoid issues with singular data, expand the min/max pairs - xmin, xmax = mtrans.nonsingular(xmin, xmax, expander=0.1) - ymin, ymax = mtrans.nonsingular(ymin, ymax, expander=0.1) + xmin, xmax = mtransforms.nonsingular(xmin, xmax, expander=0.1) + ymin, ymax = mtransforms.nonsingular(ymin, ymax, expander=0.1) # In the x-direction, the hexagons exactly cover the region from # xmin to xmax. Need some padding to avoid roundoff errors. From 027cbae67736522cdc1f1d5254a0f1edb4ee0e99 Mon Sep 17 00:00:00 2001 From: sindunuragarp Date: Sun, 19 Mar 2017 15:42:31 +0100 Subject: [PATCH 07/18] Standardized matplotlib transforms import from "as mtrans" into "as mtransforms" --- examples/pylab_examples/transoffset.py | 8 +- lib/matplotlib/colorbar.py | 16 ++-- lib/matplotlib/contour.py | 4 +- lib/matplotlib/patheffects.py | 5 +- lib/matplotlib/tests/test_artist.py | 14 ++-- lib/matplotlib/tests/test_legend.py | 4 +- lib/matplotlib/tests/test_patches.py | 4 +- lib/matplotlib/tests/test_transforms.py | 102 ++++++++++++------------ 8 files changed, 79 insertions(+), 78 deletions(-) diff --git a/examples/pylab_examples/transoffset.py b/examples/pylab_examples/transoffset.py index 1ee730b6fb56..381e9c6892d9 100644 --- a/examples/pylab_examples/transoffset.py +++ b/examples/pylab_examples/transoffset.py @@ -16,7 +16,7 @@ ''' import matplotlib.pyplot as plt -import matplotlib.transforms as mtrans +import matplotlib.transforms as mtransforms import numpy as np from matplotlib.transforms import offset_copy @@ -31,8 +31,8 @@ # we only need to make one transform. To get the # transform argument to offset_copy, we need to make the axes # first; the subplot command above is one way to do this. -trans_offset = mtrans.offset_copy(ax.transData, fig=fig, - x=0.05, y=0.10, units='inches') +trans_offset = mtransforms.offset_copy(ax.transData, fig=fig, + x=0.05, y=0.10, units='inches') for x, y in zip(xs, ys): plt.plot((x,), (y,), 'ro') @@ -42,7 +42,7 @@ # offset_copy works for polar plots also. ax = plt.subplot(2, 1, 2, projection='polar') -trans_offset = mtrans.offset_copy(ax.transData, fig=fig, y=6, units='dots') +trans_offset = mtransforms.offset_copy(ax.transData, fig=fig, y=6, units='dots') for x, y in zip(xs, ys): plt.polar((x,), (y,), 'ro') diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index df488bba7811..d0eae3ac3d27 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -39,7 +39,7 @@ import matplotlib.patches as mpatches import matplotlib.path as mpath import matplotlib.ticker as ticker -import matplotlib.transforms as mtrans +import matplotlib.transforms as mtransforms from matplotlib import docstring @@ -687,9 +687,9 @@ def _process_values(self, b=None): self.norm.vmin = 0 self.norm.vmax = 1 - self.norm.vmin, self.norm.vmax = mtrans.nonsingular(self.norm.vmin, - self.norm.vmax, - expander=0.1) + self.norm.vmin, self.norm.vmax = mtransforms.nonsingular(self.norm.vmin, + self.norm.vmax, + expander=0.1) b = self.norm.inverse(self._uniform_y(self.cmap.N + 1)) @@ -1126,8 +1126,8 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, 'parents share the same figure.') # take a bounding box around all of the given axes - parents_bbox = mtrans.Bbox.union([ax.get_position(original=True).frozen() - for ax in parents]) + parents_bbox = mtransforms.Bbox.union([ax.get_position(original=True).frozen() + for ax in parents]) pb = parents_bbox if location in ('left', 'right'): @@ -1148,12 +1148,12 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, # define a transform which takes us from old axes coordinates to # new axes coordinates - shrinking_trans = mtrans.BboxTransform(parents_bbox, pb1) + shrinking_trans = mtransforms.BboxTransform(parents_bbox, pb1) # transform each of the axes in parents using the new transform for ax in parents: new_posn = shrinking_trans.transform(ax.get_position()) - new_posn = mtrans.Bbox(new_posn) + new_posn = mtransforms.Bbox(new_posn) ax.set_position(new_posn) if parent_anchor is not False: ax.set_anchor(parent_anchor) diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index 3264c67ad2e8..ab9b1b1cedf3 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -26,7 +26,7 @@ import matplotlib.mathtext as mathtext import matplotlib.patches as mpatches import matplotlib.texmanager as texmanager -import matplotlib.transforms as mtrans +import matplotlib.transforms as mtransforms from matplotlib.cbook import mplDeprecation # Import needed for adding manual selection capability to clabel @@ -967,7 +967,7 @@ def get_transform(self): """ if self._transform is None: self._transform = self.ax.transData - elif (not isinstance(self._transform, mtrans.Transform) + elif (not isinstance(self._transform, mtransforms.Transform) and hasattr(self._transform, '_as_mpl_transform')): self._transform = self._transform._as_mpl_transform(self.ax) return self._transform diff --git a/lib/matplotlib/patheffects.py b/lib/matplotlib/patheffects.py index eaaf3d03fd53..30222e66cd93 100644 --- a/lib/matplotlib/patheffects.py +++ b/lib/matplotlib/patheffects.py @@ -10,8 +10,9 @@ import six from matplotlib.backend_bases import RendererBase -from matplotlib import ( - colors as mcolors, patches as mpatches, transforms as mtransforms) +from matplotlib import colors as mcolors +from matplotlib import patches as mpatches +from matplotlib import transforms as mtransforms class AbstractPathEffect(object): diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index 906338cdba18..dcf4b7bb10aa 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -11,7 +11,7 @@ import matplotlib.patches as mpatches import matplotlib.lines as mlines import matplotlib.path as mpath -import matplotlib.transforms as mtrans +import matplotlib.transforms as mtransforms import matplotlib.collections as mcollections import matplotlib.artist as martist from matplotlib.testing.decorators import image_comparison @@ -39,13 +39,13 @@ def test_patch_transform_of_none(): transform=None, alpha=0.5) assert e.is_transform_set() is True ax.add_patch(e) - assert isinstance(e._transform, mtrans.IdentityTransform) + assert isinstance(e._transform, mtransforms.IdentityTransform) # Providing an IdentityTransform puts the ellipse in device coordinates. e = mpatches.Ellipse(xy_pix, width=100, height=100, - transform=mtrans.IdentityTransform(), alpha=0.5) + transform=mtransforms.IdentityTransform(), alpha=0.5) ax.add_patch(e) - assert isinstance(e._transform, mtrans.IdentityTransform) + assert isinstance(e._transform, mtransforms.IdentityTransform) # Not providing a transform, and then subsequently "get_transform" should # not mean that "is_transform_set". @@ -84,14 +84,14 @@ def test_collection_transform_of_none(): alpha=0.5) c.set_transform(None) ax.add_collection(c) - assert isinstance(c.get_transform(), mtrans.IdentityTransform) + assert isinstance(c.get_transform(), mtransforms.IdentityTransform) # providing an IdentityTransform puts the ellipse in device coordinates e = mpatches.Ellipse(xy_pix, width=100, height=100) - c = mcollections.PatchCollection([e], transform=mtrans.IdentityTransform(), + c = mcollections.PatchCollection([e], transform=mtransforms.IdentityTransform(), alpha=0.5) ax.add_collection(c) - assert isinstance(c._transOffset, mtrans.IdentityTransform) + assert isinstance(c._transOffset, mtransforms.IdentityTransform) @image_comparison(baseline_images=["clip_path_clipping"], remove_text=True) diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index de5650e0f19a..bee550445337 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -12,7 +12,7 @@ from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib as mpl -import matplotlib.transforms as mtrans +import matplotlib.transforms as mtransforms import matplotlib.collections as mcollections from matplotlib.legend_handler import HandlerTuple @@ -293,7 +293,7 @@ def test_not_covering_scatter(): extensions=['png']) def test_not_covering_scatter_transform(): # Offsets point to top left, the default auto position - offset = mtrans.Affine2D().translate(-20, 20) + offset = mtransforms.Affine2D().translate(-20, 20) x = np.linspace(0, 30, 1000) plt.plot(x, x) diff --git a/lib/matplotlib/tests/test_patches.py b/lib/matplotlib/tests/test_patches.py index 1c5cc9d5accc..f7722241e47b 100644 --- a/lib/matplotlib/tests/test_patches.py +++ b/lib/matplotlib/tests/test_patches.py @@ -17,7 +17,7 @@ import matplotlib.patches as mpatches import matplotlib.collections as mcollections from matplotlib import path as mpath -from matplotlib import transforms as mtrans +from matplotlib import transforms as mtransforms import matplotlib.style as mstyle import sys @@ -113,7 +113,7 @@ def test_clip_to_bbox(): combined, alpha=0.5, facecolor='coral', edgecolor='none') ax.add_patch(patch) - bbox = mtrans.Bbox([[-12, -77.5], [50, -110]]) + bbox = mtransforms.Bbox([[-12, -77.5], [50, -110]]) result_path = combined.clip_to_bbox(bbox) result_patch = mpatches.PathPatch( result_path, alpha=0.5, facecolor='green', lw=4, edgecolor='black') diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index 61d698510140..0d47f58dc46d 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -12,14 +12,14 @@ import matplotlib.pyplot as plt import matplotlib.patches as mpatches -import matplotlib.transforms as mtrans +import matplotlib.transforms as mtransforms from matplotlib.path import Path from matplotlib.scale import LogScale from matplotlib.testing.decorators import image_comparison def test_non_affine_caching(): - class AssertingNonAffineTransform(mtrans.Transform): + class AssertingNonAffineTransform(mtransforms.Transform): """ This transform raises an assertion error when called when it shouldn't be and self.raise_on_transform is True. @@ -29,9 +29,9 @@ class AssertingNonAffineTransform(mtrans.Transform): is_affine = False def __init__(self, *args, **kwargs): - mtrans.Transform.__init__(self, *args, **kwargs) + mtransforms.Transform.__init__(self, *args, **kwargs) self.raise_on_transform = False - self.underlying_transform = mtrans.Affine2D().scale(10, 10) + self.underlying_transform = mtransforms.Affine2D().scale(10, 10) def transform_path_non_affine(self, path): assert not self.raise_on_transform, \ @@ -62,7 +62,7 @@ def __init__(self, scale_factor): self._scale_factor = scale_factor def _as_mpl_transform(self, axes): - return mtrans.Affine2D().scale(self._scale_factor) + axes.transData + return mtransforms.Affine2D().scale(self._scale_factor) + axes.transData ax = plt.axes() line, = plt.plot(np.arange(10), transform=ScaledBy(10)) @@ -70,7 +70,7 @@ def _as_mpl_transform(self, axes): ax.set_ylim(0, 100) # assert that the top transform of the line is the scale transform. assert_allclose(line.get_transform()._a.get_matrix(), - mtrans.Affine2D().scale(10).get_matrix()) + mtransforms.Affine2D().scale(10).get_matrix()) @image_comparison(baseline_images=['pre_transform_data'], @@ -80,7 +80,7 @@ def test_pre_transform_plotting(): # pre-transforming the data NOTE: The axis range is important in this # plot. It should be x10 what the data suggests it should be ax = plt.axes() - times10 = mtrans.Affine2D().scale(10) + times10 = mtransforms.Affine2D().scale(10) ax.contourf(np.arange(48).reshape(6, 8), transform=times10 + ax.transData) @@ -114,7 +114,7 @@ def test_contour_pre_transform_limits(): ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.contourf(xs, ys, np.log(xs * ys), - transform=mtrans.Affine2D().scale(0.1) + ax.transData) + transform=mtransforms.Affine2D().scale(0.1) + ax.transData) expected = np.array([[1.5, 1.24], [2., 1.25]]) @@ -126,7 +126,7 @@ def test_pcolor_pre_transform_limits(): ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.pcolor(xs, ys, np.log(xs * ys), - transform=mtrans.Affine2D().scale(0.1) + ax.transData) + transform=mtransforms.Affine2D().scale(0.1) + ax.transData) expected = np.array([[1.5, 1.24], [2., 1.25]]) @@ -138,7 +138,7 @@ def test_pcolormesh_pre_transform_limits(): ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.pcolormesh(xs, ys, np.log(xs * ys), - transform=mtrans.Affine2D().scale(0.1) + ax.transData) + transform=mtransforms.Affine2D().scale(0.1) + ax.transData) expected = np.array([[1.5, 1.24], [2., 1.25]]) @@ -151,32 +151,32 @@ def test_Affine2D_from_values(): [-1, 0], ]) - t = mtrans.Affine2D.from_values(1, 0, 0, 0, 0, 0) + t = mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, 0) actual = t.transform(points) expected = np.array([[0, 0], [10, 0], [-1, 0]]) assert_almost_equal(actual, expected) - t = mtrans.Affine2D.from_values(0, 2, 0, 0, 0, 0) + t = mtransforms.Affine2D.from_values(0, 2, 0, 0, 0, 0) actual = t.transform(points) expected = np.array([[0, 0], [0, 20], [0, -2]]) assert_almost_equal(actual, expected) - t = mtrans.Affine2D.from_values(0, 0, 3, 0, 0, 0) + t = mtransforms.Affine2D.from_values(0, 0, 3, 0, 0, 0) actual = t.transform(points) expected = np.array([[0, 0], [60, 0], [0, 0]]) assert_almost_equal(actual, expected) - t = mtrans.Affine2D.from_values(0, 0, 0, 4, 0, 0) + t = mtransforms.Affine2D.from_values(0, 0, 0, 4, 0, 0) actual = t.transform(points) expected = np.array([[0, 0], [0, 80], [0, 0]]) assert_almost_equal(actual, expected) - t = mtrans.Affine2D.from_values(0, 0, 0, 0, 5, 0) + t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 5, 0) actual = t.transform(points) expected = np.array([[5, 0], [5, 0], [5, 0]]) assert_almost_equal(actual, expected) - t = mtrans.Affine2D.from_values(0, 0, 0, 0, 0, 6) + t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 0, 6) actual = t.transform(points) expected = np.array([[0, 6], [0, 6], [0, 6]]) assert_almost_equal(actual, expected) @@ -190,8 +190,8 @@ def test_clipping_of_log(): path = Path(points, codes) # something like this happens in plotting logarithmic histograms - trans = mtrans.BlendedGenericTransform(mtrans.Affine2D(), - LogScale.Log10Transform('clip')) + trans = mtransforms.BlendedGenericTransform(mtransforms.Affine2D(), + LogScale.Log10Transform('clip')) tpath = trans.transform_path_non_affine(path) result = tpath.iter_segments(trans.get_affine(), clip=(0, 0, 100, 100), @@ -201,7 +201,7 @@ def test_clipping_of_log(): assert_allclose(tcodes, [M, L, L, L, C]) -class NonAffineForTest(mtrans.Transform): +class NonAffineForTest(mtransforms.Transform): """ A class which looks like a non affine transform, but does whatever the given transform does (even if it is affine). This is very useful @@ -214,7 +214,7 @@ class NonAffineForTest(mtrans.Transform): def __init__(self, real_trans, *args, **kwargs): self.real_trans = real_trans - mtrans.Transform.__init__(self, *args, **kwargs) + mtransforms.Transform.__init__(self, *args, **kwargs) def transform_non_affine(self, values): return self.real_trans.transform(values) @@ -226,15 +226,15 @@ def transform_path_non_affine(self, path): class BasicTransformTests(unittest.TestCase): def setUp(self): - self.ta1 = mtrans.Affine2D(shorthand_name='ta1').rotate(np.pi / 2) - self.ta2 = mtrans.Affine2D(shorthand_name='ta2').translate(10, 0) - self.ta3 = mtrans.Affine2D(shorthand_name='ta3').scale(1, 2) + self.ta1 = mtransforms.Affine2D(shorthand_name='ta1').rotate(np.pi / 2) + self.ta2 = mtransforms.Affine2D(shorthand_name='ta2').translate(10, 0) + self.ta3 = mtransforms.Affine2D(shorthand_name='ta3').scale(1, 2) - self.tn1 = NonAffineForTest(mtrans.Affine2D().translate(1, 2), + self.tn1 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), shorthand_name='tn1') - self.tn2 = NonAffineForTest(mtrans.Affine2D().translate(1, 2), + self.tn2 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), shorthand_name='tn2') - self.tn3 = NonAffineForTest(mtrans.Affine2D().translate(1, 2), + self.tn3 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), shorthand_name='tn3') # creates a transform stack which looks like ((A, (N, A)), A) @@ -379,7 +379,7 @@ def test_line_extent_compound_coords1(self): # a simple line in data coordinates in the y component, and in axes # coordinates in the x ax = plt.axes() - trans = mtrans.blended_transform_factory(ax.transAxes, ax.transData) + trans = mtransforms.blended_transform_factory(ax.transAxes, ax.transData) ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) assert_array_equal(ax.dataLim.get_points(), np.array([[np.inf, -5.], @@ -389,7 +389,7 @@ def test_line_extent_compound_coords1(self): def test_line_extent_predata_transform_coords(self): # a simple line in (offset + data) coordinates ax = plt.axes() - trans = mtrans.Affine2D().scale(10) + ax.transData + trans = mtransforms.Affine2D().scale(10) + ax.transData ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) assert_array_equal(ax.dataLim.get_points(), np.array([[1., -50.], [12., 350.]])) @@ -399,8 +399,8 @@ def test_line_extent_compound_coords2(self): # a simple line in (offset + data) coordinates in the y component, and # in axes coordinates in the x ax = plt.axes() - trans = mtrans.blended_transform_factory( - ax.transAxes, mtrans.Affine2D().scale(10) + ax.transData) + trans = mtransforms.blended_transform_factory( + ax.transAxes, mtransforms.Affine2D().scale(10) + ax.transData) ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) assert_array_equal(ax.dataLim.get_points(), np.array([[np.inf, -50.], [-np.inf, 350.]])) @@ -408,23 +408,23 @@ def test_line_extent_compound_coords2(self): def test_line_extents_affine(self): ax = plt.axes() - offset = mtrans.Affine2D().translate(10, 10) + offset = mtransforms.Affine2D().translate(10, 10) plt.plot(np.arange(10), transform=offset + ax.transData) expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 10 assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) def test_line_extents_non_affine(self): ax = plt.axes() - offset = mtrans.Affine2D().translate(10, 10) - na_offset = NonAffineForTest(mtrans.Affine2D().translate(10, 10)) + offset = mtransforms.Affine2D().translate(10, 10) + na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10)) plt.plot(np.arange(10), transform=offset + na_offset + ax.transData) expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 20 assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) def test_pathc_extents_non_affine(self): ax = plt.axes() - offset = mtrans.Affine2D().translate(10, 10) - na_offset = NonAffineForTest(mtrans.Affine2D().translate(10, 10)) + offset = mtransforms.Affine2D().translate(10, 10) + na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10)) pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]])) patch = mpatches.PathPatch(pth, transform=offset + na_offset + ax.transData) @@ -434,7 +434,7 @@ def test_pathc_extents_non_affine(self): def test_pathc_extents_affine(self): ax = plt.axes() - offset = mtrans.Affine2D().translate(10, 10) + offset = mtransforms.Affine2D().translate(10, 10) pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]])) patch = mpatches.PathPatch(pth, transform=offset + ax.transData) ax.add_patch(patch) @@ -444,7 +444,7 @@ def test_pathc_extents_affine(self): def test_line_extents_for_non_affine_transData(self): ax = plt.axes(projection='polar') # add 10 to the radius of the data - offset = mtrans.Affine2D().translate(0, 10) + offset = mtransforms.Affine2D().translate(0, 10) plt.plot(np.arange(10), transform=offset + ax.transData) # the data lim of a polar plot is stored in coordinates @@ -459,8 +459,8 @@ def assert_bbox_eq(bbox1, bbox2): def test_bbox_intersection(): - bbox_from_ext = mtrans.Bbox.from_extents - inter = mtrans.Bbox.intersection + bbox_from_ext = mtransforms.Bbox.from_extents + inter = mtransforms.Bbox.intersection r1 = bbox_from_ext(0, 0, 1, 1) r2 = bbox_from_ext(0.5, 0.5, 1.5, 1.5) @@ -481,8 +481,8 @@ def test_bbox_intersection(): def test_bbox_as_strings(): - b = mtrans.Bbox([[.5, 0], [.75, .75]]) - assert_bbox_eq(b, eval(repr(b), {'Bbox': mtrans.Bbox})) + b = mtransforms.Bbox([[.5, 0], [.75, .75]]) + assert_bbox_eq(b, eval(repr(b), {'Bbox': mtransforms.Bbox})) asdict = eval(str(b), {'Bbox': dict}) for k, v in asdict.items(): assert getattr(b, k) == v @@ -493,7 +493,7 @@ def test_bbox_as_strings(): def test_transform_single_point(): - t = mtrans.Affine2D() + t = mtransforms.Affine2D() r = t.transform_affine((1, 1)) assert r.shape == (2,) @@ -507,13 +507,13 @@ def test_log_transform(): def test_nan_overlap(): - a = mtrans.Bbox([[0, 0], [1, 1]]) - b = mtrans.Bbox([[0, 0], [1, np.nan]]) + a = mtransforms.Bbox([[0, 0], [1, 1]]) + b = mtransforms.Bbox([[0, 0], [1, np.nan]]) assert not a.overlaps(b) def test_transform_angles(): - t = mtrans.Affine2D() # Identity transform + t = mtransforms.Affine2D() # Identity transform angles = np.array([20, 45, 60]) points = np.array([[0, 0], [1, 1], [2, 2]]) @@ -535,12 +535,12 @@ def test_nonsingular(): zero_expansion = np.array([-0.001, 0.001]) cases = [(0, np.nan), (0, 0), (0, 7.9e-317)] for args in cases: - out = np.array(mtrans.nonsingular(*args)) + out = np.array(mtransforms.nonsingular(*args)) assert_array_equal(out, zero_expansion) def test_invalid_arguments(): - t = mtrans.Affine2D() + t = mtransforms.Affine2D() # There are two different exceptions, since the wrong number of # dimensions is caught when constructing an array_view, and that # raises a ValueError, and a wrong shape with a possible number @@ -565,8 +565,8 @@ def test_transformed_path(): codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] path = Path(points, codes) - trans = mtrans.Affine2D() - trans_path = mtrans.TransformedPath(path, trans) + trans = mtransforms.Affine2D() + trans_path = mtransforms.TransformedPath(path, trans) assert_allclose(trans_path.get_fully_transformed_path().vertices, points) # Changing the transform should change the result. @@ -584,10 +584,10 @@ def test_transformed_path(): def test_transformed_patch_path(): - trans = mtrans.Affine2D() + trans = mtransforms.Affine2D() patch = mpatches.Wedge((0, 0), 1, 45, 135, transform=trans) - tpatch = mtrans.TransformedPatchPath(patch) + tpatch = mtransforms.TransformedPatchPath(patch) points = tpatch.get_fully_transformed_path().vertices # Changing the transform should change the result. From 34f688b1faaab3b93bcada366caeec6e0e0c5495 Mon Sep 17 00:00:00 2001 From: sindunuragarp Date: Mon, 20 Mar 2017 21:42:54 +0100 Subject: [PATCH 08/18] Reconfigured line to comply with pep8 length --- lib/matplotlib/tests/test_artist.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index dcf4b7bb10aa..71b87e5af21a 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -88,8 +88,9 @@ def test_collection_transform_of_none(): # providing an IdentityTransform puts the ellipse in device coordinates e = mpatches.Ellipse(xy_pix, width=100, height=100) - c = mcollections.PatchCollection([e], transform=mtransforms.IdentityTransform(), - alpha=0.5) + c = mcollections.PatchCollection([e], + transform=mtransforms.IdentityTransform(), + alpha=0.5) ax.add_collection(c) assert isinstance(c._transOffset, mtransforms.IdentityTransform) From 03bacb800340816e15c9c13ae341aa206078674c Mon Sep 17 00:00:00 2001 From: sindunuragarp Date: Tue, 21 Mar 2017 11:30:26 +0100 Subject: [PATCH 09/18] Removed additional pep8 e501 error caused by mtransforms --- lib/matplotlib/colorbar.py | 11 ++++++----- lib/matplotlib/tests/test_transforms.py | 12 +++++++----- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index d0eae3ac3d27..be9311926f17 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -687,9 +687,10 @@ def _process_values(self, b=None): self.norm.vmin = 0 self.norm.vmax = 1 - self.norm.vmin, self.norm.vmax = mtransforms.nonsingular(self.norm.vmin, - self.norm.vmax, - expander=0.1) + self.norm.vmin, self.norm.vmax = mtransforms.nonsingular( + self.norm.vmin, + self.norm.vmax, + expander=0.1) b = self.norm.inverse(self._uniform_y(self.cmap.N + 1)) @@ -1126,8 +1127,8 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, 'parents share the same figure.') # take a bounding box around all of the given axes - parents_bbox = mtransforms.Bbox.union([ax.get_position(original=True).frozen() - for ax in parents]) + parents_bbox = mtransforms.Bbox.union( + [ax.get_position(original=True).frozen() for ax in parents]) pb = parents_bbox if location in ('left', 'right'): diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index 0d47f58dc46d..68c65154aee5 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -62,7 +62,8 @@ def __init__(self, scale_factor): self._scale_factor = scale_factor def _as_mpl_transform(self, axes): - return mtransforms.Affine2D().scale(self._scale_factor) + axes.transData + return (mtransforms.Affine2D().scale(self._scale_factor) + + axes.transData) ax = plt.axes() line, = plt.plot(np.arange(10), transform=ScaledBy(10)) @@ -191,7 +192,7 @@ def test_clipping_of_log(): # something like this happens in plotting logarithmic histograms trans = mtransforms.BlendedGenericTransform(mtransforms.Affine2D(), - LogScale.Log10Transform('clip')) + LogScale.Log10Transform('clip')) tpath = trans.transform_path_non_affine(path) result = tpath.iter_segments(trans.get_affine(), clip=(0, 0, 100, 100), @@ -379,7 +380,8 @@ def test_line_extent_compound_coords1(self): # a simple line in data coordinates in the y component, and in axes # coordinates in the x ax = plt.axes() - trans = mtransforms.blended_transform_factory(ax.transAxes, ax.transData) + trans = mtransforms.blended_transform_factory(ax.transAxes, + ax.transData) ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) assert_array_equal(ax.dataLim.get_points(), np.array([[np.inf, -5.], @@ -399,8 +401,8 @@ def test_line_extent_compound_coords2(self): # a simple line in (offset + data) coordinates in the y component, and # in axes coordinates in the x ax = plt.axes() - trans = mtransforms.blended_transform_factory( - ax.transAxes, mtransforms.Affine2D().scale(10) + ax.transData) + trans = mtransforms.blended_transform_factory(ax.transAxes, + mtransforms.Affine2D().scale(10) + ax.transData) ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) assert_array_equal(ax.dataLim.get_points(), np.array([[np.inf, -50.], [-np.inf, 350.]])) From 465a4539ef3a598da2f1a250fdae25ea011f27ea Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Fri, 10 Mar 2017 18:11:24 -0500 Subject: [PATCH 10/18] STY: pep8 cleanup --- lib/matplotlib/backends/backend_ps.py | 54 +++++++++++++++++---------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index a14b346afeb1..30f62a195d2e 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1068,39 +1068,46 @@ def write(self, *kl, **kwargs): else: creator_str = "matplotlib version " + __version__ + \ ", http://matplotlib.org/" + def print_figure_impl(): # write the PostScript headers - if isEPSF: print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) - else: print("%!PS-Adobe-3.0", file=fh) - if title: print("%%Title: "+title, file=fh) + if isEPSF: + print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) + else: + print("%!PS-Adobe-3.0", file=fh) + if title: + print("%%Title: "+title, file=fh) print("%%Creator: " + creator_str, file=fh) # get source date from SOURCE_DATE_EPOCH, if set # See https://reproducible-builds.org/specs/source-date-epoch/ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") if source_date_epoch: source_date = datetime.datetime.utcfromtimestamp( - int(source_date_epoch) ).strftime("%a %b %d %H:%M:%S %Y") + int(source_date_epoch)).strftime("%a %b %d %H:%M:%S %Y") else: source_date = time.ctime() print("%%CreationDate: "+source_date, file=fh) print("%%Orientation: " + orientation, file=fh) - if not isEPSF: print("%%DocumentPaperSizes: "+papertype, file=fh) + if not isEPSF: + print("%%DocumentPaperSizes: "+papertype, file=fh) print("%%%%BoundingBox: %d %d %d %d" % bbox, file=fh) - if not isEPSF: print("%%Pages: 1", file=fh) + if not isEPSF: + print("%%Pages: 1", file=fh) print("%%EndComments", file=fh) Ndict = len(psDefs) print("%%BeginProlog", file=fh) if not rcParams['ps.useafm']: Ndict += len(ps_renderer.used_characters) - print("/mpldict %d dict def"%Ndict, file=fh) + print("/mpldict %d dict def" % Ndict, file=fh) print("mpldict begin", file=fh) for d in psDefs: - d=d.strip() + d = d.strip() for l in d.split('\n'): print(l.strip(), file=fh) if not rcParams['ps.useafm']: - for font_filename, chars in six.itervalues(ps_renderer.used_characters): + for font_filename, chars in six.itervalues( + ps_renderer.used_characters): if len(chars): font = get_font(font_filename) glyph_ids = [] @@ -1120,21 +1127,29 @@ def print_figure_impl(): # STIX fonts). This will simply turn that off to avoid # errors. if is_opentype_cff_font(font_filename): - raise RuntimeError("OpenType CFF fonts can not be saved using the internal Postscript backend at this time.\nConsider using the Cairo backend.") + msg = ("OpenType CFF fonts can not be saved " + "using the internal Postscript backend " + "at this time.\nConsider using the " + "Cairo backend.") + raise RuntimeError(msg) else: fh.flush() convert_ttf_to_ps( - font_filename.encode(sys.getfilesystemencoding()), + font_filename.encode( + sys.getfilesystemencoding()), fh, fonttype, glyph_ids) print("end", file=fh) print("%%EndProlog", file=fh) - if not isEPSF: print("%%Page: 1 1", file=fh) + if not isEPSF: + print("%%Page: 1 1", file=fh) print("mpldict begin", file=fh) - #print >>fh, "gsave" - print("%s translate"%_nums_to_str(xo, yo), file=fh) - if rotation: print("%d rotate"%rotation, file=fh) - print("%s clipbox"%_nums_to_str(width*72, height*72, 0, 0), file=fh) + + print("%s translate" % _nums_to_str(xo, yo), file=fh) + if rotation: + print("%d rotate" % rotation, file=fh) + print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0), + file=fh) # write the figure content = self._pswriter.getvalue() @@ -1143,10 +1158,10 @@ def print_figure_impl(): print(content, file=fh) # write the trailer - #print >>fh, "grestore" print("end", file=fh) print("showpage", file=fh) - if not isEPSF: print("%%EOF", file=fh) + if not isEPSF: + print("%%EOF", file=fh) fh.flush() if rcParams['ps.usedistiller']: @@ -1161,8 +1176,9 @@ def print_figure_impl(): requires_unicode = file_requires_unicode(outfile) if (not requires_unicode and - (six.PY3 or not isinstance(outfile, StringIO))): + (six.PY3 or not isinstance(outfile, StringIO))): fh = io.TextIOWrapper(outfile, encoding="latin-1") + # Prevent the io.TextIOWrapper from closing the # underlying file def do_nothing(): From 6e451f1f22c7bf81662ba445dad31342279b900e Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Fri, 10 Mar 2017 18:17:41 -0500 Subject: [PATCH 11/18] MNT: explicitly pass in file handle to print_figure_impl Rather than closing over it and relying on it being defined in the top-level function namespace. --- lib/matplotlib/backends/backend_ps.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index 30f62a195d2e..56582ac438f0 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1069,7 +1069,7 @@ def write(self, *kl, **kwargs): creator_str = "matplotlib version " + __version__ + \ ", http://matplotlib.org/" - def print_figure_impl(): + def print_figure_impl(fh): # write the PostScript headers if isEPSF: print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) @@ -1169,7 +1169,7 @@ def print_figure_impl(): # Write to a temporary file. fd, tmpfile = mkstemp() with io.open(fd, 'w', encoding='latin-1') as fh: - print_figure_impl() + print_figure_impl(fh) else: # Write directly to outfile. if passed_in_file_object: @@ -1187,10 +1187,10 @@ def do_nothing(): else: fh = outfile - print_figure_impl() + print_figure_impl(fh) else: with io.open(outfile, 'w', encoding='latin-1') as fh: - print_figure_impl() + print_figure_impl(fh) if rcParams['ps.usedistiller']: if rcParams['ps.usedistiller'] == 'ghostscript': From 710b509d5d99b93110054346f1c2efc47b5b2f35 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Fri, 10 Mar 2017 18:29:53 -0500 Subject: [PATCH 12/18] FIX: always remove the temporary file in eps print_figure In cases were a filename is passed in we clean up the temporary file by renaming it to the output file, however if a file handle is passed in we copy the contents into that the file and do not clean up the temporary file. Use a try...finally block to always remove the temporary file, even if things go wrong. --- lib/matplotlib/backends/backend_ps.py | 47 ++++++++++++++------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index 56582ac438f0..5de1c7d39bdd 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1168,8 +1168,31 @@ def print_figure_impl(fh): # We are going to use an external program to process the output. # Write to a temporary file. fd, tmpfile = mkstemp() - with io.open(fd, 'w', encoding='latin-1') as fh: - print_figure_impl(fh) + try: + with io.open(fd, 'w', encoding='latin-1') as fh: + print_figure_impl(fh) + if rcParams['ps.usedistiller'] == 'ghostscript': + gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) + elif rcParams['ps.usedistiller'] == 'xpdf': + xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) + + if passed_in_file_object: + if file_requires_unicode(outfile): + with io.open(tmpfile, 'rb') as fh: + outfile.write(fh.read().decode('latin-1')) + else: + with io.open(tmpfile, 'rb') as fh: + outfile.write(fh.read()) + else: + with io.open(outfile, 'w') as fh: + pass + mode = os.stat(outfile).st_mode + shutil.move(tmpfile, outfile) + os.chmod(outfile, mode) + finally: + if os.path.isfile(tmpfile): + os.unlink(tmpfile) + else: # Write directly to outfile. if passed_in_file_object: @@ -1192,26 +1215,6 @@ def do_nothing(): with io.open(outfile, 'w', encoding='latin-1') as fh: print_figure_impl(fh) - if rcParams['ps.usedistiller']: - if rcParams['ps.usedistiller'] == 'ghostscript': - gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) - elif rcParams['ps.usedistiller'] == 'xpdf': - xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) - - if passed_in_file_object: - if file_requires_unicode(outfile): - with io.open(tmpfile, 'rb') as fh: - outfile.write(fh.read().decode('latin-1')) - else: - with io.open(tmpfile, 'rb') as fh: - outfile.write(fh.read()) - else: - with io.open(outfile, 'w') as fh: - pass - mode = os.stat(outfile).st_mode - shutil.move(tmpfile, outfile) - os.chmod(outfile, mode) - def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor, orientation, isLandscape, papertype, metadata=None, **kwargs): From 9f53b14d440a2c546d4d977abe0f61ee547a736d Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Fri, 10 Mar 2017 18:35:32 -0500 Subject: [PATCH 13/18] STY: pep8 clean up --- lib/matplotlib/backends/backend_ps.py | 53 +++++++++++++++------------ 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index 5de1c7d39bdd..1aefe3a145dd 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1234,7 +1234,7 @@ def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor, else: raise ValueError("outfile must be a path or a file-like object") - self.figure.dpi = 72 # ignore the dpi kwarg + self.figure.dpi = 72 # ignore the dpi kwarg width, height = self.figure.get_size_inches() xo = 0 yo = 0 @@ -1262,18 +1262,17 @@ def write(self, *kl, **kwargs): else: self._pswriter = io.StringIO() - # mixed mode rendering _bbox_inches_restore = kwargs.pop("bbox_inches_restore", None) ps_renderer = self._renderer_class(width, height, self._pswriter, imagedpi=dpi) renderer = MixedModeRenderer(self.figure, - width, height, dpi, ps_renderer, - bbox_inches_restore=_bbox_inches_restore) + width, height, dpi, ps_renderer, + bbox_inches_restore=_bbox_inches_restore) self.figure.draw(renderer) - if dryrun: # return immediately if dryrun (tightbbox=True) + if dryrun: # return immediately if dryrun (tightbbox=True) return self.figure.set_facecolor(origfacecolor) @@ -1287,18 +1286,22 @@ def write(self, *kl, **kwargs): ", http://matplotlib.org/" # write to a temp file, we'll move it to outfile when done + fd, tmpfile = mkstemp() + with io.open(fd, 'w', encoding='latin-1') as fh: # write the Encapsulated PostScript headers print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) - if title: print("%%Title: "+title, file=fh) + if title: + print("%%Title: "+title, file=fh) print("%%Creator: " + creator_str, file=fh) # get source date from SOURCE_DATE_EPOCH, if set # See https://reproducible-builds.org/specs/source-date-epoch/ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") if source_date_epoch: source_date = datetime.datetime.utcfromtimestamp( - int(source_date_epoch) ).strftime("%a %b %d %H:%M:%S %Y") + int(source_date_epoch)).strftime( + "%a %b %d %H:%M:%S %Y") else: source_date = time.ctime() print("%%CreationDate: "+source_date, file=fh) @@ -1307,30 +1310,29 @@ def write(self, *kl, **kwargs): Ndict = len(psDefs) print("%%BeginProlog", file=fh) - print("/mpldict %d dict def"%Ndict, file=fh) + print("/mpldict %d dict def" % Ndict, file=fh) print("mpldict begin", file=fh) for d in psDefs: - d=d.strip() + d = d.strip() for l in d.split('\n'): print(l.strip(), file=fh) print("end", file=fh) print("%%EndProlog", file=fh) print("mpldict begin", file=fh) - #print >>fh, "gsave" - print("%s translate"%_nums_to_str(xo, yo), file=fh) - print("%s clipbox"%_nums_to_str(width*72, height*72, 0, 0), file=fh) + print("%s translate" % _nums_to_str(xo, yo), file=fh) + print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0), + file=fh) # write the figure print(self._pswriter.getvalue(), file=fh) # write the trailer - #print >>fh, "grestore" print("end", file=fh) print("showpage", file=fh) fh.flush() - if isLandscape: # now we are ready to rotate + if isLandscape: # now we are ready to rotate isLandscape = True width, height = height, width bbox = (lly, llx, ury, urx) @@ -1344,16 +1346,17 @@ def write(self, *kl, **kwargs): paperWidth, paperHeight = paperHeight, paperWidth else: temp_papertype = _get_papertype(width, height) - if papertype=='auto': + if papertype == 'auto': papertype = temp_papertype paperWidth, paperHeight = papersize[temp_papertype] else: paperWidth, paperHeight = papersize[papertype] - if (width>paperWidth or height>paperHeight) and isEPSF: + if (width > paperWidth or height > paperHeight) and isEPSF: paperWidth, paperHeight = papersize[temp_papertype] - verbose.report('Your figure is too big to fit on %s paper. %s \ - paper will be used to prevent clipping.'%(papertype, temp_papertype), 'helpful') - + verbose.report( + ('Your figure is too big to fit on %s paper. %s ' + 'paper will be used to prevent clipping.' + ) % (papertype, temp_papertype), 'helpful') texmanager = ps_renderer.get_texmanager() font_preamble = texmanager.get_font_preamble() @@ -1361,7 +1364,8 @@ def write(self, *kl, **kwargs): psfrag_rotated = convert_psfrags(tmpfile, ps_renderer.psfrag, font_preamble, - custom_preamble, paperWidth, paperHeight, + custom_preamble, paperWidth, + paperHeight, orientation) if rcParams['ps.usedistiller'] == 'ghostscript': @@ -1371,9 +1375,11 @@ def write(self, *kl, **kwargs): xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, rotated=psfrag_rotated) elif rcParams['text.usetex']: - if False: pass # for debugging - else: gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, - rotated=psfrag_rotated) + if False: + pass # for debugging + else: + gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, + rotated=psfrag_rotated) if is_writable_file_like(outfile): if file_requires_unicode(outfile): @@ -1389,6 +1395,7 @@ def write(self, *kl, **kwargs): shutil.move(tmpfile, outfile) os.chmod(outfile, mode) + def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble, paperWidth, paperHeight, orientation): """ From b9ff429d88506be90b218e6389df5e003c8bdf4e Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Fri, 10 Mar 2017 18:37:26 -0500 Subject: [PATCH 14/18] FIX: always remove the temporary file in eps print_figure_tex In cases were a filename is passed in we clean up the temporary file by renaming it to the output file, however if a file handle is passed in we copy the contents into that the file and do not clean up the temporary file. Use a try...finally block to always remove the temporary file, even if things go wrong. --- lib/matplotlib/backends/backend_ps.py | 203 +++++++++++++------------- 1 file changed, 103 insertions(+), 100 deletions(-) diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index 1aefe3a145dd..167eff74167d 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1288,112 +1288,115 @@ def write(self, *kl, **kwargs): # write to a temp file, we'll move it to outfile when done fd, tmpfile = mkstemp() - - with io.open(fd, 'w', encoding='latin-1') as fh: - # write the Encapsulated PostScript headers - print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) - if title: - print("%%Title: "+title, file=fh) - print("%%Creator: " + creator_str, file=fh) - # get source date from SOURCE_DATE_EPOCH, if set - # See https://reproducible-builds.org/specs/source-date-epoch/ - source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") - if source_date_epoch: - source_date = datetime.datetime.utcfromtimestamp( - int(source_date_epoch)).strftime( - "%a %b %d %H:%M:%S %Y") - else: - source_date = time.ctime() - print("%%CreationDate: "+source_date, file=fh) - print("%%%%BoundingBox: %d %d %d %d" % bbox, file=fh) - print("%%EndComments", file=fh) - - Ndict = len(psDefs) - print("%%BeginProlog", file=fh) - print("/mpldict %d dict def" % Ndict, file=fh) - print("mpldict begin", file=fh) - for d in psDefs: - d = d.strip() - for l in d.split('\n'): - print(l.strip(), file=fh) - print("end", file=fh) - print("%%EndProlog", file=fh) - - print("mpldict begin", file=fh) - print("%s translate" % _nums_to_str(xo, yo), file=fh) - print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0), - file=fh) - - # write the figure - print(self._pswriter.getvalue(), file=fh) - - # write the trailer - print("end", file=fh) - print("showpage", file=fh) - fh.flush() - - if isLandscape: # now we are ready to rotate - isLandscape = True - width, height = height, width - bbox = (lly, llx, ury, urx) - - # set the paper size to the figure size if isEPSF. The - # resulting ps file has the given size with correct bounding - # box so that there is no need to call 'pstoeps' - if isEPSF: - paperWidth, paperHeight = self.figure.get_size_inches() - if isLandscape: - paperWidth, paperHeight = paperHeight, paperWidth - else: - temp_papertype = _get_papertype(width, height) - if papertype == 'auto': - papertype = temp_papertype - paperWidth, paperHeight = papersize[temp_papertype] + try: + with io.open(fd, 'w', encoding='latin-1') as fh: + # write the Encapsulated PostScript headers + print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) + if title: + print("%%Title: "+title, file=fh) + print("%%Creator: " + creator_str, file=fh) + # get source date from SOURCE_DATE_EPOCH, if set + # See https://reproducible-builds.org/specs/source-date-epoch/ + source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") + if source_date_epoch: + source_date = datetime.datetime.utcfromtimestamp( + int(source_date_epoch)).strftime( + "%a %b %d %H:%M:%S %Y") + else: + source_date = time.ctime() + print("%%CreationDate: "+source_date, file=fh) + print("%%%%BoundingBox: %d %d %d %d" % bbox, file=fh) + print("%%EndComments", file=fh) + + Ndict = len(psDefs) + print("%%BeginProlog", file=fh) + print("/mpldict %d dict def" % Ndict, file=fh) + print("mpldict begin", file=fh) + for d in psDefs: + d = d.strip() + for l in d.split('\n'): + print(l.strip(), file=fh) + print("end", file=fh) + print("%%EndProlog", file=fh) + + print("mpldict begin", file=fh) + print("%s translate" % _nums_to_str(xo, yo), file=fh) + print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0), + file=fh) + + # write the figure + print(self._pswriter.getvalue(), file=fh) + + # write the trailer + print("end", file=fh) + print("showpage", file=fh) + fh.flush() + + if isLandscape: # now we are ready to rotate + isLandscape = True + width, height = height, width + bbox = (lly, llx, ury, urx) + + # set the paper size to the figure size if isEPSF. The + # resulting ps file has the given size with correct bounding + # box so that there is no need to call 'pstoeps' + if isEPSF: + paperWidth, paperHeight = self.figure.get_size_inches() + if isLandscape: + paperWidth, paperHeight = paperHeight, paperWidth else: - paperWidth, paperHeight = papersize[papertype] - if (width > paperWidth or height > paperHeight) and isEPSF: + temp_papertype = _get_papertype(width, height) + if papertype == 'auto': + papertype = temp_papertype paperWidth, paperHeight = papersize[temp_papertype] - verbose.report( - ('Your figure is too big to fit on %s paper. %s ' - 'paper will be used to prevent clipping.' - ) % (papertype, temp_papertype), 'helpful') - - texmanager = ps_renderer.get_texmanager() - font_preamble = texmanager.get_font_preamble() - custom_preamble = texmanager.get_custom_preamble() - - psfrag_rotated = convert_psfrags(tmpfile, ps_renderer.psfrag, - font_preamble, - custom_preamble, paperWidth, - paperHeight, - orientation) - - if rcParams['ps.usedistiller'] == 'ghostscript': - gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, - rotated=psfrag_rotated) - elif rcParams['ps.usedistiller'] == 'xpdf': - xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, - rotated=psfrag_rotated) - elif rcParams['text.usetex']: - if False: - pass # for debugging - else: + else: + paperWidth, paperHeight = papersize[papertype] + if (width > paperWidth or height > paperHeight) and isEPSF: + paperWidth, paperHeight = papersize[temp_papertype] + verbose.report( + ('Your figure is too big to fit on %s paper. %s ' + 'paper will be used to prevent clipping.' + ) % (papertype, temp_papertype), 'helpful') + + texmanager = ps_renderer.get_texmanager() + font_preamble = texmanager.get_font_preamble() + custom_preamble = texmanager.get_custom_preamble() + + psfrag_rotated = convert_psfrags(tmpfile, ps_renderer.psfrag, + font_preamble, + custom_preamble, paperWidth, + paperHeight, + orientation) + + if rcParams['ps.usedistiller'] == 'ghostscript': gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, rotated=psfrag_rotated) + elif rcParams['ps.usedistiller'] == 'xpdf': + xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, + rotated=psfrag_rotated) + elif rcParams['text.usetex']: + if False: + pass # for debugging + else: + gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, + rotated=psfrag_rotated) - if is_writable_file_like(outfile): - if file_requires_unicode(outfile): - with io.open(tmpfile, 'rb') as fh: - outfile.write(fh.read().decode('latin-1')) + if is_writable_file_like(outfile): + if file_requires_unicode(outfile): + with io.open(tmpfile, 'rb') as fh: + outfile.write(fh.read().decode('latin-1')) + else: + with io.open(tmpfile, 'rb') as fh: + outfile.write(fh.read()) else: - with io.open(tmpfile, 'rb') as fh: - outfile.write(fh.read()) - else: - with io.open(outfile, 'wb') as fh: - pass - mode = os.stat(outfile).st_mode - shutil.move(tmpfile, outfile) - os.chmod(outfile, mode) + with io.open(outfile, 'wb') as fh: + pass + mode = os.stat(outfile).st_mode + shutil.move(tmpfile, outfile) + os.chmod(outfile, mode) + finally: + if os.path.isfile(tmpfile): + os.unlink(tmpfile) def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble, From c3d012a2b3ccbd86228c5a5a21ff044d9fdc1678 Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Wed, 22 Mar 2017 09:29:17 +0530 Subject: [PATCH 15/18] Revert "numpydocstring added" This reverts commit ea9250d92045b56c899bbdb7eee7d7ff07ae1029. --- lib/matplotlib/axes/_axes.py | 162 +++++++++++++++++------------------ 1 file changed, 80 insertions(+), 82 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 08bb3b7fb5b1..76dc174e2f53 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -56,7 +56,7 @@ 'markeredgecolor': ['mec'], 'markeredgewidth': ['mew'], 'markersize': ['ms'], - } + } def _plot_args_replacer(args, data): @@ -1063,7 +1063,7 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', verts = [((thisx, thisymin), (thisx, thisymax)) for thisx, thisymin, thisymax in zip(x, ymin, ymax)] - # print 'creating line collection' + #print 'creating line collection' lines = mcoll.LineCollection(verts, colors=colors, linestyles=linestyles, label=label) self.add_collection(lines, autolim=False) @@ -1082,9 +1082,9 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', return lines @_preprocess_data(replace_names=["positions", "lineoffsets", - "linelengths", "linewidths", - "colors", "linestyles"], - label_namer=None) + "linelengths", "linewidths", + "colors", "linestyles"], + label_namer=None) @docstring.dedent_interpd def eventplot(self, positions, orientation='horizontal', lineoffsets=1, linelengths=1, linewidths=None, colors=None, @@ -1226,7 +1226,7 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1, colls = [] for position, lineoffset, linelength, linewidth, color, linestyle in \ zip(positions, lineoffsets, linelengths, linewidths, - colors, linestyles): + colors, linestyles): coll = mcoll.EventCollection(position, orientation=orientation, lineoffset=lineoffset, @@ -1263,8 +1263,8 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1, # ### Basic plotting # The label_naming happens in `matplotlib.axes._base._plot_args` @_preprocess_data(replace_names=["x", "y"], - positional_parameter_names=_plot_args_replacer, - label_namer=None) + positional_parameter_names=_plot_args_replacer, + label_namer=None) @docstring.dedent_interpd def plot(self, *args, **kwargs): """ @@ -1857,10 +1857,10 @@ def step(self, x, y, *args, **kwargs): return self.plot(x, y, *args, **kwargs) @_preprocess_data(replace_names=["left", "height", "width", "bottom", - "color", "edgecolor", "linewidth", - "tick_label", "xerr", "yerr", - "ecolor"], - label_namer=None) + "color", "edgecolor", "linewidth", + "tick_label", "xerr", "yerr", + "ecolor"], + label_namer=None) @docstring.dedent_interpd def bar(self, left, height, width=0.8, bottom=None, **kwargs): """ @@ -2469,13 +2469,14 @@ def stem(self, *args, **kwargs): return stem_container @_preprocess_data(replace_names=['x', 'explode', 'labels', 'colors'], - label_namer=None) + label_namer=None) def pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False): - r"""Plot a pie chart. + r""" + Plot a pie chart. Make a pie chart of array *x*. The fractional area of each wedge is given by x/sum(x). If sum(x) <= 1, then the values @@ -2483,94 +2484,90 @@ def pie(self, x, explode=None, labels=None, colors=None, be normalized. The wedges are plotted counterclockwise, by default starting from the x-axis. - Parameters - ---------- - x : array - The input array used to make the pie chart. + Keyword arguments: - explode: None or array + *explode*: [ *None* | len(x) sequence ] If not *None*, is a ``len(x)`` array which specifies the fraction of the radius with which to offset each wedge. - colors: None or array + *colors*: [ *None* | color sequence ] A sequence of matplotlib color args through which the pie chart will cycle. If `None`, will use the colors in the currently active cycle. - labels: None or list + *labels*: [ *None* | len(x) sequence of strings ] A sequence of strings providing the labels for each wedge - autopct: None or string or function + *autopct*: [ *None* | format string | format function ] If not *None*, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be ``fmt%pct``. If it is a function, it will be called. - pctdistance: float + *pctdistance*: scalar The ratio between the center of each pie slice and the start of the text generated by *autopct*. Ignored if *autopct* is *None*; default is 0.6. - labeldistance: float + *labeldistance*: scalar The radial distance at which the pie labels are drawn - shadow: bool + *shadow*: [ *False* | *True* ] Draw a shadow beneath the pie. - startangle: None or Offset angle + *startangle*: [ *None* | Offset angle ] If not *None*, rotates the start of the pie chart by *angle* degrees counterclockwise from the x-axis. - radius: None or float + *radius*: [ *None* | scalar ] The radius of the pie, if *radius* is *None* it will be set to 1. - counterclock: bool + *counterclock*: [ *False* | *True* ] Specify fractions direction, clockwise or counterclockwise. - wedgeprops: None or dict + *wedgeprops*: [ *None* | dict of key value pairs ] Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = { 'linewidth' : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default `clip_on=False`. - textprops: None or dict + *textprops*: [ *None* | dict of key value pairs ] Dict of arguments to pass to the text objects. - center: list of int - Center position of the chart. Takes value (0,0) or is a sequence - of 2 scalars. + *center*: [ (0,0) | sequence of 2 scalars ] + Center position of the chart. - frame: bool - Plot axes frame with the chart if true. + *frame*: [ *False* | *True* ] + Plot axes frame with the chart. - rotatelabels: bool - Rotate each label to the angle of the corresponding slice if true. + *rotatelabels*: [ *False* | *True* ] + Rotate each label to the angle of the corresponding slice. - Returns - ------- - patches: list - A sequence of :class:`matplotlib.patches.Wedge` instances + The pie chart will probably look best if the figure and axes are + square, or the Axes aspect is equal. e.g.:: - texts: list - A is a list of the label :class:`matplotlib.text.Text` instances. + figure(figsize=(8,8)) + ax = axes([0.1, 0.1, 0.8, 0.8]) - autotexts: list - A is a list of :class:`~matplotlib.text.Text` instances for the - numeric labels. Is returned only is if parameter *autopct* is - not *None*. If *autopct* is *None*, the tuple returned - is (patches, texts). + or:: - Examples - -------- - The pie chart will probably look best if the figure and axes are - square, or the Axes aspect is equal. + axes(aspect=1) + + Return value: + If *autopct* is *None*, return the tuple (*patches*, *texts*): - >>> figure(figsize=(8,8)) - >>> ax = axes([0.1, 0.1, 0.8, 0.8]) + - *patches* is a sequence of + :class:`matplotlib.patches.Wedge` instances - >>> axes(aspect=1) + - *texts* is a list of the label + :class:`matplotlib.text.Text` instances. + If *autopct* is not *None*, return the tuple (*patches*, + *texts*, *autotexts*), where *patches* and *texts* are as + above, and *autotexts* is a list of + :class:`~matplotlib.text.Text` instances for the numeric + labels. """ x = np.array(x, np.float32) @@ -2626,9 +2623,9 @@ def get_next_color(): y += expl * math.sin(thetam) w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2), - 360. * max(theta1, theta2), - facecolor=get_next_color(), - **wedgeprops) + 360. * max(theta1, theta2), + facecolor=get_next_color(), + **wedgeprops) slices.append(w) self.add_patch(w) w.set_label(label) @@ -2685,9 +2682,9 @@ def get_next_color(): self.set_frame_on(False) self.set_xlim((-1.25 + center[0], - 1.25 + center[0])) + 1.25 + center[0])) self.set_ylim((-1.25 + center[1], - 1.25 + center[1])) + 1.25 + center[1])) self.set_xticks([]) self.set_yticks([]) @@ -2697,7 +2694,7 @@ def get_next_color(): return slices, texts, autotexts @_preprocess_data(replace_names=["x", "y", "xerr", "yerr"], - label_namer="y") + label_namer="y") @docstring.dedent_interpd def errorbar(self, x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, @@ -3308,8 +3305,7 @@ def _update_dict(dictionary, rc_name, properties): dictionary = dict() for prop_dict in properties: dictionary.setdefault(prop_dict, - rcParams[rc_str.format(rc_name, - prop_dict)]) + rcParams[rc_str.format(rc_name, prop_dict)]) return dictionary # Common property dictionnaries loading from rc @@ -3319,7 +3315,7 @@ def _update_dict(dictionary, rc_name, properties): boxprops = _update_dict(boxprops, 'boxprops', default_props) whiskerprops = _update_dict(whiskerprops, 'whiskerprops', - default_props) + default_props) capprops = _update_dict(capprops, 'capprops', default_props) medianprops = _update_dict(medianprops, 'medianprops', default_props) meanprops = _update_dict(meanprops, 'meanprops', default_props) @@ -3811,9 +3807,9 @@ def dopatch(xs, ys, **kwargs): medians=medians, fliers=fliers, means=means) @_preprocess_data(replace_names=["x", "y", "s", "linewidths", - "edgecolors", "c", 'facecolor', - 'facecolors', 'color'], - label_namer="y") + "edgecolors", "c", 'facecolor', + 'facecolors', 'color'], + label_namer="y") def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, @@ -4617,7 +4613,7 @@ def stackplot(self, x, *args, **kwargs): stackplot.__doc__ = mstack.stackplot.__doc__ @_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"], - label_namer=None) + label_namer=None) def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, zorder=None, @@ -4717,7 +4713,7 @@ def fill(self, *args, **kwargs): return patches @_preprocess_data(replace_names=["x", "y1", "y2", "where"], - label_namer=None) + label_namer=None) @docstring.dedent_interpd def fill_between(self, x, y1, y2=0, where=None, interpolate=False, step=None, @@ -4886,7 +4882,7 @@ def get_interp_point(ind): return collection @_preprocess_data(replace_names=["y", "x1", "x2", "where"], - label_namer=None) + label_namer=None) @docstring.dedent_interpd def fill_betweenx(self, y, x1, x2=0, where=None, step=None, interpolate=False, **kwargs): @@ -5185,7 +5181,7 @@ def imshow(self, X, cmap=None, norm=None, aspect=None, if im.get_clip_path() is None: # image does not already have clipping set, clip to axes patch im.set_clip_path(self.patch) - # if norm is None and shape is None: + #if norm is None and shape is None: # im.set_clim(vmin, vmax) if vmin is not None or vmax is not None: im.set_clim(vmin, vmax) @@ -5245,7 +5241,7 @@ def _pcolorargs(funcname, *args, **kw): if X.shape != Y.shape: raise TypeError( 'Incompatible X, Y inputs to %s; see help(%s)' % ( - funcname, funcname)) + funcname, funcname)) if allmatch: if not (Nx == numCols and Ny == numRows): raise TypeError('Dimensions of C %s are incompatible with' @@ -5497,7 +5493,7 @@ def pcolor(self, *args, **kwargs): # Transform from native to data coordinates? t = collection._transform if (not isinstance(t, mtransforms.Transform) and - hasattr(t, '_as_mpl_transform')): + hasattr(t, '_as_mpl_transform')): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): @@ -5649,7 +5645,7 @@ def pcolormesh(self, *args, **kwargs): # Transform from native to data coordinates? t = collection._transform if (not isinstance(t, mtransforms.Transform) and - hasattr(t, '_as_mpl_transform')): + hasattr(t, '_as_mpl_transform')): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): @@ -7348,7 +7344,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None, nr, nc = Z.shape extent = [-0.5, nc - 0.5, nr - 0.5, -0.5] ret = self.imshow(mask, interpolation='nearest', aspect=aspect, - extent=extent, origin=origin, **kwargs) + extent=extent, origin=origin, **kwargs) else: if hasattr(Z, 'tocoo'): c = Z.tocoo() @@ -7368,8 +7364,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None, if markersize is None: markersize = 10 marks = mlines.Line2D(x, y, linestyle='None', - marker=marker, markersize=markersize, - **kwargs) + marker=marker, markersize=markersize, **kwargs) self.add_line(marks) nr, nc = Z.shape self.set_xlim(xmin=-0.5, xmax=nc - 0.5) @@ -7380,9 +7375,11 @@ def spy(self, Z, precision=0, marker=None, markersize=None, self.xaxis.tick_top() self.xaxis.set_ticks_position('both') self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], integer=True)) + steps=[1, 2, 5, 10], + integer=True)) self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], integer=True)) + steps=[1, 2, 5, 10], + integer=True)) return ret def matshow(self, Z, **kwargs): @@ -7427,10 +7424,11 @@ def matshow(self, Z, **kwargs): self.xaxis.tick_top() self.xaxis.set_ticks_position('both') self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], integer=True)) + steps=[1, 2, 5, 10], + integer=True)) self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, - steps=[1, 2, 5, 10], - integer=True)) + steps=[1, 2, 5, 10], + integer=True)) return im @_preprocess_data(replace_names=["dataset"], label_namer=None) From d12a3cda5e4dcf915f6f974c5c15a44724324ca7 Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Wed, 22 Mar 2017 11:09:56 +0530 Subject: [PATCH 16/18] Docstring to Numpydoc Converts the docstring of pie() function in _ axes.py into numpydoc --- lib/matplotlib/axes/_axes.py | 81 +++++++++++++++++++----------------- 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 76dc174e2f53..bd62835d9afa 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -2475,8 +2475,7 @@ def pie(self, x, explode=None, labels=None, colors=None, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False): - r""" - Plot a pie chart. + r"""Plot a pie chart. Make a pie chart of array *x*. The fractional area of each wedge is given by x/sum(x). If sum(x) <= 1, then the values @@ -2484,90 +2483,94 @@ def pie(self, x, explode=None, labels=None, colors=None, be normalized. The wedges are plotted counterclockwise, by default starting from the x-axis. - Keyword arguments: + Parameters + ---------- + x : array + The input array used to make the pie chart. - *explode*: [ *None* | len(x) sequence ] + explode: None or array If not *None*, is a ``len(x)`` array which specifies the fraction of the radius with which to offset each wedge. - *colors*: [ *None* | color sequence ] + colors: None or array A sequence of matplotlib color args through which the pie chart will cycle. If `None`, will use the colors in the currently active cycle. - *labels*: [ *None* | len(x) sequence of strings ] + labels: None or list A sequence of strings providing the labels for each wedge - *autopct*: [ *None* | format string | format function ] + autopct: None or string or function If not *None*, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be ``fmt%pct``. If it is a function, it will be called. - *pctdistance*: scalar + pctdistance: float The ratio between the center of each pie slice and the start of the text generated by *autopct*. Ignored if *autopct* is *None*; default is 0.6. - *labeldistance*: scalar + labeldistance: float The radial distance at which the pie labels are drawn - *shadow*: [ *False* | *True* ] + shadow: bool Draw a shadow beneath the pie. - *startangle*: [ *None* | Offset angle ] + startangle: None or Offset angle If not *None*, rotates the start of the pie chart by *angle* degrees counterclockwise from the x-axis. - *radius*: [ *None* | scalar ] + radius: None or float The radius of the pie, if *radius* is *None* it will be set to 1. - *counterclock*: [ *False* | *True* ] + counterclock: bool Specify fractions direction, clockwise or counterclockwise. - *wedgeprops*: [ *None* | dict of key value pairs ] + wedgeprops: None or dict Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = { 'linewidth' : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default `clip_on=False`. - *textprops*: [ *None* | dict of key value pairs ] + textprops: None or dict Dict of arguments to pass to the text objects. - *center*: [ (0,0) | sequence of 2 scalars ] - Center position of the chart. - - *frame*: [ *False* | *True* ] - Plot axes frame with the chart. + center: list of int + Center position of the chart. Takes value (0,0) or is a sequence + of 2 scalars. - *rotatelabels*: [ *False* | *True* ] - Rotate each label to the angle of the corresponding slice. + frame: bool + Plot axes frame with the chart if true. - The pie chart will probably look best if the figure and axes are - square, or the Axes aspect is equal. e.g.:: + rotatelabels: bool + Rotate each label to the angle of the corresponding slice if true. - figure(figsize=(8,8)) - ax = axes([0.1, 0.1, 0.8, 0.8]) + Returns + ------- + patches: list + A sequence of :class:`matplotlib.patches.Wedge` instances - or:: + texts: list + A is a list of the label :class:`matplotlib.text.Text` instances. - axes(aspect=1) + autotexts: list + A is a list of :class:`~matplotlib.text.Text` instances for the + numeric labels. Is returned only is if parameter *autopct* is + not *None*. If *autopct* is *None*, the tuple returned + is (patches, texts). - Return value: - If *autopct* is *None*, return the tuple (*patches*, *texts*): + Notes + -------- + The pie chart will probably look best if the figure and axes are + square, or the Axes aspect is equal. - - *patches* is a sequence of - :class:`matplotlib.patches.Wedge` instances + >>> figure(figsize=(8,8)) + >>> ax = axes([0.1, 0.1, 0.8, 0.8]) - - *texts* is a list of the label - :class:`matplotlib.text.Text` instances. + >>> axes(aspect=1) - If *autopct* is not *None*, return the tuple (*patches*, - *texts*, *autotexts*), where *patches* and *texts* are as - above, and *autotexts* is a list of - :class:`~matplotlib.text.Text` instances for the numeric - labels. """ x = np.array(x, np.float32) From 0b4909a737722fb27e4080f96efb99ecf81f96a9 Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Wed, 22 Mar 2017 11:52:01 +0530 Subject: [PATCH 17/18] FIX small nitpicks # Conflicts: # lib/matplotlib/tests/test_backend_pgf.py --- lib/matplotlib/tests/test_backend_pgf.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/matplotlib/tests/test_backend_pgf.py b/lib/matplotlib/tests/test_backend_pgf.py index 52151256f71a..36120aa785cf 100644 --- a/lib/matplotlib/tests/test_backend_pgf.py +++ b/lib/matplotlib/tests/test_backend_pgf.py @@ -81,9 +81,13 @@ def create_figure(): # test compiling a figure to pdf with xelatex +<<<<<<< HEAD @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_xelatex(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -93,9 +97,13 @@ def test_xelatex(): # test compiling a figure to pdf with pdflatex +<<<<<<< HEAD @needs_pdflatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_pdflatex(): import os if os.environ.get('APPVEYOR', False): @@ -113,10 +121,14 @@ def test_pdflatex(): # test updating the rc parameters for each figure +<<<<<<< HEAD @needs_xelatex @needs_pdflatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_rcupdate(): rc_sets = [] rc_sets.append({'font.family': 'sans-serif', @@ -145,9 +157,13 @@ def test_rcupdate(): # test backend-side clipping, since large numbers are not supported by TeX +<<<<<<< HEAD @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_pathclip(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -162,9 +178,13 @@ def test_pathclip(): # test mixed mode rendering +<<<<<<< HEAD @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_mixedmode(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -177,9 +197,13 @@ def test_mixedmode(): # test bbox_inches clipping +<<<<<<< HEAD @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') +======= +@switch_backend('pgf') +>>>>>>> 40d5e418e... FIX small nitpicks def test_bbox_inches(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} From a0c7bd80c98f79285e4168d98cbea53bf53e0ff4 Mon Sep 17 00:00:00 2001 From: Kanchana Ranasinghe Date: Wed, 22 Mar 2017 13:43:53 +0530 Subject: [PATCH 18/18] Made style changes and edits suggested Added spacing between colons and made the changes pointed out --- lib/matplotlib/axes/_axes.py | 41 ++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index bd62835d9afa..d78581b85485 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -2488,78 +2488,77 @@ def pie(self, x, explode=None, labels=None, colors=None, x : array The input array used to make the pie chart. - explode: None or array + explode : None or array If not *None*, is a ``len(x)`` array which specifies the fraction of the radius with which to offset each wedge. - colors: None or array + colors : None or array A sequence of matplotlib color args through which the pie chart will cycle. If `None`, will use the colors in the currently active cycle. - labels: None or list + labels : None or list A sequence of strings providing the labels for each wedge - autopct: None or string or function + autopct : None or string or function If not *None*, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be ``fmt%pct``. If it is a function, it will be called. - pctdistance: float + pctdistance : float The ratio between the center of each pie slice and the start of the text generated by *autopct*. Ignored if *autopct* is *None*; default is 0.6. - labeldistance: float + labeldistance : float The radial distance at which the pie labels are drawn - shadow: bool + shadow : bool Draw a shadow beneath the pie. - startangle: None or Offset angle + startangle : None or float If not *None*, rotates the start of the pie chart by *angle* degrees counterclockwise from the x-axis. - radius: None or float + radius : None or float The radius of the pie, if *radius* is *None* it will be set to 1. - counterclock: bool + counterclock : bool Specify fractions direction, clockwise or counterclockwise. - wedgeprops: None or dict + wedgeprops : None or dict Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = { 'linewidth' : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default `clip_on=False`. - textprops: None or dict + textprops : None or dict Dict of arguments to pass to the text objects. - center: list of int + center : list of float Center position of the chart. Takes value (0,0) or is a sequence of 2 scalars. - frame: bool + frame : bool Plot axes frame with the chart if true. - rotatelabels: bool + rotatelabels : bool Rotate each label to the angle of the corresponding slice if true. Returns ------- - patches: list + patches : list A sequence of :class:`matplotlib.patches.Wedge` instances - texts: list + texts : list A is a list of the label :class:`matplotlib.text.Text` instances. - autotexts: list + autotexts : list A is a list of :class:`~matplotlib.text.Text` instances for the - numeric labels. Is returned only is if parameter *autopct* is - not *None*. If *autopct* is *None*, the tuple returned - is (patches, texts). + numeric labels. Is returned only if parameter *autopct* is + not *None*. Notes --------