Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Minor cleanup to Text class. #9832

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 6, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 40 additions & 55 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


def _process_text_args(override, fontdict=None, **kwargs):
"Return an override dict. See :func:`~pyplot.text' docstring for info"
"""Return an override dict. See `~pyplot.text' docstring for info."""
Copy link
Member

Choose a reason for hiding this comment

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

Style nit-picks: Since the primary function of triple quotes is to generate multi-line text blocks, I would prefer to see them used in docstrings only in the form

"""
This is a docstring that might have more than one line.
"""

If you want a docstring to occupy only a single line, to save space, then I think you should use quotes as in the line above before your change. When I see triple quotes, I want to see the ending triple on a subsequent line; and starting a docstring with triple quotes followed by text on the same line looks ugly to me.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is actually explicitly specified in https://www.python.org/dev/peps/pep-0257/#one-line-docstrings. If we decide to explicitly not follow that recommendation it should probably go into the documentation guidelines...

Copy link
Member

Choose a reason for hiding this comment

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

Agreed. I think that PEP is giving bad advice with a silly rationale, but it's not critical. @tacaswell, do you want to follow the PEP for new code and whenever existing docstrings are edited?

Copy link
Member

Choose a reason for hiding this comment

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

Maybe it's just habit, but using always triple quotes feels more consistent. Docstrings look more alike. Even though the rationale in PEP-257 is of course nonsense, I would stick to the suggested conventions.


if fontdict is not None:
override.update(fontdict)
Expand All @@ -51,24 +51,21 @@ def _wrap_text(textobj):
# Extracted from Text's method to serve as a function
def get_rotation(rotation):
"""
Return the text angle as float. The returned
angle is between 0 and 360 deg.
Return the text angle as float between 0 and 360 degrees.

*rotation* may be 'horizontal', 'vertical', or a numeric value in degrees.
"""
try:
angle = float(rotation)
return float(rotation) % 360
except (ValueError, TypeError):
if cbook._str_equal(rotation, 'horizontal') or rotation is None:
angle = 0.
return 0.
elif cbook._str_equal(rotation, 'vertical'):
angle = 90.
return 90.
else:
raise ValueError("rotation is {0} expected either 'horizontal'"
" 'vertical', numeric value or"
"None".format(rotation))

return angle % 360
raise ValueError("rotation is {!r}; expected either 'horizontal', "
"'vertical', numeric value, or None"
.format(rotation))


def _get_textbox(text, renderer):
Expand Down Expand Up @@ -104,9 +101,7 @@ def _get_textbox(text, renderer):
xt_box, yt_box = min(projected_xs), min(projected_ys)
w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box

tr = Affine2D().rotate(theta)

x_box, y_box = tr.transform_point((xt_box, yt_box))
x_box, y_box = Affine2D().rotate(theta).transform_point((xt_box, yt_box))

return x_box, y_box, w_box, h_box

Expand All @@ -125,9 +120,8 @@ def _get_textbox(text, renderer):
"weight": ["fontweight"],
})
class Text(Artist):
"""
Handle storing and drawing of text in window or data coordinates.
"""
"""Handle storing and drawing of text in window or data coordinates."""

zorder = 3
_cached = cbook.maxdict(50)

Expand All @@ -149,8 +143,7 @@ def __init__(self,
**kwargs
):
"""
Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
with string *text*.
Create a `Text` instance at *x*, *y* with string *text*.

Valid kwargs are
%(Text)s
Expand Down Expand Up @@ -232,7 +225,9 @@ def contains(self, mouseevent):
return inside, cattr

def _get_xy_display(self):
'get the (possibly unit converted) transformed x, y in display coords'
"""
Get the (possibly unit converted) transformed x, y in display coords.
"""
x, y = self.get_unitless_position()
return self.get_transform().transform_point((x, y))

Expand All @@ -243,7 +238,7 @@ def _get_multialignment(self):
return self._horizontalalignment

def get_rotation(self):
'return the text angle as float in degrees'
"""Return the text angle as float in degrees."""
return get_rotation(self._rotation) # string_or_number -> number

def set_rotation_mode(self, m):
Expand All @@ -266,11 +261,11 @@ def set_rotation_mode(self, m):
self.stale = True

def get_rotation_mode(self):
"get text rotation mode"
"""Get the text rotation mode."""
return self._rotation_mode

def update_from(self, other):
'Copy properties from other to self'
"""Copy properties from other to self."""
Artist.update_from(self, other)
self._color = other._color
self._multialignment = other._multialignment
Expand Down Expand Up @@ -481,16 +476,16 @@ def set_bbox(self, rectprops):

def get_bbox_patch(self):
"""
Return the bbox Patch object. Returns None if the
FancyBboxPatch is not made.
Return the bbox Patch, or None if the FancyBboxPatch is not made.
"""
return self._bbox_patch

def update_bbox_position_size(self, renderer):
"""
Update the location and the size of the bbox. This method
should be used when the position and size of the bbox needs to
be updated before actually drawing the bbox.
Update the location and the size of the bbox.

This method should be used when the position and size of the bbox needs
to be updated before actually drawing the bbox.
"""

if self._bbox_patch:
Expand All @@ -514,9 +509,8 @@ def update_bbox_position_size(self, renderer):
self._bbox_patch.set_mutation_scale(fontsize_in_pixel)

def _draw_bbox(self, renderer, posx, posy):

""" Update the location and the size of the bbox
(FancyBboxPatch), and draw
"""
Update the location and size of the bbox (FancyBboxPatch), and draw.
"""

x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
Expand All @@ -533,7 +527,6 @@ def _update_clip_properties(self):
clipprops = dict(clip_box=self.clipbox,
clip_path=self._clippath,
clip_on=self._clipon)

if self._bbox_patch:
bbox = self._bbox_patch.update(clipprops)

Expand Down Expand Up @@ -586,11 +579,11 @@ def set_clip_on(self, b):
self._update_clip_properties()

def get_wrap(self):
"""Returns the wrapping state for the text."""
"""Return the wrapping state for the text."""
return self._wrap

def set_wrap(self, wrap):
"""Sets the wrapping state for the text.
"""Set the wrapping state for the text.

Parameters
----------
Expand All @@ -601,8 +594,8 @@ def set_wrap(self, wrap):

def _get_wrap_line_width(self):
"""
Returns the maximum line width for wrapping text based on the
current orientation.
Return the maximum line width for wrapping text based on the current
orientation.
"""
x0, y0 = self.get_transform().transform(self.get_position())
figure_box = self.get_figure().get_window_extent()
Expand All @@ -614,10 +607,7 @@ def _get_wrap_line_width(self):

left = self._get_dist_to_box(rotation, x0, y0, figure_box)
right = self._get_dist_to_box(
(180 + rotation) % 360,
x0,
y0,
figure_box)
(180 + rotation) % 360, x0, y0, figure_box)

if alignment == 'left':
line_width = left
Expand All @@ -630,8 +620,8 @@ def _get_wrap_line_width(self):

def _get_dist_to_box(self, rotation, x0, y0, figure_box):
"""
Returns the distance from the given points, to the boundaries
of a rotated box in pixels.
Return the distance from the given points to the boundaries of a
rotated box, in pixels.
"""
if rotation > 270:
quad = rotation - 270
Expand All @@ -653,7 +643,7 @@ def _get_dist_to_box(self, rotation, x0, y0, figure_box):

def _get_rendered_text_width(self, text):
"""
Returns the width of a given text string, in pixels.
Return the width of a given text string, in pixels.
"""
w, h, d = self._renderer.get_text_width_height_descent(
text,
Expand Down Expand Up @@ -1228,7 +1218,7 @@ class TextWithDash(Text):
__name__ = 'textwithdash'

def __str__(self):
return "TextWithDash(%g,%g,%s)" % (self._x, self._y, repr(self._text))
return "TextWithDash(%g, %g, %r)" % (self._x, self._y, self._text)

def __init__(self,
x=0, y=0, text='',
Expand Down Expand Up @@ -1855,9 +1845,7 @@ def draggable(self, state=None, use_blit=False):

class Annotation(Text, _AnnotationBase):
def __str__(self):
return "Annotation(%g,%g,%s)" % (self.xy[0],
self.xy[1],
repr(self._text))
return "Annotation(%g, %g, %r)" % (self.xy[0], self.xy[1], self._text)

@docstring.dedent_interpd
def __init__(self, s, xy,
Expand All @@ -1876,10 +1864,10 @@ def __init__(self, s, xy,
----------

s : str
The text of the annotation
The text of the annotation.

xy : iterable
Length 2 sequence specifying the *(x,y)* point to annotate
Length 2 sequence specifying the *(x,y)* point to annotate.

xytext : iterable, optional
Length 2 sequence specifying the *(x,y)* to place the text
Expand Down Expand Up @@ -2089,15 +2077,13 @@ def set_figure(self, fig):
Artist.set_figure(self, fig)

def update_positions(self, renderer):
""""Update the pixel positions of the annotated point and the
text.
"""
"""Update the pixel positions of the annotated point and the text."""
xy_pixel = self._get_position_xy(renderer)
self._update_position_xytext(renderer, xy_pixel)

def _update_position_xytext(self, renderer, xy_pixel):
"""Update the pixel positions of the annotation text and the arrow
patch.
"""
Update the pixel positions of the annotation text and the arrow patch.
"""
# generate transformation,
self.set_transform(self._get_xy_transform(renderer, self.anncoords))
Expand Down Expand Up @@ -2236,7 +2222,6 @@ def get_window_extent(self, renderer=None):
simpler to call the method after saving the figure. The
*dpi* used defaults to self.figure.dpi; the renderer dpi is
irrelevant.

'''
if not self.get_visible():
return Bbox.unit()
Expand Down