For loop for assigning colors to a plot python

Tags: , , ,



I am working on a for loop to assign numbers to the classes and I am successful in that but I find it hard to simultaneously insert different colors based on the number of classes using the same for loop but I am getting the error :‘list’ object cannot be interpreted as an integer

Below is the code:

n_class = 5
colors = ['r', 'g', 'b', 'y','k', 'y']
# plotting
for i, c in range(n_class, colors):
    plt.plot(fpr[i], tpr[i], linestyle='--',color=[c], label= 'Class %d' %i )
        

plt.title('Multiclass ROC curve')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive rate')
plt.legend(loc='best')
plt.savefig('Multiclass ROC',dpi=300);

Answer

The error is on this line

for i, c in range(n_class, colors):

It’s pretty simple, all you have to do is to get the length of the list

for i, c in range(n_class, len(colors)):

But I don’t think that’s the main error are, because then it will take it as

range(5,6)

if you want to give all the plots a color you’ll need

for i in range(len(colors)):
    plt.plot(fpr[i], tpr[i], linestyle='--',color=colors[i], label= 'Class %d' %i )


Source: stackoverflow