Skip to content
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

Fix python3 issues in some examples #3831

Merged
merged 13 commits into from Jan 1, 2015
2 changes: 1 addition & 1 deletion doc/pyplots/text_commands.py
Expand Up @@ -16,7 +16,7 @@

ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)

ax.text(3, 2, unicode('unicode: Institut f\374r Festk\366rperphysik', 'latin-1'))
ax.text(3, 2, u'unicode: Institut f\374r Festk\366rperphysik')

ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
Expand Down
2 changes: 1 addition & 1 deletion doc/pyplots/whats_new_99_spines.py
Expand Up @@ -4,7 +4,7 @@


def adjust_spines(ax,spines):
for loc, spine in ax.spines.iteritems():
for loc, spine in ax.spines.items():
Copy link
Member

Choose a reason for hiding this comment

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

This should be done as six.iteritems(spines)

Copy link
Member Author

Choose a reason for hiding this comment

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

I deliberately chose to avoid six as much as possible to simplify the examples. As I see it examples has a different balance between code readability and performance. But you are probably right that in the cases of axes spines etc. which are somewhat longer loops it makes sense to use iterators.

Copy link
Member

Choose a reason for hiding this comment

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

Fair enough. At this point I think of six as being part of the 'standard'
library and don't write anything without it so did not give it a tremendous
amount of thought.

The case could be made that the examples are should also be examples of
general best practices, and python 2/3 compatibility is one of them, but I
will defer to your judgement on this.

On Tue Nov 25 2014 at 3:40:52 PM Jens Hedegaard Nielsen <
notifications@github.com> wrote:

In doc/pyplots/whats_new_99_spines.py:

@@ -4,7 +4,7 @@

def adjust_spines(ax,spines):

  • for loc, spine in ax.spines.iteritems():
  • for loc, spine in ax.spines.items():

I deliberately chose to avoid six as much as possible to simplify the
examples. As I see it examples has a different balance between code
readability and performance. But you are probably right that in the cases
of axes spines etc. which are somewhat longer loops it makes sense to use
iterators.


Reply to this email directly or view it on GitHub
https://github.com/matplotlib/matplotlib/pull/3831/files#r20893607.

Copy link
Member Author

Choose a reason for hiding this comment

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

I will go through them one by one and change to six in cases like this where it is a definite advantage.

Copy link
Member

Choose a reason for hiding this comment

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

Use your judgment; in my view, six should be used as little as possible, especially in examples. It's an ugly but sometimes necessary workaround for 2/3 compatibility. One would have to have a huge dictionary before there would be any practical difference between items and iteritems, for example.

Copy link
Member

Choose a reason for hiding this comment

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

I agree with @efiring here: Let's not use six in examples unless there is a strong reason on a case-by-case basis.

Copy link
Member Author

Choose a reason for hiding this comment

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

Only 4 spines in a figure so six is unlikely to make a difference.

if loc in spines:
spine.set_position(('outward',10)) # outward by 10 points
else:
Expand Down
20 changes: 10 additions & 10 deletions doc/users/plotting/colormaps/Lfunction.py
Expand Up @@ -3,7 +3,7 @@
with the binary matplotlib colormap, too. Trying to show the difference between
adding blackness to a color at different rates.
'''

from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import colorconv as color
Expand Down Expand Up @@ -39,10 +39,10 @@

# Alter successive rows with more black
k = 1
for i in xrange(red.shape[1]):
for i in range(red.shape[1]):
Copy link
Member

Choose a reason for hiding this comment

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

I would also include from six.moves import range at the top (but we should check the six version that got added in).

Copy link
Member Author

Choose a reason for hiding this comment

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

No need (only 5 items)

# more blackness is closer to 0 than one, and in first column of LAB
lab_add[0,i,0] = lab_add[0,i,0] - 10*i
print i,k
print(i,k)
if i != 0:
lab_geometric[0,i,0] = lab_geometric[0,i,0] - 10*k
k *= 2
Expand All @@ -57,15 +57,15 @@

fig = plt.figure()
k = 1
for i in xrange(red.shape[1]):
for i in range(red.shape[1]):

# LHS: additive
ax1 = fig.add_subplot(nrows,2,i*2+1, axisbg=tuple(rgb_add[0,i,:]))
print tuple(lab_add[0,i,:])#, tuple(rgb_add[0,i,:])
print(tuple(lab_add[0,i,:]))#, tuple(rgb_add[0,i,:])

# RHS: multiplicative
ax2 = fig.add_subplot(nrows,2,i*2+2, axisbg=tuple(rgb_geometric[0,i,:]))
print tuple(lab_geometric[0,i,:])#, tuple(rgb_geometric[0,i,:])
print(tuple(lab_geometric[0,i,:]))#, tuple(rgb_geometric[0,i,:])

# ylabels
if i!=0:
Expand Down Expand Up @@ -117,24 +117,24 @@
k = 1
di = 8
I0 = 5
for i in xrange(nrows):
for i in range(nrows):
# Do more blackness via increasing indices
rgb_add[:,i,:] = rgb[:,i*di+I0,:]

if i != 0:
print i*di+I0, di*k+I0, (I0**(1./3)+i*di**(1./3))**3
print(i*di+I0, di*k+I0, (I0**(1./3)+i*di**(1./3))**3)
rgb_geometric[:,i,:] = rgb[:,I0+di*k,:]
k *= 2
elif i==0:
print i*di+I0, I0, (I0**(1./3)+i*di**(1./3))**3
print(i*di+I0, I0, (I0**(1./3)+i*di**(1./3))**3)
rgb_geometric[:,i,:] = rgb[:,I0,:]

lab_add = color.rgb2lab(rgb_add)
lab_geometric = color.rgb2lab(rgb_geometric)

fig = plt.figure()
k = 1
for i in xrange(nrows):
for i in range(nrows):

# LHS: additive
ax1 = fig.add_subplot(nrows,ncols,i*2+1, axisbg=tuple(rgb_add[0,i,:]))
Expand Down
2 changes: 1 addition & 1 deletion doc/users/plotting/colormaps/lightness.py
Expand Up @@ -58,7 +58,7 @@

fig = plt.figure(figsize=(11.5,4*nsubplots))

for i, subplot in enumerate(xrange(nsubplots)):
for i, subplot in enumerate(range(nsubplots)):
Copy link
Member Author

Choose a reason for hiding this comment

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

Less that 10 items


locs = [] # locations for text labels

Expand Down
2 changes: 1 addition & 1 deletion doc/users/plotting/examples/demo_gridspec06.py
Expand Up @@ -23,7 +23,7 @@ def squiggle_xy(a, b, c, d, i=np.arange(0.0, 2*np.pi, 0.05)):
# gridspec inside gridspec
outer_grid = gridspec.GridSpec(4, 4, wspace=0.0, hspace=0.0)

for i in xrange(16):
for i in range(16):
Copy link
Member Author

Choose a reason for hiding this comment

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

16 elements. Iterator makes no difference

inner_grid = gridspec.GridSpecFromSubplotSpec(3, 3,
subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
a, b = int(i/4)+1,i%4+1
Expand Down
2 changes: 1 addition & 1 deletion examples/api/skewt.py
Expand Up @@ -146,7 +146,7 @@ def _set_lim_and_transforms(self):
# Now make a simple example using the custom projection.
from matplotlib.ticker import ScalarFormatter, MultipleLocator
import matplotlib.pyplot as plt
from StringIO import StringIO
from six import StringIO
import numpy as np

# Some examples data
Expand Down
10 changes: 8 additions & 2 deletions examples/lines_bars_and_markers/marker_reference.py
@@ -1,6 +1,7 @@
"""
Reference for filled- and unfilled-marker types included with Matplotlib.
"""
from six import iteritems
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
Expand Down Expand Up @@ -32,9 +33,14 @@ def split_list(a_list):
fig, axes = plt.subplots(ncols=2)

# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.iteritems()
# We use iteritems from six to make sure that we get an iterator
# in both python 2 and 3
unfilled_markers = [m for m, func in iteritems(Line2D.markers)
if func != 'nothing' and m not in Line2D.filled_markers]
unfilled_markers = sorted(unfilled_markers)[::-1] # Reverse-sort for pretty
# Reverse-sort for pretty. We use our own sort key which is essentially
# a python3 compatible reimplementation of python2 sort.
unfilled_markers = sorted(unfilled_markers,
key=lambda x: (str(type(x)), str(x)))[::-1]
for ax, markers in zip(axes, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, nice_repr(marker), **text_style)
Expand Down
2 changes: 1 addition & 1 deletion examples/pylab_examples/animation_demo.py
Expand Up @@ -13,7 +13,7 @@
y = np.arange(5)
z = x * y[:, np.newaxis]

for i in xrange(5):
for i in range(5):
if i == 0:
p = plt.imshow(z)
fig = plt.gcf()
Expand Down
4 changes: 2 additions & 2 deletions examples/pylab_examples/boxplot_demo2.py
Expand Up @@ -57,15 +57,15 @@
# Now fill the boxes with desired colors
boxColors = ['darkkhaki', 'royalblue']
numBoxes = numDists*2
medians = range(numBoxes)
medians = list(range(numBoxes))
for i in range(numBoxes):
box = bp['boxes'][i]
boxX = []
boxY = []
for j in range(5):
boxX.append(box.get_xdata()[j])
boxY.append(box.get_ydata()[j])
boxCoords = zip(boxX, boxY)
boxCoords = list(zip(boxX, boxY))
# Alternate between Dark Khaki and Royal Blue
k = i % 2
boxPolygon = Polygon(boxCoords, facecolor=boxColors[k])
Expand Down
2 changes: 1 addition & 1 deletion examples/pylab_examples/logo.py
Expand Up @@ -9,7 +9,7 @@
datafile = cbook.get_sample_data('membrane.dat', asfileobj=False)
print('loading', datafile)

x = 1000*0.1*fromstring(file(datafile, 'rb').read(), float32)
x = 1000*0.1*fromstring(open(datafile, 'rb').read(), float32)
Copy link
Member

Choose a reason for hiding this comment

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

Should probably do this with a context manager, but that is out of scope for this PR.

Copy link
Member Author

Choose a reason for hiding this comment

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

Agreed

# 0.0005 is the sample interval
t = 0.0005*arange(len(x))
figure(1, figsize=(7, 1), dpi=100)
Expand Down
2 changes: 1 addition & 1 deletion examples/pylab_examples/multiple_yaxis_with_spines.py
Expand Up @@ -4,7 +4,7 @@
def make_patch_spines_invisible(ax):
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.itervalues():
for sp in ax.spines.values():
Copy link
Member

Choose a reason for hiding this comment

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

six.itervalues(...)

Copy link
Member Author

Choose a reason for hiding this comment

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

No need, there is a maximum of 4 spines

sp.set_visible(False)

fig, host = plt.subplots()
Expand Down