Python:如何使用plotly制作阴影区域或交替背景颜色?

12

只使用来自plot.ly的这几行代码,您可以在jupyter笔记本中得到下面的图表:

代码段 1:

import plotly
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)

iplot(cf.datagen.lines().iplot(asFigure=True,
                               kind='scatter',xTitle='Dates',yTitle='Returns',title='Returns'))

情节1:

enter image description here

如何使用matplotlib设置下面的图表,使其像此帖子中所示具有交替的背景颜色?

这里有一个链接,可以解释如何添加类似于以下的阴影区域:

片段2:

df.iplot(vspan={'x0':'2015-02-15','x1':'2015-03-15','color':'rgba(30,30,30,0.3)','fill':True,'opacity':.4}, 
         filename='cufflinks/custom-regions')

情节2:

enter image description here

感谢任何建议!


1
这个 https://dev59.com/d10a5IYBdhLWcg3wxbHm 的回答可能会有所帮助。在 plotly 顶部使用的 cufflinks 无法进行这些更改。 - El Ruso
2个回答

9
如问题所建议的,可能的解决方案可以在vspan函数中找到。然而,使用hspan为y轴添加多个阴影区域似乎更容易,而对于x轴的情况则需要进行一些微调。后者需要更多的细节调整。在我的建议解决方案之后可以找到更多详细信息。
以下图表由下面的代码片段和函数multiShades生成:

图表:

enter image description here

代码片段:

### Setup from the question ###

import plotly
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import numpy as np
from IPython.display import HTML
from IPython.core.display import display, HTML
import copy

# setup
init_notebook_mode(connected=True)
np.random.seed(123)
cf.set_config_file(theme='pearl')

# Random data using cufflinks
df = cf.datagen.lines()

fig = df.iplot(asFigure=True, kind='scatter',
               xTitle='Dates',yTitle='Returns',title='Returns',
               vspan={'x0':'2015-01-11','x1':'2015-02-22','color':'rgba(30,30,30,0.3)','fill':True,'opacity':.4})

### ANSWER ###

xStart = ['2015-01-11', '2015-02-08', '2015-03-08', '2015-04-05']
xStop = ['2015-01-25', '2015-02-22', '2015-03-22', '2015-04-10']

def multiShades(plot, x0, x1):
    """ Adds shaded areas for specified dates in a plotly plot.
        The lines of the areas are set to transparent using rgba(0,0,0,0)
    """
    # get start and end dates
    x0 = xStart
    x1 = xStop

    # get dict from tuple made by vspan()
    xElem = fig['layout']['shapes'][0]

    # container (list) for dicts / shapes
    shp_lst=[]

    # make dicts according to x0 and X1
    # and edit elements of those dicts
    for i in range(0,len(x0)):
        shp_lst.append(copy.deepcopy(xElem))
        shp_lst[i]['x0'] = x0[i]
        shp_lst[i]['x1'] = x1[i]
        shp_lst[i]['line']['color'] = 'rgba(0,0,0,0)'

    # replace shape in fig with multiple new shapes
    fig['layout']['shapes']= tuple(shp_lst)
    return(fig)

fig = multiShades(plot=fig, x0=xStart, x1=xStop)

iplot(fig)

一些细节:

函数vspan将以字典形式填充元组fig['layout']['shapes']

{'fillcolor': 'rgba(187, 187, 187, 0.4)',
 'line': {'color': '#BBBBBB', 'dash': 'solid', 'width': 1},
 'type': 'rect',
 'x0': '2015-01-11',
 'x1': '2015-02-22',
 'xref': 'x',
 'y0': 0,
 'y1': 1,
 'yref': 'paper'}

我的函数只是简单地接受那个字典,制作多个副本,根据函数参数编辑这些副本,并用函数的新元组替换原始元组。
挑战:
当添加更多形状时,这种方法可能会变得有点棘手。此外,日期必须硬编码 - 至少在有人找到如何检索主刻度和网格线的值?的答案之前。

7
现在您可以使用plotly 4.12中添加的fig.add_vrect()来实现此操作。例如,要添加对应于白天时间的阴影区域,请先创建一个列表“morning”,其中包含每天的早晨时间,然后执行以下操作:
for morning in mornings:
    fig.add_vrect(
        x0=morning,
        x1=morning + timedelta(hours=12),
        fillcolor="white",
        opacity=0.1,
        line_width=0,
    )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接