1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python123填充颜色_Python:如何使用plotly制作着色区域或交替背景色?

python123填充颜色_Python:如何使用plotly制作着色区域或交替背景色?

时间:2021-11-07 23:14:59

相关推荐

python123填充颜色_Python:如何使用plotly制作着色区域或交替背景色?

正如问题中所建议的,一个可能的解决方案可能存在于vspan函数中。然而,使用hspan为y轴添加多个阴影区域似乎比使用vspan和x轴更容易。后者需要更多的调整。更多细节可以在我建议的解决方案后找到。在

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

绘图:

片段:### 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':'-01-11','x1':'-02-22','color':'rgba(30,30,30,0.3)','fill':True,'opacity':.4})

### ANSWER ###

xStart = ['-01-11', '-02-08', '-03-08', '-04-05']

xStop = ['-01-25', '-02-22', '-03-22', '-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']:

^{pr2}$

我的函数只需获取字典,生成若干副本,根据函数参数编辑这些副本,然后用函数中的新元组替换原始元组。在

挑战:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。