roudan
roudan

Reputation: 4200

customize color of bar chart based on value in plotly

I am using plotly go figure instead of plotly express. so I use go.Bar(), How to color the bar based on the value?

I am thinking to loop over one value at a time to plot one bar for one value such that different bar will have different colors. Now the question is how to customize the color based on value, for example, from small value to larger value use colors from blue to red.

Here is what I did for subplot case:

    for ix_loc,loc in enumerate(time_plot_location_list):
        fig.add_trace(
            go.Bar(
            x=[time_plot_location_list[ix_loc]],   # single data have to use list [data]
            y=[slope_list[ix_loc]],  
            text=slope_list[ix_loc],
            hoverinfo='text',
            ),
            row=row,
            col=1,
                     )

enter image description here Thank you so much for your help

Upvotes: 0

Views: 3350

Answers (1)

Davide_sd
Davide_sd

Reputation: 13150

Sometimes, while looking at Plotly documentation we can see examples that are easily achievable with Plotly express but "undocumented" on plotly.graph_objects. In these occasions we can execute the example with plotly express, and explore what's going on with fig.data[0] (for example). Then, we can replicate the options on regular plotly.graph_objects.

Here is how you achieve it:

import plotly.graph_objects as go
import numpy as np

x = np.arange(20)
y = np.random.rand(len(x)) * 10
fig = go.Figure(data=[
    go.Bar(
        x=x, y=y,
        marker=dict(
            color=np.cos(x / 3),
            colorscale="Bluered_r",
            showscale=True,
            colorbar=dict(title="value"),
        ),
    )
])

enter image description here

Upvotes: 2

Related Questions