python - Plotly:如何根据条件为两条线之间的填充着色?

标签 python charts plotly fill plotly-python

我想在 Plotly 图表上的黑色和蓝色线之间添加填充颜色。我知道这可以通过 Plotly 完成,但我不确定如何根据条件用两种颜色填充图表。 This is my Plotly chart This is what I want to achieve
蓝色背景的图表是我的 Plotly 图表。我想让它看起来像带有白色背景的图表。 (忽略白色图表上的红色和绿色条)
我希望它通过的条件是:
如果黑线在蓝线上方,则将两条线之间的区域填充为绿色。
如果黑线低于蓝线,则将两条线之间的区域填充为红色。
如何用 Plotly 做到这一点?如果 Plotly 无法做到这一点,可以使用其他与 Python 一起工作的图形工具来完成。

最佳答案

出于多种原因(如果您感兴趣,我愿意进一步解释),最好的方法似乎是在每次平均值相互交叉时向 go.Figure() 对象添加两条轨迹,然后使用 fill='tonexty' 定义填充第二个跟踪使用:

for df in dfs:
    fig.add_traces(go.Scatter(x=df.index, y = df.ma1,
                              line = dict(color='rgba(0,0,0,0)')))
    
    fig.add_traces(go.Scatter(x=df.index, y = df.ma2,
                              line = dict(color='rgba(0,0,0,0)'),
                              fill='tonexty', 
                              fillcolor = fillcol(df['label'].iloc[0])))
fillcolor 是一个简单的自定义函数,在下面的完整代码段中进行了描述。每次平均值相互交叉时,我都使用 How to split a dataframe each time a string value changes in a column? 中描述的方法在数据帧中生成必要的拆分。
阴谋
enter image description here
完整代码:
import plotly.graph_objects as go
import numpy as np

import pandas as pd
from datetime import datetime
pd.options.plotting.backend = "plotly"

# sample data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df.index = df.Date
df = df[['AAPL.Close', 'mavg']]
df['mavg2'] = df['AAPL.Close'].rolling(window=50).mean()
df.columns = ['y', 'ma1', 'ma2']
df=df.tail(250).dropna()
df1 = df.copy()

# split data into chunks where averages cross each other
df['label'] = np.where(df['ma1']>df['ma2'], 1, 0)
df['group'] = df['label'].ne(df['label'].shift()).cumsum()
df = df.groupby('group')
dfs = []
for name, data in df:
    dfs.append(data)

# custom function to set fill color
def fillcol(label):
    if label >= 1:
        return 'rgba(0,250,0,0.4)'
    else:
        return 'rgba(250,0,0,0.4)'

fig = go.Figure()

for df in dfs:
    fig.add_traces(go.Scatter(x=df.index, y = df.ma1,
                              line = dict(color='rgba(0,0,0,0)')))
    
    fig.add_traces(go.Scatter(x=df.index, y = df.ma2,
                              line = dict(color='rgba(0,0,0,0)'),
                              fill='tonexty', 
                              fillcolor = fillcol(df['label'].iloc[0])))

# include averages
fig.add_traces(go.Scatter(x=df1.index, y = df1.ma1,
                          line = dict(color = 'blue', width=1)))

fig.add_traces(go.Scatter(x=df1.index, y = df1.ma2,
                          line = dict(color = 'red', width=1)))

# include main time-series
fig.add_traces(go.Scatter(x=df1.index, y = df1.y,
                          line = dict(color = 'black', width=2)))

fig.update_layout(showlegend=False)
fig.show()

关于python - Plotly:如何根据条件为两条线之间的填充着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64741015/

相关文章:

python - Pandas 行计算

javascript - Google Visualization API 多次调用权限被拒绝 (IE)

r - 如何使用 plotly 在 R 中将每个带有数据子集的多条轨迹/趋势线添加到单个散点图

python - 如何在 Plotly 中根据 X、Y、Z 数组绘制 3D 曲面?

python - Plotly:如何使用散点图显示 multiIndex 数据框?

python - 使用 tkinter 创建计时器

python - Numpy 数组改变 id

android - 使用 achartengine 的条形图

delphi - T 图表 - 不绘制小于 0 的值吗?

Python:将列表链接在一起