除了您对情节的积极评论之外,这里是一个如何为数据集实现多轴的示例。
该代码比看起来简单得多。由于我格式化的方式,代码显得“冗长”dict
s 以便于阅读。
关键要素是:
- 添加累计总和
time
柱子 (time_c
)用于xaxis2
.
- 添加一条隐藏的轨迹来对齐
xaxis
,以及您的时间数据xaxis2
。如果没有隐藏迹线,则两个轴要么不出现,要么出现但未对齐,因为只绘制了一条迹线。
(更新)示例代码:
以下代码已更新,以解决 OP 在使用更大(70k 行)数据集时遇到的问题。
关键的变化是更新layout['xaxis']
and layout['xaxis2']
包含的字典'type': 'category'
, 'nticks'
并定义'range'
keys.
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')
示例图(原始数据集):
为了代码简单起见,我故意省略了任何额外的显示配置。然而,参考顶层情节文档 https://plotly.com/python/,图表是highly可配置。
示例图(新数据集):
该图使用来自其他答案的(更大,70k 行)合成数据集。