首页 > 解决方案 > Plotly:向条形图添加阴影阈值

问题描述

我在 Pandas 数据框中有一个销售数据集,df类似于以下内容:

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

我绘制了这些数据,如下所示:

import plotly.express as px

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

在此处输入图像描述

我希望能够添加一些阴影“阈值”,类似于以下内容:

在此处输入图像描述

阈值是:

这将类似于 中的fill_between方法Matplotlib

这在 Plotly 中可能吗?

谢谢!

标签: pythonplotlyplotly-dashplotly-python

解决方案


最好是add_hrect()在这种情况下使用。

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)

推荐阅读