Python Plotly Express:如何有条件地填充区域图?

Posted

技术标签:

【中文标题】Python Plotly Express:如何有条件地填充区域图?【英文标题】:Python Plotly Express: How to conditionally fill an area plot? 【发布时间】:2021-11-01 10:54:28 【问题描述】:

我想绘制一个时间序列区域图,其中正 (>= 0) 值以一种颜色填充,负 (

举个例子:

import pandas as pd
import numpy as np
import plotly.express as px

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').assign(
    PnL = lambda x: x['AAPL.Close'] - 100
)
px.area(
    data_frame = df,
    x = 'Date',
    y = 'PnL',
    width = 500,
    height = 300
)

我希望将 PnL 低于 0 的部分填充为红色。

这就是我尝试过的:

import pandas as pd
import numpy as np
import plotly.express as px

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').assign(
    PnL = lambda x: x['AAPL.Close'] - 100
)
df['sign'] = np.where(df['PnL'] >= 0, 'positive', 'negative')
px.area(
    data_frame = df,
    x = 'Date',
    y = 'PnL',
    color = 'sign',
    color_discrete_map = 
        'positive': 'steelblue',
        'negative': 'crimson'
    ,
    width = 500,
    height = 300
)

但这给了我:

这不是我想要的。最好的方法是什么?

【问题讨论】:

您能否详细解释一下与您要查找的内容有何不同? 【参考方案1】:

这是我在有耐心的时候能做的最好的事情:

import plotly.graph_objects as go

mask = df['PnL'] >= 0
df['PnL_above'] = np.where(mask, df['PnL'], 0)
df['PnL_below'] = np.where(mask, 0, df['PnL'])

fig = go.Figure()
fig.add_trace(go.Scatter(x=df['Date'], y=df['PnL_above'], fill='tozeroy'))
fig.add_trace(go.Scatter(x=df['Date'], y=df['PnL_below'], fill='tozeroy'))

结果:

显然不理想,但可以帮助您完成大部分工作。两条迹线相交处有一些轻微的伪影,显然值为零时线条颜色仍然可见。

通过将mode='none'添加到两条迹线中,您可以移除线条并仅渲染填充区域:

【讨论】:

以上是关于Python Plotly Express:如何有条件地填充区域图?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Python 中更改 plotly.express 的颜色和大小?

Plotly:如何手动设置 plotly express 散点图中点的颜色?

如何使用字典中的 plotly express 创建(条形)图?

如何使用 Python 中的 Plotly Express 为每个条形图添加可点击链接?

Plotly:如何在 plotly express 折线图中更改图例的变量/标签名称?

Plotly:如何使用 plotly express 在单迹散点图中显示图例?