Plotly multiple axes colors merge

Viewed 88

Im trying to plot the different stats of two football players mirrored across. Id like the better stat to have a green color and the worse stat red. Only problem is In my color scale one color will be red and one will be green which merges both. Does anyone know a solution or a better way to plot this kind of graph?

data =[['Messi', 88]]
   data2 = [['Ronaldo', -88]]

   df = pd.DataFrame(data, columns=['Player', 'Dribbling'])
   df2 = pd.DataFrame(data2, columns=['Player', 'Dribbling'])

   fig = make_subplots(specs=[[{"secondary_y": True}]])

   fig.add_trace(go.Bar(
            orientation='h',
            name=df['Player'],
            x=df['Dribbling'],
            marker_color=((df.Dribbling >= df2.Dribbling)).astype('int'),
            marker_colorscale=[[0, 'red'], [1, 'green']],
            ),secondary_y=False)
            

   fig.add_trace(go.Bar(
            orientation='h',
            name=df2['Player'],
            x=df2['Dribbling'],
            marker_color=((df.Dribbling >= df2.Dribbling)).astype('int'),
            marker_colorscale=[[0, 'red'], [1, 'green']],
            ),secondary_y=True)

   fig.update_layout(
      barmode="group"
   )
   fig.update_xaxes(range=[-100, 100])

1 Answers

I think your method could be simplified a bit. It doesn't seem like a secondary y-axis is needed, just a categorical one for the different players. I also think that the way you have set up your colors, brown is the actual color - if you only plot one bar, it's still that brown color.

An easier way to achieve what you want is to combine both players' information in one DataFrame, then create a column called "Color" where the minimum score is mapped to "red" and the maximum score is mapped to "green", then loop through the rows of your DataFrame and add a horizontal bar as a trace for each loop iteration.

This method has the advantage of being generalizable: if you want to plot the stats of other football players and have their bars be another color, you can modify the DataFrame and the plotting code will still work.

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame([['Messi', 88],['Ronaldo', -88]], columns=['Player', 'Dribbling'])
df["Color"] = ['red' if x==min(df.Dribbling) else "green" if x==max(df.Dribbling) else np.nan for x in df.Dribbling]

fig = go.Figure()
for row in df.itertuples(index=False):
    fig.add_trace(go.Bar(
        orientation='h',
        name=row.Player,
        x=[row.Dribbling],
        y=[row.Player],
        marker_color=row.Color,
    ))
        
fig.show()

enter image description here

Related