Python:如何为单个跟踪添加辅助x轴?

2024-06-02 04:37:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框(见下面的“测试数据”部分),我想添加一个辅助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)")

输出图:

enter image description here

这张大桌子看起来怎么样

enter image description here


Tags: dfdatarawtimeplotline时间ax
2条回答

除了您对plotly的积极评价之外,下面是一个如何为数据集实现多X轴的示例

代码比看起来简单得多。由于我对dict进行了格式化以便于阅读,因此代码看起来“冗长”

关键要素包括:

  • 添加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 docs,这些图是高度可配置的

enter image description here

示例图(新数据集):

此图使用来自另一个答案的(较大的70k行)综合数据集

enter image description here

尽管通常不鼓励这样做,但我将发布另一个答案来解决新的数据集,因为前面的答案在给定原始数据集的情况下是有效的

此示例与辅助x轴的原始请求不同,原因有两个:

  1. 由于(新)数据集的大小,绘制“隐藏”数据层不是最优的
  2. 要使次x轴正确显示,必须绘制第二个趋势,鉴于前面的原因,这不再是一个选项

因此,采用了不同的方法-x轴的组合标记。与打印两个轴不同,单个x轴具有两个必需的标签

示例图:

注:这(显然)是综合数据,以获得更新问题中的行数(70k)

enter image description here

示例代码:

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')

相关问题 更多 >