Search code examples
pythonplotlyplotly-python

How to get bar colors of multiple traces from bar chart?


I created a bar chart with multiple traces using a loop. The colors of each trace are assigned by plotly automatically. Now chart is done, how to get colors of all traces? I needed to assign these same colors to another scatter plot inside subplots to make color consistent. Thank you so much for your help.


for i in range (10):
            fig.add_trace(
                    go.Bar(
                        x=weights_df_best.index,
                        y=weights_df_best[col].values,
                        name = col,
                        text=col,
                        hoverinfo='text',
                        legendgroup = '1',
                        offsetgroup=0,
                        ),
                    row=1,
                    col=1,
                         )


Solution

  • If you'd like to put the colors in a list after you've produced a figure, just run:

    colors = []
    fig.for_each_trace(lambda t: colors.append(t.marker.color))
    

    If you use that approach in the complete snippet below, you'll get

    ['#636efa', '#EF553B', '#00cc96']
    

    Plot

    enter image description here

    Complete code:

    import plotly.express as px
    df = px.data.medals_long()
    fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)
    
    colors = []
    fig.for_each_trace(lambda t: colors.append(t.marker.color))
    colors