The below pasted code gives me error TypeError: list indices must be integers or slices, not str . The code identical to the solution, i copied the solution in jupyter notebook and that gives correct output but my below code is throwing error.
stem_cats = ['Engineering', 'Computer Science', 'Psychology', 'Biology', 'Physical Sciences', 'Math and Statistics']
major_cat =['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig = plt.figure(figsize=(18,3))
for x in range(0,6):
ax = fig.add_subplot(1,6,x+1)
ax.plot(women['Year'],women[stem_cats[x]],c='blue',label='Women')
ax.plot(women['Year'],100-women[stem_cats[x]],c='green',label='Men')
for x,y in ax.spines.items():
y.set_visible(False)
ax.set_xlim(1968,2011)
ax.set_ylim(0,100)
ax.set_title(stem_cats[x])
ax.tick_params(bottom="off", top="off", left="off", right="off")
if x == 0:
ax.text(2005,87,"Men")
ax.text(2002,8,"Women")
elif x == 5:
ax.text(2005,62,"Men")
ax.text(2001,35,"Women")
plt.show()
Around which lines of code does the stack trace say the error is? You can start reading it from top to down, it will show you what code calls what code and the bottom of the trace is where the error is generated. (but starting from the top is easier since that’s code you wrote). I suspect there may be indexing operator [] on a list, like lst[] that contains strings.
You can try enclosing your code with triple back ticks ``` so the indentations are normal and more readable
"off" are deprecated in later versions of matplotlib.
Use boolean value instead. ax.tick_params(bottom=False, top=True, left=False, right=False)
The error message tells you that the input for list indices must be integers or slices and not string. That is, your input for list indices is a string. This is causing an error.
stem_cats is a list.
To access an element, you have to provide integers or slice notation.
The error message tell us that x is a string object. x is an invalid type to access an element in a list.
To fix it, you have either change x into an integer object if x is a numeric value but in string format. Example:
y = [0, 1, 2]
x = "1" # String object
y[int(x)] # convert x into integer
Or, you have to provide a valid input instead since x cannot be converted into integer.
In the future you can use the markdown back ticks to format your code in the discourse post to be more readable for others to understand faster in order for a faster reply.
Use triple backticks to format a block of code ```python
while x:
x += 1
if x == 4: break ```