0

I have a few lines of code that creates a great bar chart.

import plotly.express as px
fig = px.bar(df, x="site_name", y="value", color="variable", title="2019 & 2020 Revenue vs. Expenses")
fig.show()

Here is some sample data.

# Import pandas library 
import pandas as pd 
  
# initialize list of lists 
data = [['14', '20 Hudson Yards_IB', 'revenue', '2651324.42'], 
        ['5', '5 Camden Yards', 'revenue', '2772115.61'],
        ['12', 'PHO_SUNS', 'revenue', '2818249.28'],
        ['87', 'OSUMC--MAIN', 'expense', '4300628.21'],
        ['7', 'DA STADIUM', 'expense', '6452307.48'],
        ['99', '50 Midtown East', 'expense', '3534523.12']] 
  
# Create the pandas DataFrame 
df_result = pd.DataFrame(data, columns = ['index', 'site_name', 'variable', 'value']) 
# print dataframe. 
df_result

Result:

     index      site_name              variable       value
0    14         20 Hudson Yards_IB     revenue        2651324.42
1    5          5 Camden Yards         revenue        2772115.61
2    12         PHO_SUNS               revenue        2818249.28
3    87         OSUMC--MAIN            expense        4300628.21
4    7          DA STADIUM             expense        6452307.48
5    99         50 Midtown East        expense        3534523.12

The chart is almost exactly what I want, but I'm trying to get two specific colors for two variables. One variable is 'revenue' and one variable is 'expenses'. Now, with the default code shown above, my chart is red for revenue and blue for expenses. What I really want to do is make the 'revenue' green and 'expenses' red. How can I control this?

ASH
  • 20,759
  • 19
  • 87
  • 200
  • I got busy with something else at work; just circled back to this now. I updated my original post with some sample data. Thanks for the look. – ASH Feb 24 '21 at 23:58

1 Answers1

2

Use color_discrete_sequence and to specify order, use category_orders

fig = px.bar(df, x="site_name", y="value", color="variable", 
             color_discrete_sequence=["green","red"], 
             category_orders={"variable":["Revenue","Expenses"]}, 
             title="2019 & 2020 Revenue vs. Expenses")

or use color_discrete_map

fig = px.bar(df, x="site_name", y="value", color="variable", 
             color_discrete_map={"Revenue": "green", "Expenses":"red"}, 
             category_orders={"variable":["Revenue","Expenses"]}, 
             title="2019 & 2020 Revenue vs. Expenses")
Ani
  • 532
  • 3
  • 13
  • 1
    Awesome! Thank you so much!! The other link under 'This question already has an answer here:' is very helpful too!! – ASH Feb 25 '21 at 03:14