簡體   English   中英

Plotly:使用循環添加跟蹤

[英]Plotly: Add traces using a loop

我只是學習 Plotly,我正在努力使我的 Python 代碼更好。 這是我的數據框: 在此處輸入圖片說明

為了形象化,這是我的代碼,但我認為它可以用 For 循環來完成:

fig = go.Figure()

fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,0], mode ='lines', name = 'Australian Capital Territory'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,1], mode ='lines', name = 'New South Wales'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,2], mode ='lines', name = 'Northern Territory'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,3], mode ='lines', name = 'Queensland'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,4], mode ='lines', name = 'South Australia'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,5], mode ='lines', name = 'Tasmania'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,6], mode ='lines', name = 'Victoria'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,7], mode ='lines', name = 'Western Australia'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,8], mode ='lines', name = 'New Zealand'))

annotations = []

annotations.append(dict(xref='paper', yref='paper', x=0.0, y=1.05,
                              xanchor='left', yanchor='bottom',
                              text="Covid 19 Death Cases between Australian' states vs New Zealand",
                              font=dict(family='Arial',
                                        size=18,
                                        color='rgb(37,37,37)'),
                              showarrow=False))

fig.update_layout(legend=dict(y=0.5, traceorder='reversed', font_size=16), 
                  plot_bgcolor='white',
                  annotations=annotations,
                  xaxis_title="Date",
                  yaxis_title="Number of Death"
                 )

fig.show()

我正在嘗試對這部分使用 For 循環:

fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,0], mode ='lines', name = 'Australian Capital Territory'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,1], mode ='lines', name = 'New South Wales'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,2], mode ='lines', name = 'Northern Territory'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,3], mode ='lines', name = 'Queensland'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,4], mode ='lines', name = 'South Australia'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,5], mode ='lines', name = 'Tasmania'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,6], mode ='lines', name = 'Victoria'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,7], mode ='lines', name = 'Western Australia'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,8], mode ='lines', name = 'New Zealand'))

關於如何為此使用 For 循環的任何想法,將不勝感激。 這是 Plotly 的一個例子:

import plotly.graph_objects as go
import numpy as np

title = 'Main Source for News'
labels = ['Television', 'Newspaper', 'Internet', 'Radio']
colors = ['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)']

mode_size = [8, 8, 12, 8]
line_size = [2, 2, 4, 2]

x_data = np.vstack((np.arange(2001, 2014),)*4)

y_data = np.array([
    [74, 82, 80, 74, 73, 72, 74, 70, 70, 66, 66, 69],
    [45, 42, 50, 46, 36, 36, 34, 35, 32, 31, 31, 28],
    [13, 14, 20, 24, 20, 24, 24, 40, 35, 41, 43, 50],
    [18, 21, 18, 21, 16, 14, 13, 18, 17, 16, 19, 23],
])

fig = go.Figure()

for i in range(0, 4):
    fig.add_trace(go.Scatter(x=x_data[i], y=y_data[i], mode='lines',
        name=labels[i],
        line=dict(color=colors[i], width=line_size[i]),
        connectgaps=True,
    ))

    # endpoints
    fig.add_trace(go.Scatter(
        x=[x_data[i][0], x_data[i][-1]],
        y=[y_data[i][0], y_data[i][-1]],
        mode='markers',
        marker=dict(color=colors[i], size=mode_size[i])
    ))

fig.update_layout(
    xaxis=dict(
        showline=True,
        showgrid=False,
        showticklabels=True,
        linecolor='rgb(204, 204, 204)',
        linewidth=2,
        ticks='outside',
        tickfont=dict(
            family='Arial',
            size=12,
            color='rgb(82, 82, 82)',
        ),
    ),
    yaxis=dict(
        showgrid=False,
        zeroline=False,
        showline=False,
        showticklabels=False,
    ),
    autosize=False,
    margin=dict(
        autoexpand=False,
        l=100,
        r=20,
        t=110,
    ),
    showlegend=False,
    plot_bgcolor='white'
)

annotations = []

# Adding labels
for y_trace, label, color in zip(y_data, labels, colors):
    # labeling the left_side of the plot
    annotations.append(dict(xref='paper', x=0.05, y=y_trace[0],
                                  xanchor='right', yanchor='middle',
                                  text=label + ' {}%'.format(y_trace[0]),
                                  font=dict(family='Arial',
                                            size=16),
                                  showarrow=False))
    # labeling the right_side of the plot
    annotations.append(dict(xref='paper', x=0.95, y=y_trace[11],
                                  xanchor='left', yanchor='middle',
                                  text='{}%'.format(y_trace[11]),
                                  font=dict(family='Arial',
                                            size=16),
                                  showarrow=False))
# Title
annotations.append(dict(xref='paper', yref='paper', x=0.0, y=1.05,
                              xanchor='left', yanchor='bottom',
                              text='Main Source for News',
                              font=dict(family='Arial',
                                        size=30,
                                        color='rgb(37,37,37)'),
                              showarrow=False))
# Source
annotations.append(dict(xref='paper', yref='paper', x=0.5, y=-0.1,
                              xanchor='center', yanchor='top',
                              text='Source: PewResearch Center & ' +
                                   'Storytelling with data',
                              font=dict(family='Arial',
                                        size=12,
                                        color='rgb(150,150,150)'),
                              showarrow=False))

fig.update_layout(annotations=annotations)

fig.show()

這是您在for循環中創建所有跟蹤的行:

for idx, col in enumerate(anz_d_df.columns, 0):
    fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,idx], mode ='lines', name = col))

解釋:

此循環使用enumerate函數,該函數接受一個可迭代對象(在本例中為列名列表)並返回(index, string)tuple 例如:

(0, 'Australian Capital Territory')
(1, 'New South Wales')
...
(8, 'New Zealand')

然后,這些值被傳遞到每個add_trace()調用中。

上下文代碼:

下面是用於創建數據集以復制您的數據集(盡管是零 DataFrame )的代碼,以及用於創建跟蹤的循環。

# Build dataset
cols = ['Australian Capital Territory',
        'New South Wales',
        'Northern Territory',
        'Queensland',
        'South Australia',
        'Tasmania',
        'Victoria',
        'Western Australia',
        'New Zealand']
index = pd.date_range(start='2020-01-22', periods=10)

# Create working DataFrame.
anz_d_df = pd.DataFrame(0,columns=cols, index=index)

# Add all traces.
for idx, col in enumerate(anz_d_df.columns, 0):
    fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,idx], mode ='lines', name = col))

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM