1

How to solve this error:

File "rainbow.py", line 53, in plot_rainbow

xr[0],yr[0] = offset_curve(ax, x,y, lw/2.)

TypeError: 'range' object does not support item assignment

in the following code, please? I tried to replace range with xrange, but it does not help.

import numpy as np
import matplotlib.pyplot as plt
dpi = 100
def offset(x,y, o):
 """ Offset coordinates given by array x,y by o """
 X = np.c_[x,y].T
 m = np.array([[0,-1],[1,0]])
 R = np.zeros_like(X)
 S = X[:,2:]-X[:,:-2]
 R[:,1:-1] = np.dot(m, S)
 R[:,0] = np.dot(m, X[:,1]-X[:,0])
 R[:,-1] = np.dot(m, X[:,-1]-X[:,-2])
 On = R/np.sqrt(R[0,:]**2+R[1,:]**2)*o
 Out = On+X
 return Out[0,:], Out[1,:]
def offset_curve(ax, x,y, o):
 """ Offset array x,y in data coordinates
 by o in points """
 trans = ax.transData.transform
 inv = ax.transData.inverted().transform
 X = np.c_[x,y]
 Xt = trans(X)
 xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72. )
 Xto = np.c_[xto, yto]
 Xo = inv(Xto)
 return Xo[:,0], Xo[:,1]
# some single points
y = np.array([1,2,2,3,3,0]) 
x = np.arange(len(y))
#or try a sinus
x = np.linspace(0,9)
y=np.sin(x)*x/3.
fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)
cols = ["#fff40b", "#00e103", "#ff9921", "#3a00ef", "#ff2121", "#af00e7"]
lw = 2.
lines = []
for i in range(len(cols)):
 l, = plt.plot(x,y, lw=lw, color=cols[i])
 lines.append(l)
def plot_rainbow(event=None):
 xr = range(6); yr = range(6); 
 xr[0],yr[0] = offset_curve(ax, x,y, lw/2.)
 xr[1],yr[1] = offset_curve(ax, x,y, -lw/2.)
 xr[2],yr[2] = offset_curve(ax, xr[0],yr[0], lw)
 xr[3],yr[3] = offset_curve(ax, xr[1],yr[1], -lw)
 xr[4],yr[4] = offset_curve(ax, xr[2],yr[2], lw)
 xr[5],yr[5] = offset_curve(ax, xr[3],yr[3], -lw)
 for i in range(6): 
 lines[i].set_data(xr[i], yr[i])
plot_rainbow()
fig.canvas.mpl_connect("resize_event", plot_rainbow)
fig.canvas.mpl_connect("button_release_event", plot_rainbow)
plt.savefig(__file__+".png", dpi=dpi)
plt.show()

I try to compile the code from this question.

asked Dec 19, 2020 at 18:05

2 Answers 2

2

range object can not be set.

You can change it to list by:

 xr = list(range(6)); yr = list(range(6)); 

But I don't understand why you use in range in the first place. If you just wan to initialize a list, I would go with something like:

xr, yr = 6*[None], 6*[None]

Ofcourse you can put 0 or whatever instead None

answered Dec 19, 2020 at 18:14
1

range() returns range object instead of list. To convert:

xr = list(range(6))
answered Dec 19, 2020 at 18:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.