简体   繁体   中英

Plotly: preventing bars on bar chart from changing color based on background color

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()

在此处输入图像描述

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!

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM