Plotly bar chart - change color based on positive/negative value - python

Viewed 6973

I have the following code which plots a bar chart (1 series), but I need the bars to be coloured blue if the 'Net' value is positive, and red if its negative:

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({
     'Net':[15,20,-10,-15], 
     'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020']
})

df['Date'] = pd.to_datetime(df['Date'])
fig = go.Figure(data=[go.Bar(name='Net', x=df['Date'], y=df['Net'])])
fig.update_layout(barmode='stack')
fig.show()
2 Answers

You can check documentation here. Full code as following

import pandas as pd
import plotly.graph_objects as go
import numpy as np

# Data

df = pd.DataFrame({
     'Net':[15,20,-10,-15], 
     'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020']
})

df['Date'] = pd.to_datetime(df['Date'])

## here I'm adding a column with colors
df["Color"] = np.where(df["Net"]<0, 'red', 'green')

# Plot
fig = go.Figure()
fig.add_trace(
    go.Bar(name='Net',
           x=df['Date'],
           y=df['Net'],
           marker_color=df['Color']))
fig.update_layout(barmode='stack')
fig.show()

enter image description here

@rpanai that is a great answer and got me where I needed to go. I wanted to simply add a way to do the same if using plotly.express.

Note that most of this is the same as above.

import pandas as pd
import numpy as np
import plotly.express as px

df = pd.DataFrame({
       'Net':[15,20,-10,-15],
       'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020']
})
df['Date'] = pd.to_datetime(df['Date'])
df["Color"] = np.where(df["Net"]<0, 'red', 'green')

# PLOT
fig = px.bar(df,x="Date",y="Net")

# COLOR
fig.update_traces(marker_color=df["Color"])

fig.show()
Related