简体   繁体   中英

Plotly: adding a shaded threshold to a bar plot

I have a dataset 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 plot this data, as follows:

import plotly.express as px

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

在此处输入图像描述

I would like to be able to add some shaded 'thresholds', similar to the following:

在此处输入图像描述

The thresholds are:

  • Green: greater than 5,000
  • Yellow: greater than 2,200 and less than 5,000
  • Red: less than 2,200

This would be similar to the fill_between method in Matplotlib .

Is this possible in Plotly?

Thanks!

The best is to use add_hrect() in this case.

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)

Add this between figure creation and fig.show():

fig.add_shape(type="rect", line_width=0,
    xref="x domain",
    x0=0, x1=1, y0=0, y1=2200,
    fillcolor="Red", opacity=0.25,
)

This will give you the red rectangle, you can add the other ones accordingly by adjusting fillcolor and opacity as well as y0 and y1 to your needs.

Note how x0 and x1 are given in relative coordinates of zero to one to span the complete figure (because xref="x domain") but y0 and y1 use absolute values.

For further reference, see the Plotly docs on Shapes .

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