Home > Software design >  How can I change the color of my scatter plot points based on a "color" column in my datas
How can I change the color of my scatter plot points based on a "color" column in my datas

Time:06-12

I have this code which animates NFL tracking data using plotly. I would like to be able to manually change the color of the home/away team and the ball. I have tried using the code below however it all comes in the same color. I have a column in my dataset called "color" which I would like to be used to assign the color to each individual data point.

# SCATTER TO ANIMATE TRACKING DATA 
fig = px.scatter(data,  x = "x", y = "y", hover_name="displayName",
          color="color", animation_frame = "frameId", animation_group = "displayName",
          range_y = [-5, 60], range_x = [-5, 125])

fig.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 80


for i in range(0, 121, 10):
    fig.add_trace(go.Scatter(x=[i,i], y=[0,53.3], mode='lines', line=dict(color='white'), showlegend=False))
    
fig.update_layout(xaxis=dict(zeroline=False, showgrid=False), 
                  yaxis=dict(zeroline=False, showgrid=False))

fig.add_trace(go.Scatter(x=[0,120], y=[0,0], mode='lines', line=dict(color='white'), showlegend=False))
fig.add_trace(go.Scatter(x=[0,120], y=[53.3,53.3], mode='lines', line=dict(color='white'), showlegend=False))

#fig.write_html("football.html")

fig.update_layout(
    autosize=False,
    width=1000,
    height=600
)

fig

Here is a sample of the data:

x y team color frameId displayName
61.21 46.77 home Green 1 Mahomes
60 32 away black 1 Beckham

And a photo of what I currently have:

Picture of the updated figure (If you look at the right the label names don't match the colors I want)

CodePudding user response:

color_discrete_sequence="color" should just be color="color"

So should be

# SCATTER TO ANIMATE TRACKING DATA 
fig = px.scatter(data,  x = "x", y = "y", hover_name="displayName",
          color="color", animation_frame = "frameId", animation_group = "displayName",
          range_y = [-5, 60], range_x = [-5, 125])

CodePudding user response:

I've managed to do it, I had to set color = "team" and then color_discrete_map. The code that works is:

fig = px.scatter(data,  x = "x", y = "y", hover_name="displayName",
          color="team", animation_frame = "frameId", animation_group = "displayName",
          range_y = [-5, 60], range_x = [-5, 125], color_discrete_map = dict((["home", "black"], ["away", "red"], ["football", "brown"])))
  • Related