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

仅使用plot.ly 中的这几行代码将在 jupyter notebook 中为您提供以下图:


片段 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:

http://img3.mukewang.com/61a5d75d0001775811240551.jpg

您如何设置它以便您可以在下面的图中使用交替的背景颜色,就像这篇文章中使用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:

http://img3.mukewang.com/61a5d76e0001dd2c07990474.jpg

慕神8447489
浏览 259回答 2
2回答

慕桂英3389331

正如问题中所建议的,一个可能的解决方案可能在于vspan函数。但是,使用hspan,为 y 轴添加多个阴影区域似乎比使用vspan和 x 轴容易得多。后者需要更多的调整。在我建议的解决方案之后可以找到更多详细信息。下图由以下代码段和函数生成multiShades:阴谋:片段:### Setup from the question ###import plotlyimport cufflinks as cffrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport pandas as pdimport numpy as npfrom IPython.display import HTMLfrom IPython.core.display import display, HTMLimport copy# setupinit_notebook_mode(connected=True)np.random.seed(123)cf.set_config_file(theme='pearl')# Random data using cufflinksdf = 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'}我的函数只是获取该字典,制作多个副本,根据函数参数编辑这些副本,然后用函数中的新元组替换原始元组。

慕雪6442864

您现在可以使用plotly 4.12 中添加的fig.add_vrect()来执行此操作。例如,要添加对应于白天时间的阴影区域,有一个列表,早上,指定每天的早上时间,然后:for morning in mornings:    fig.add_vrect(        x0=morning,        x1=morning + timedelta(hours=12),        fillcolor="white",        opacity=0.1,        line_width=0,    )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python