亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python:如何為單個跡線添加輔助 x 軸?

Python:如何為單個跡線添加輔助 x 軸?

偶然的你 2023-08-03 17:17:49
我有一個 DataFrame(請參閱下面的“測試數據”部分),我想添加一個輔助 x 軸(在頂部)。但該軸必須在 0 到 38.24(ms) 之間。這是“時間”列中所有值的總和。它表示執行 4 個推理所需的總時間。到目前為止,我已經嘗試過“twinx()”但沒有成功。我怎樣才能做到這一點?有可能嗎還是我缺乏信息?測試數據:raw_data = {'Time': [21.9235, 4.17876, 4.02168, 3.81504, 4.2972],            'TPU': [33.3, 33.3, 33.3, 33.3, 33.3],            'CPU': [32, 32, 32, 32, 32],            'MemUsed': [435.92, 435.90, 436.02, 436.02, 436.19]}df_m=pd.DataFrame(raw_data, columns = ['Time', 'TPU', 'CPU', 'MemUsed'])df_m##Sum of all values in column Time(ms)(df_m.iloc[:, 0].sum())##Time per inference(ms)ax = df_m.plot(kind = 'line', y = 'MemUsed', grid = True)ax.set_xlabel("NUMBER OF INFERENCES")ax.set_ylabel("MemUsed(MB)")我嘗試過的:ax = df_m.plot(kind = 'line', y = 'MemUsed', grid = True)df_m.plot(kind='line', ax=ax.twinx(), secondary_x=range(0, 39))ax.set_xlabel("NUMBER OF INFERENCES")ax.set_ylabel("MemUsed(MB)")輸出圖:大桌子長什么樣子
查看完整描述

2 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

除了您對情節的積極評論之外,這里是一個如何為數據集實現多軸的示例。

該代碼比看起來簡單得多。由于我格式化dicts 以便于閱讀的方式,代碼顯得“冗長”。

關鍵要素是:

  • time添加列 ( )的累積和time_c以供使用xaxis2。

  • 添加與 對齊的隱藏跟蹤xaxis,以及與 對齊的時間數據xaxis2。如果沒有隱藏跡線,則兩個軸要么不出現,要么出現但未對齊,因為只繪制了一條跡線。

(更新)示例代碼:

以下代碼已更新,以解決 OP 在使用更大(70k 行)數據集時遇到的問題。

layout['xaxis']鍵的更改是對和字典的更新,layout['xaxis2']以包含'type': 'category','nticks'和 定義的'range'鍵。

import pandas as pd

from plotly.offline import plot


# Create the dataset.

raw_data = {'time': [21.9235, 4.17876, 4.02168, 3.81504, 4.2972],

            'tpu': [33.3, 33.3, 33.3, 33.3, 33.3],

            'cpu': [32, 32, 32, 32, 32],

            'memused': [435.92, 435.90, 436.02, 436.02, 436.19]}


df = pd.DataFrame(raw_data)

df['time_c'] = df['time'].cumsum().round(2)


# Plotting code.

data = []

layout = {'margin': {'t': 105},

          'title': {'text': 'Example Showing use of Secondary X-Axis', 

                    'y': 0.97}}


# Create a (hidden) trace for the xaxis.

data.append({'x': df.index,

             'y': df['memused'],

             'showlegend': False,

             'mode': 'markers', 

             'marker': {'size': 0.001}})

# Create the visible trace for xaxis2.

data.append({'x': df['time_c'],

             'y': df['memused'],

             'xaxis': 'x2',

             'name': 'Inference'})


# Configure graph layout.

nticks = int(df.shape[0] // (df.shape[0] * 0.05))

layout['xaxis'] = {'title': 'Number of Inferences',

                   'nticks': nticks,

                   'range': [df.index.min(), df.index.max()],

                   'tickangle': 45,

                   'type': 'category'}

layout['xaxis2'] = {'title': 'Time(ms)', 

                    'nticks': nticks,

                    'overlaying': 'x1', 

                    'range': [df['time_c'].min(), df['time_c'].max()],

                    'side': 'top', 

                    'tickangle': 45,

                    'type': 'category'}

layout['yaxis'] = {'title': 'Memory Used (MB)'}


fig = {'data': data, 'layout': layout}

plot(fig, filename='/path/to/graph.html')

示例圖(原始數據集):

為了代碼簡單起見,我故意省略了任何額外的顯示配置。然而,參考頂級的plotly 文檔,這些圖表是高度可配置的。

https://img1.sycdn.imooc.com//64cb70fb0001058d08580436.jpg

示例圖(新數據集):

該圖使用來自其他答案的(更大,70k 行)合成數據集。

https://img1.sycdn.imooc.com//64cb710800016b1908400451.jpg

查看完整回答
反對 回復 2023-08-03
?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

盡管通常不鼓勵,但我將發布另一個答案來解決新數據集,因為前面的答案在給定原始數據集的情況下有效。

此示例與輔助 x 軸的原始請求不同,原因有兩個:

  1. 由于(新)數據集的大小,繪制“隱藏”數據層并不是最佳選擇。

  2. 為了使輔助 x 軸正確顯示,必須繪制第二個趨勢,并且考慮到之前的原因,這不再是一個選項。

因此,采取了不同的方法——x軸的組合標記。單個 x 軸沒有繪制兩個軸,而是具有兩個所需的標簽。

示例圖:

注意:這(顯然)是合成數據,以便達到更新問題中的行數 (70k)。

https://img1.sycdn.imooc.com//64cb71180001515308120436.jpg

示例代碼:

import numpy as np

import pandas as pd

from plotly.offline import plot


# Synthesised dataset. (This code can be ignored.)

np.random.seed(0)

a = np.random.exponential(size=70000)*4

t = pd.Series(a).rolling(window=2000, min_periods=50).mean().to_numpy()

r = np.arange(70000).astype(str)

m = t*100


df = pd.DataFrame({'run': r, 

                   'time': t,

                   'memused': m}).dropna()


# Add cumulative time column.

df['time_c'] = df['time'].cumsum().round(1)



# --- Graphing code starts here ---


def create_labels(x):

    """Function to create xaxis labels."""

    return f"({x['run']}): {x['time_c']}"


# Create xaxis labels.

df['xaxis'] = df.apply(create_labels, axis=1)


# Create the graph.

data = []

layout = {'title': 'Combined X-Axis Labeling'}

data.append({'x': df['xaxis'], 

             'y': df['memused']})


layout['xaxis'] = {'title': '(Inference): Cumulative Time (ms)', 

                   'type': 'category', 

                   'nticks': df.shape[0] // 3500,

                   'tickangle': 45}

layout['yaxis'] = {'title': 'Memory Used (MB)'}



fig = {'data': data, 'layout': layout}

plot(fig, filename='/path/to/graph.html')


查看完整回答
反對 回復 2023-08-03
  • 2 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號