第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Plotly:如何使用 For 循環(huán)突出顯示具有矩形形狀的 Pandas 時(shí)間序列中的某些時(shí)期?

Plotly:如何使用 For 循環(huán)突出顯示具有矩形形狀的 Pandas 時(shí)間序列中的某些時(shí)期?

九州編程 2023-10-06 19:30:36
我試圖在 Plotly 中突出顯示時(shí)間段。我似乎最好的方法是使用 Shapes,就像這樣,但在現(xiàn)實(shí)世界中,您不想像示例 url 中那樣手動(dòng)添加每個(gè)形狀。我認(rèn)為 for 循環(huán)是最好的解決方案,但歡迎其他(計(jì)算量較小的)建議。我的腳本如下所示:np.random.seed(12345)rows = 20x = pd.Series(np.random.randn(rows),index=pd.date_range('1/1/2020', periods=rows)).cumsum()df = pd.DataFrame({"index": x})# add column showing what to shadedf["signal"] = df['index'] < 5# plot index and highlight periods with Rectangle Shapes in Plotlyfig = px.line(df, x=df.index, y="index")for row in df.iterrows():    if df['signal'] == False:        ply_shapes['shape_' + str(i)]=go.layout.Shape(type="rect",                                                            x0=df.dato[i-1],                                                            y0=0,                                                            x1=df.dato[i],                                                            y1=2000,                                                            opacity=0.5,                                                            layer="below"                                                        )lst_shapes=list(ply_shapes.values())fig.update_layout(shapes=lst_shapes)fig.show()但這返回:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
查看完整描述

1 回答

?
臨摹微笑

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊

您的代碼片段無法工作的原因有多種。

1. iterrows()返回一個(gè)迭代器,其中包含每行的索引和每行中的數(shù)據(jù)作為seres。要使用它,您必須替換

for row in df.iterrows():
    if df['signal'] == False:

與(例如):

for row in df.iterrows():
    if row[1]['signal'] == True:

引發(fā)您的錯(cuò)誤是因?yàn)槟峙淞艘幌盗?em>with而True, False不是if df['signal'] == False:if row[1]['signal'將做的那樣分配單個(gè)值。

但僅僅解決這個(gè)問題并不能幫助你。至少不在您的代碼片段的范圍內(nèi),因?yàn)椋?/p>

2. dato您的示例數(shù)據(jù)框中不存在。

類似的問題之前已經(jīng)被問過并回答過。但由于對于聽起來非常不同的問題,解決方案是相似的,因此我決定也為您的用例制定一個(gè)自定義解決方案。


在這兩種情況下,最好的方法在很大程度上取決于您如何在時(shí)間序列中識(shí)別和分配突出顯示的時(shí)間段。以下示例將使用隨機(jī)數(shù)據(jù)并根據(jù)閾值識(shí)別要突出顯示的時(shí)間段。就像你的問題一樣。

我的建議將歸結(jié)為一個(gè)函數(shù),highLights()該函數(shù)將一個(gè)繪圖圖、一個(gè) pandas 系列和一個(gè)閾值作為輸入,以及一些其他細(xì)節(jié)(看看文檔字符串)。

highLights()具有一些示例輸入的函數(shù):

fig = highLights(fig = fig, variable = 'signal', level = 5, mode = 'above',
               fillcolor = 'rgba(200,0,200,0.2)', layer = 'below')

陰謀

https://img1.sycdn.imooc.com//651ff0220001fd1307880381.jpg

完整代碼:

# imports

import numpy as np

import pandas as pd

import plotly.graph_objects as go

import plotly.express as px

import datetime


pd.set_option('display.max_rows', None)


# data sample

cols = ['signal']

nperiods = 200

np.random.seed(123)

df = pd.DataFrame(np.random.randint(-10, 12, size=(nperiods, len(cols))),

                  columns=cols)

datelist = pd.date_range(datetime.datetime(2020, 1, 1).strftime('%Y-%m-%d'),periods=nperiods).tolist()

df['dato'] = datelist 

df = df.set_index(['dato'])

df.index = pd.to_datetime(df.index)

df.iloc[0] = 0

df = df.cumsum().reset_index()


# plotly setup

fig = px.line(df, x='dato', y=df.columns[1:])

fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,255,0.1)')

fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,255,0.1)')



# function to set background color for a

# specified variable and a specified level

def highLights(fig, variable, level, mode, fillcolor, layer):

    """

    Set a specified color as background for given

    levels of a specified variable using a shape.

    

    Keyword arguments:

    ==================

    fig -- plotly figure

    variable -- column name in a pandas dataframe

    level -- int or float

    mode -- set threshold above or below

    fillcolor -- any color type that plotly can handle

    layer -- position of shape in plotly fiugre, like "below"

    

    """

    

    if mode == 'above':

        m = df[variable].gt(level)

    

    if mode == 'below':

        m = df[variable].lt(level)

        

    df1 = df[m].groupby((~m).cumsum())['dato'].agg(['first','last'])


    for index, row in df1.iterrows():

        #print(row['first'], row['last'])

        fig.add_shape(type="rect",

                        xref="x",

                        yref="paper",

                        x0=row['first'],

                        y0=0,

                        x1=row['last'],

                        y1=1,

                        line=dict(color="rgba(0,0,0,0)",width=3,),

                        fillcolor=fillcolor,

                        layer=layer) 

    return(fig)


fig = highLights(fig = fig, variable = 'signal', level = 5, mode = 'above',

               fillcolor = 'rgba(200,0,200,0.2)', layer = 'below')


fig.update_layout(template = 'plotly_dark')


fig.show()



查看完整回答
反對 回復(fù) 2023-10-06
  • 1 回答
  • 0 關(guān)注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號