Create a legend for user-defined marker_colors in Plotly

Viewed 115

I´ve set manually colors for some bars of a bar plot (one which corresponds to the max value and another one - to the value I´d like to draw attention to).

Here´s a sample of the df

  ranking = df['rank_1', 'rank_2', 'rank_3', 'rank_4', 'rank_5', 'rank_6'].mean()
    >>> ranking

   rank_1   3.267
   rank_2   2.911
   rank_3   2.654
   rank_4   3.729
   rank_5   4.485
   rank_6   3.953

Here´s how I plot it.

fig = px.bar(ranking, x=ranking.values, y=ranking.index, orientation='h', 
         labels={'x': 'average rank', 'y': 'movie'})

colors=[] 
for val in ranking.values:
    colors.append('rgb(252, 128, 14)' if val ==  ranking.values.max() else 'rgb(137, 137, 137)')
colors[1] = 'rgb(95, 158, 209)'

fig.update_traces(hovertemplate='<i>Average rank:</i> %{x:.2f}', marker_color=colors)

How can I create a legend for colors used in the plot?

0 Answers
Related