Skip to content

Commit ec1cd25

Browse files
committed
minor docstring, formatting, cleanup changes in contour, colorbar, collections
1 parent 94722ef commit ec1cd25

File tree

4 files changed

+71
-64
lines changed

4 files changed

+71
-64
lines changed
+10-10
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import matplotlib.pyplot as plt
2-
import numpy
2+
import numpy as np
33

44

55
# invent some numbers, turning the x and y arrays into simple
6-
# 2d arrays, which make combining them together easier.
7-
x = numpy.linspace(-3, 5, 150).reshape(1, -1)
8-
y = numpy.linspace(-3, 5, 120).reshape(-1, 1)
9-
z = numpy.cos(x) + numpy.sin(y)
6+
# 2d arrays, which make combining them together easier.
7+
x = np.linspace(-3, 5, 150).reshape(1, -1)
8+
y = np.linspace(-3, 5, 120).reshape(-1, 1)
9+
z = np.cos(x) + np.sin(y)
1010

1111
# we no longer need x and y to be 2 dimensional, so flatten them.
1212
x, y = x.flatten(), y.flatten()
@@ -17,7 +17,7 @@
1717
# ---------------------------------------------
1818
# the simplest hatched plot with a colorbar
1919
fig = plt.figure()
20-
cs = plt.contourf(x, y, z, hatches=['-', '/', '\\', '//'],
20+
cs = plt.contourf(x, y, z, hatches=['-', '/', '\\', '//'],
2121
cmap=plt.get_cmap('gray'),
2222
extend='both', alpha=0.5
2323
)
@@ -31,15 +31,15 @@
3131
plt.figure()
3232
n_levels = 6
3333
plt.contour(x, y, z, n_levels, colors='black', linestyles='-')
34-
cs = plt.contourf(x, y, z, n_levels, colors='none',
35-
hatches=['.', '/', '\\', None, '\\\\', '*'],
34+
cs = plt.contourf(x, y, z, n_levels, colors='none',
35+
hatches=['.', '/', '\\', None, '\\\\', '*'],
3636
extend='lower'
3737
)
3838

39-
# create a legend for the contour set
39+
# create a legend for the contour set
4040
artists, labels = cs.legend_elements()
4141
plt.legend(artists, labels, handleheight=2)
4242

4343

4444

45-
plt.show()
45+
plt.show()

lib/matplotlib/collections.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -235,10 +235,10 @@ def draw(self, renderer):
235235
gc = renderer.new_gc()
236236
self._set_gc_clip(gc)
237237
gc.set_snap(self.get_snap())
238-
238+
239239
if self._hatch:
240240
gc.set_hatch(self._hatch)
241-
241+
242242
renderer.draw_path_collection(
243243
gc, transform.frozen(), paths, self.get_transforms(),
244244
offsets, transOffset, self.get_facecolor(), self.get_edgecolor(),
@@ -322,6 +322,10 @@ def set_hatch(self, hatch):
322322
Hatching is supported in the PostScript, PDF, SVG and Agg
323323
backends only.
324324
325+
Unlike other properties such as linewidth and colors, hatching
326+
can only be specified for the collection as a whole, not separately
327+
for each member.
328+
325329
ACCEPTS: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ]
326330
"""
327331
self._hatch = hatch

lib/matplotlib/colorbar.py

+37-36
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@
135135
False | If *cax* is None, a new *cax* is created as an instance of
136136
Axes. If *ax* is an instance of Subplot and *use_gridspec* is True,
137137
*cax* is created as an instance of Subplot using the
138-
grid_spec module.
138+
grid_spec module.
139139
140140
141141
Additional keyword arguments are of two kinds:
@@ -756,11 +756,11 @@ def __init__(self, ax, mappable, **kw):
756756
def on_mappable_changed(self, mappable):
757757
"""
758758
Updates this colorbar to match the mappable's properties.
759-
759+
760760
Typically this is automatically registered as an event handler
761761
by :func:`colorbar_factory` and should not be called manually.
762-
763-
"""
762+
763+
"""
764764
self.set_cmap(mappable.get_cmap())
765765
self.set_clim(mappable.get_clim())
766766
self.update_normal(mappable)
@@ -892,7 +892,7 @@ def make_axes_gridspec(parent, **kw):
892892
893893
* *make_axes* creates an instance of Axes. *make_axes_gridspec*
894894
creates an instance of Subplot.
895-
895+
896896
* *make_axes* updates the position of the
897897
parent. *make_axes_gridspec* replaces the grid_spec attribute
898898
of the parent with a new one.
@@ -979,96 +979,97 @@ class ColorbarPatch(Colorbar):
979979
"""
980980
A Colorbar which is created using :class:`~matplotlib.patches.Patch`
981981
rather than the default :func:`~matplotlib.axes.pcolor`.
982-
982+
983+
It uses a list of Patch instances instead of a
984+
:class:`~matplotlib.collections.PatchCollection` because the
985+
latter does not allow the hatch pattern to vary among the
986+
members of the collection.
983987
"""
984988
def __init__(self, ax, mappable, **kw):
985989
# we do not want to override the behaviour of solids
986990
# so add a new attribute which will be a list of the
987-
# colored patches in the colorbar
991+
# colored patches in the colorbar
988992
self.solids_patches = []
989993
Colorbar.__init__(self, ax, mappable, **kw)
990-
994+
991995
def _add_solids(self, X, Y, C):
992-
'''
996+
"""
993997
Draw the colors using :class:`~matplotlib.patches.Patch`;
994998
optionally add separators.
995-
'''
999+
"""
9961000
# Save, set, and restore hold state to keep pcolor from
9971001
# clearing the axes. Ordinarily this will not be needed,
9981002
# since the axes object should already have hold set.
9991003
_hold = self.ax.ishold()
10001004
self.ax.hold(True)
1001-
1005+
10021006
kw = {'alpha':self.alpha,}
1003-
1007+
10041008
n_segments = len(C)
1005-
1009+
10061010
# ensure there are sufficent hatches
10071011
hatches = self.mappable.hatches * n_segments
1008-
1012+
10091013
patches = []
10101014
for i in xrange(len(X)-1):
10111015
val = C[i][0]
10121016
hatch = hatches[i]
1013-
1014-
xy = np.array([[X[i][0], Y[i][0]], [X[i][1], Y[i][0]],
1017+
1018+
xy = np.array([[X[i][0], Y[i][0]], [X[i][1], Y[i][0]],
10151019
[X[i+1][1], Y[i+1][0]], [X[i+1][0], Y[i+1][1]]])
1016-
1020+
10171021
if self.orientation == 'horizontal':
10181022
# if horizontal swap the xs and ys
10191023
xy = xy[..., ::-1]
1020-
1024+
10211025
patch = mpatches.PathPatch(mpath.Path(xy),
10221026
facecolor=self.cmap(self.norm(val)),
10231027
hatch=hatch,
1024-
edgecolor='none', linewidth=0,
1028+
edgecolor='none', linewidth=0,
10251029
antialiased=False, **kw
10261030
)
1027-
c = self.mappable.collections[i]
1028-
1031+
10291032
self.ax.add_patch(patch)
10301033
patches.append(patch)
1031-
1034+
10321035
if self.solids_patches:
10331036
for solid in self.solids_patches:
10341037
solid.remove()
1035-
1038+
10361039
self.solids_patches = patches
10371040

1038-
# for compatibility with Colorbar, we will implement edge drawing as a
1039-
# seperate line collection, even though we could have put a line on
1040-
# the patches in self.solids_patches.
10411041
if self.dividers is not None:
10421042
self.dividers.remove()
10431043
self.dividers = None
1044-
1044+
10451045
if self.drawedges:
10461046
self.dividers = collections.LineCollection(self._edges(X,Y),
10471047
colors=(mpl.rcParams['axes.edgecolor'],),
10481048
linewidths=(0.5*mpl.rcParams['axes.linewidth'],)
10491049
)
10501050
self.ax.add_collection(self.dividers)
1051-
1051+
10521052
self.ax.hold(_hold)
1053-
1054-
1053+
1054+
10551055
def colorbar_factory(cax, mappable, **kwargs):
10561056
"""
10571057
Creates a colorbar on the given axes for the given mappable.
1058-
1058+
10591059
Typically, for automatic colorbar placement given only a mappable use
10601060
:meth:`~matplotlib.figure.Figure.colorbar`.
1061-
1061+
10621062
"""
1063-
# if the given mappable is a contourset with any hatching, use
1063+
# if the given mappable is a contourset with any hatching, use
10641064
# ColorbarPatch else use Colorbar
10651065
if (isinstance(mappable, contour.ContourSet) \
10661066
and any([hatch is not None for hatch in mappable.hatches])):
10671067
cb = ColorbarPatch(cax, mappable, **kwargs)
10681068
else:
10691069
cb = Colorbar(cax, mappable, **kwargs)
1070-
1070+
10711071
mappable.callbacksSM.connect('changed', cb.on_mappable_changed)
10721072
mappable.set_colorbar(cb, cax)
1073-
1074-
return cb
1073+
1074+
return cb
1075+

lib/matplotlib/contour.py

+18-16
Original file line numberDiff line numberDiff line change
@@ -844,33 +844,33 @@ def legend_elements(self, variable_name='x', str_format=str):
844844
"""
845845
Return a list of artist and labels suitable for passing through
846846
to :func:`plt.legend` which represent this ContourSet.
847-
847+
848848
Args:
849-
850-
*variable_name*: the string used inside the innequality used
849+
850+
*variable_name*: the string used inside the inequality used
851851
on the labels
852-
852+
853853
*str_format*: function used to format the numbers in the labels
854854
"""
855855
artists = []
856856
labels = []
857-
857+
858858
if self.filled:
859859
lowers, uppers = self._get_lowers_and_uppers()
860860
n_levels = len(self.collections)
861-
861+
862862
for i, (collection, lower, upper) in enumerate(zip(self.collections,
863863
lowers, uppers)):
864-
patch = mpatches.Rectangle((0, 0), 1, 1,
864+
patch = mpatches.Rectangle((0, 0), 1, 1,
865865
facecolor=collection.get_facecolor()[0],
866866
hatch=collection.get_hatch(),
867867
alpha=collection.get_alpha(),
868868
)
869869
artists.append(patch)
870-
870+
871871
lower = str_format(lower)
872872
upper = str_format(upper)
873-
873+
874874
if i == 0 and self.extend in ('lower', 'both'):
875875
labels.append(r'$%s \leq %s$' % (variable_name, upper, ))
876876
elif i == n_levels-1 and self.extend in ('upper', 'both'):
@@ -879,16 +879,16 @@ def legend_elements(self, variable_name='x', str_format=str):
879879
labels.append(r'$%s < %s \leq %s$' % (lower, variable_name, upper))
880880
else:
881881
for collection, level in zip(self.collections, self.levels):
882-
882+
883883
patch = mcoll.LineCollection(None)
884884
patch.update_from(collection)
885-
885+
886886
artists.append(patch)
887887
# format the level for insertion into the labels
888888
level = str_format(level)
889889
labels.append(r'$%s = %s$' % (variable_name, level))
890-
891-
return artists, labels
890+
891+
return artists, labels
892892

893893
def _process_args(self, *args, **kwargs):
894894
"""
@@ -1542,11 +1542,13 @@ def _initialize_x_y(self, z):
15421542
points. This may never actually be advantageous, so this option may
15431543
be removed. Chunking introduces artifacts at the chunk boundaries
15441544
unless *antialiased* is *False*.
1545-
1546-
*hatches*:
1545+
1546+
*hatches*:
15471547
A list of cross hatch patterns to use on the filled areas.
15481548
If None, no hatching will be added to the contour.
1549-
Currently only supported on a few backends.
1549+
Hatching is supported in the PostScript, PDF, SVG and Agg
1550+
backends only.
1551+
15501552
15511553
Note: contourf fills intervals that are closed at the top; that
15521554
is, for boundaries *z1* and *z2*, the filled region is::

0 commit comments

Comments
 (0)