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

2024-02-20

仅使用这几行代码plot.ly https://plot.ly/python/offline/#plotting-offline-with-cufflinks将在 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'))

Plot 1:

如何设置它以便可以在下面的图中具有交替的背景颜色,如所示这个帖子 https://stackoverflow.com/questions/54652114/matplotlib-how-can-i-add-an-alternating-background-color-when-i-have-dates-on-t using 绘图库 https://matplotlib.org/?

这是一个链接 https://plot.ly/ipython-notebooks/cufflinks/#lines-and-shaded-areas这解释了如何添加阴影区域,如下所示:

片段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')

Plot 2:

感谢您的任何建议!


正如问题中所建议的,可能的解决方案可能在于vspan功能。然而,使用以下命令为 y 轴添加多个阴影区域似乎更容易hspan,比情况是vspan和 x 轴。后者需要更多调整。更多详细信息可以在我建议的解决方案后找到。


下面的图是由代码片段和函数生成的multiShades below:

Plot:

Snippet:

### 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'}

我的函数只是获取该字典,制作多个副本,根据函数参数编辑这些副本,然后用函数中的新元组替换原始元组。

挑战:

当添加更多形状时,这种方法可能会变得有点棘手。此外,日期必须是硬编码的——至少在有人找到答案之前如何检索主要刻度线和网格线的值? https://stackoverflow.com/questions/55118898/plotly-how-to-retrieve-values-for-major-ticks-and-gridlines

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐