簡體   English   中英

yaxis 可以在 plotly 中動態添加到 graph_objects 布局中嗎?

[英]Can yaxis be dynamically added into an graph_objects Layout in plotly?

在我現在正在接受的實際培訓中,有一個 Python 腳本可以讀取 CSV 文件並針對該文件的選定列進行繪圖。 然而,標題的選擇是硬編碼的,所以如果有人想使用腳本,他們必須操縱代碼。 我的任務是使其全部動態化,例如腳本的用戶可以通過控制台( argparse )選擇任意數量的列,腳本會自動創建跟蹤,創建布局,將兩者添加到圖形並將其導出到 html 文件中.

除了布局部分,我已經設法完成了所有這些。 在腳本的當前(硬編碼)狀態中,有以下參數傳遞給graph_objects.Layout函數:

 layout = go.Layout(title=inFile,
                       plot_bgcolor='rgb(230, 230,230)', showlegend=True,
                       yaxis=dict(
                           title=df.columns[y1graph] # Note: 'ygraph' contains the index of the column
                       ),
                       yaxis2=dict(
                            title=df.columns[y2graph],
                            side='right',
                            overlaying='y'
                       ),
                       yaxis3=dict(
                            title=df.columns[y3graph],
                            side='right',
                            overlaying='y'
                       )
                    )

不幸的是,我都沒有找到一種方法來使所有這些都動態化,以便根據所選列的數量添加“yaxis”參數。 我也沒有找到一種方法來為圖表添加標題,使它們相互重疊並像go.Layout一樣將它們放在右側。 當然,有一種方法可以用 plotly express 添加標題,但在overlayingside參數方面,它對我來說並沒有做同樣的事情。

有任何想法嗎?

請注意:這是我在 stackoverflow 上的第一個問題,所以如果我做錯了什么,請指教! 另外,如果我遺漏了關鍵信息,請告訴我。

  • 模擬一個 CSV,一個有 20 列的數據框
  • 模擬用戶選擇要繪制的列(隨機抽樣 20 列中的 4 列)
  • 構建圖形,為每個軌跡分配不同的yaxis
  • 最后根據問題,動態配置 y 軸
import numpy as np
import plotly.express as px
import pandas as pd

# simulate a CSV, 20 columns...
df = pd.DataFrame(
    {
        chr(ord("A") + i): np.random.uniform(miny, miny + 200, 30)
        for i, miny in zip(range(20), np.random.randint(30, 3000, 20))
    }
)

# simulate user passing columns to plot...
cols = pd.Series(df.columns).sample(4).tolist()

# build figure with each trace using it's own yaxis
fig = px.line(df, y=cols).for_each_trace(
    lambda t: t.update(yaxis=f"y{cols.index(t.name)+1 if cols.index(t.name)>0 else ''}")
).update_layout(yaxis={"title":cols[0]})

# dynamically update yaxes...
fig.update_layout(
    {
        t.yaxis.replace("y", "yaxis"): {
            "title": t.name,
            "overlaying": "y",
            "side": "right",
            "position":1-(i/15)
        }
        for i,t in enumerate(fig.data)
        if t.yaxis != "y"
    }
).update_layout(xaxis={"domain":[0,1-(len(cols)*.05)]}) # give some space for additional yaxes

在此處輸入圖片說明

暫無
暫無

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

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