Search code examples
pythonanimationcolorsplotlybar-chart

change bar colour in plotly animation chart


I've plotted an animated bar chart using the following code, but the default bar colour is blue, how can I change it?

import plotly.express as px

fig = px.bar(df, x="x", y="Y", 
  animation_frame="Year_slider")

fig.show()

I've tried:

fig.update_traces(marker_color='green')

This only provide the green colour for the first bar, not the rest of the bars as the year slider goes further, how could I make all the bar colour green instead of the default colour?


Solution

  • Animation in plotly is realized by creating data for each frame of the animation, which can be seen by executing print(fig.frames). The composition of the graph consists of the initial graph data(fig.data), layout information(fig.layout), and animation frame information(fig.frames). So not only the initial color needs to be changed, but also the animation frames. For each frame, change the color of the bar graph. Your data is unknown, but I have created the code by modifying the examples in the reference for illustrative purposes.

    import plotly.express as px
    
    data_Africa = px.data.gapminder().query("continent == 'Africa'")
    fig = px.bar(data_Africa, x='country', y='pop', animation_frame='year')
    fig.update_traces(marker_color='green')
    
    for i,frame in enumerate(fig.frames):
        fig.frames[i]['data'][0]['marker']['color'] = 'green'
    
    fig.update_yaxes(range=[0, 100_000_000])
    
    fig.show()
    

    enter image description here