Python:如何为单个轨迹添加辅助X轴? [英] Python: How to add a secondary x axis for a single trace?

查看:44
本文介绍了Python:如何为单个轨迹添加辅助X轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame(请参见下面的测试数据"部分),我想添加一个辅助x轴(在顶部).但是此轴必须为0到38.24(ms).这是时间"列中所有值的总和.它表示执行4个推理所需的总时间.到目前为止,我没有尝试过'twinx()'.

我该怎么做?有可能还是我缺少信息?

测试数据:

  raw_data = {'时间':[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 

  ## Time(毫秒)列中所有值的总和(df_m.iloc [:, 0] .sum())##每次推断的时间(毫秒)ax = df_m.plot(种类='line',y ='MemUsed',grid = True)ax.set_xlabel(推断数")ax.set_ylabel("MemUsed(MB)") 

我尝试过的事情:

  ax = df_m.plot(种类='line',y ='MemUsed',grid = True)df_m.plot(kind ='line',ax = ax.twinx(),secondary_x = range(0,39))ax.set_xlabel(推断数")ax.set_ylabel("MemUsed(MB)") 

输出图:

大桌子的样子

解决方案

在关于积算的正面评论之后,这是一个如何为数据集实现多轴的示例.

代码比看起来简单得多.由于我格式化 dict s以便于阅读的方式,代码显得冗长".

关键元素是:

  • 添加 time 列的累积总和( time_c ),以便在 xaxis2 上使用.
  • 添加一条与 xaxis 对齐的隐藏轨迹,以及与 xaxis2 对齐的时间数据.如果没有隐藏的迹线,由于仅绘制了一条迹线,两个轴都不会出现,或者它们都出现但未对齐.

(已更新)示例代码:

下面的代码已更新,以解决OP在具有较大(70k行)数据集的情况下遇到的问题.

关键更改是对 layout ['xaxis'] layout ['xaxis2'] 字典的更新,其中包含'type':'category''nticks'和已定义的'range'键.

 将pandas导入为pd从plotly.offline导入图#创建数据集.raw_data = {'时间':[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)#绘图代码.数据= []布局= {'margin':{'t':105},'title':{'text':'示例显示辅助X轴的使用','y':0.97}}#为xaxis创建(隐藏)跟踪.data.append({'x':df.index,'y':df ['memused'],'showlegend':错误,'模式':'标记','标记':{'size':0.001}})#创建xaxis2的可见迹线.data.append({'x':df ['time_c'],'y':df ['memused'],'xaxis':'x2','name':'Inference'})#配置图形布局.nticks = int(df.shape [0]////(df.shape [0] * 0.05))layout ['xaxis'] = {'title':'推论数','nticks':nticks,'范围':[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':'已使用的内存(MB)'}图= {'数据':数据,'布局':布局}情节(fig,filename ='/path/to/graph.html') 

示例图(原始数据集):

为了简化代码,我特意省略了任何其他外观配置.但是,参考顶层

示例图(新数据集):

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

I have a DataFrame (see 'Test Data' section below) and I would like to add a secondary x axis (at the top). But this axis has to be from 0 to 38.24(ms). This is the sum of all values in column 'Time'. It expresses the total time that the 4 inferences took to execute. So far I have tried 'twinx()' without success.

How can I do that? Is it possible or am I lacking information?

Test Data:

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

What I have tried:

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

Output Graph:

How does the big table look like

解决方案

Further to your positive comment regarding plotly, here is an example of how to achieve a multi-xaxis for your dataset.

The code is a lot simpler than it looks. The code appears 'lengthy' due to the way I've formatted the dicts for easier reading.

The key elements are:

  • Adding a cumulative sum of the time column (time_c) for use on xaxis2.
  • Adding a hidden trace which aligns to xaxis, and your time data which aligns to xaxis2. Without the hidden trace, either both axes do not appear, or they appear but are not aligned, due to only one trace being plotted.

(Updated) Sample Code:

The following code has been updated to address the issue OP was having with a larger (70k row) dataset.

The key change is an update to the layout['xaxis'] and layout['xaxis2'] dicts to contain 'type': 'category', 'nticks' and defined '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')

Example Graph (original dataset):

I've intentionally left out any additional appear configuration for code simplicity. However, referring to the top level plotly docs, the graphs are highly configurable.

Example Graph (new dataset):

This graph uses the (larger, 70k row) synthesised dataset from the other answer.

这篇关于Python:如何为单个轨迹添加辅助X轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆