Reputation:
Here is my code. I've done this before and it's worked. I want the negative bars to be red and the positive bars to be green but I'm just getting all yellow.
import pandas as pd
import plotly.express as px
deciles = pd.read_csv('https://github.com/ngpsu22/2016-2018-ASEC-/raw/master/deciles.csv')
fig = px.bar(deciles, x="deciles", y="percent_change",
text='percent_change',
height=800,
labels={
"percent_change": "Percent change",
"deciles": "Decile"
},
color_discrete_map={'10th': '#6aaa96',
'20th': '#6aaa96',
'30th': '#6aaa96',
'40th': '#6aaa96',
'50th': '#6aaa96',
'60th': '#e67f83',
'70th': '#e67f83',
'80th': '#e67f83',
'90th': '#e67f83'})
fig.update_layout(
title='Average percent change in real resources per person',
xaxis_tickfont_size=14,
yaxis=dict(
title='Percent change in real resources',
titlefont_size=16,
tickfont_size=14))
fig.update_traces(textposition='outside')
fig.update_traces(texttemplate='%{text}%')
fig.update_layout(uniformtext_minsize=14, uniformtext_mode='hide', xaxis_tickfont_size=16)
fig.show()
Upvotes: 1
Views: 2656
Reputation: 13437
You better add a new columns called color
and use within plotly.express
or import plotly.graph_objects as go
import pandas as pd
import plotly.express as px
import numpy as np
deciles = pd.read_csv('https://github.com/ngpsu22/2016-2018-ASEC-/raw/master/deciles.csv')
# here you define the color
deciles["color"] = np.where(deciles["percent_change"] >= 0, 'green', "red")
fig = px.bar(deciles, x="deciles", y="percent_change",
text='percent_change',
color='color',
height=800,
labels={"percent_change": "Percent change",
"deciles": "Decile"
},)\
.update_traces(showlegend=False) # you don't need legend in this case
fig.update_layout(
title='Average percent change in real resources per person',
title_x=0.5, # title is nicer if centered
xaxis_tickfont_size=14,
yaxis=dict(
title='Percent change in real resources',
titlefont_size=16,
tickfont_size=14))
fig.update_traces(textposition='outside')
fig.update_traces(texttemplate='%{text}%')
fig.update_layout(uniformtext_minsize=14, uniformtext_mode='hide', xaxis_tickfont_size=16)
fig.show()
Upvotes: 2