How to change colors of lines based on an attribute in Matplotlib?

Viewed 176

I've looked everywhere for this answer - sorry if it's been asked already

I'm working with Python 3, and trying to connect dots on a scatter plot based on the color of the dot.

I've tried doing this:

plt.plot(al['yearID'], al['Payroll(K)'])

But I get this: enter image description here

I would like the lines to be the same color as the ones shown on the legend. I tried looping through the dataframe to change the colors, but that is not working.

Is there a way to enumerate through an array while setting colors? Something like:

colors = ["green", "red", "blue"]
plt.plot(al['yearID'], al['Payroll(K)'], colors = *loop through colors array*)

I've also tried making the original plot a line plot, but scatter is the only one that seems to be working. Thanks!

EDIT:

For the first graph:

for i, txt in enumerate(al.teamID):
    team = al['teamID'].iat[i]
    col = color_assignment[team]
    if team in seen:
        plt.scatter(al['yearID'].iat[i], al['Payroll(K)'].iat[i], c = [col])
    else:
        plt.scatter(al['yearID'].iat[i], al['Payroll(K)'].iat[i], c = [col], label = al['teamID'].iat[i])
        seen.append(al['teamID'].iat[i])

I assigned a color to each team with:

colors = []
random_color(al, colors)
team_names = al['teamID'].unique()
color_assignment = {team_names[i] : colors[i] for i in range(len(team_names))}
0 Answers
Related