0
votes

I have a set of sales data in a Pandas dataframe df that looks similar to the following:

import pandas as pd

df = pd.DataFrame({'date':['2021-01-04', '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08', '2021-01-11', '2021-01-12', '2021-01-13', '2021-01-14', '2021-01-15'],
                  'sales':[1500, 2000, 1300, 2700, 1800, 4500, 2600, 2750, 8000, 1300]})

    date          sales
0   2021-01-04    1500
1   2021-01-05    2000
2   2021-01-06    1300
3   2021-01-07    2700
4   2021-01-08    1800
5   2021-01-11    4500
6   2021-01-12    2600
7   2021-01-13    2750
8   2021-01-14    8000
9   2021-01-15    1300

I then plot this data, as follows:

import plotly.express as px

fig = px.bar(df, x='date', y='sales')

fig.add_hrect(y0=0, y1=2200, line_width=0, fillcolor="red", opacity=0.25)
fig.add_hrect(y0=2200, y1=5000, line_width=0, fillcolor="yellow", opacity=0.25)
fig.add_hrect(y0=5000, y1=10000, line_width=0, fillcolor="green", opacity=0.25)

fig.show()

enter image description here

As you can see, the blue vertical bars turn a purple color when combined with the red background color.

One workaround might be to paint the red, green, and yellow background colors first, then to overlay the blue bars. This way, we're not 'mixing' red and blue, thereby making purple.

Is this possible? Is there another, better solution?

Thanks!

1

1 Answers

2
votes

There is the option to add layer='below' to the add_hrect.

fig = px.bar(df, x='date', y='sales')

fig.add_hrect(y0=0, y1=2200, line_width=0, fillcolor="red", opacity=0.25, layer='below')
fig.add_hrect(y0=2200, y1=5000, line_width=0, fillcolor="yellow", opacity=0.25, layer='below')
fig.add_hrect(y0=5000, y1=10000, line_width=0, fillcolor="green", opacity=0.25, layer='below')