绘制折线图,不考虑x轴的顺序

2024-09-27 09:37:23 发布

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

我有一个有两列的数据框。机器ID和价值。我将数据框按降序排序(首先是具有高值的机器),并绘制折线图。但是,它仍然显示x轴(MachineID 1到60,而不是首先获取最高值MachineID)

要解决此错误,请将machineID列更改为string,但仍然无法首先获取具有高值的计算机

示例数据帧:

MachineID   Value
    33     6.962754
    16     6.955913
    44     6.722355
    31     6.320854
    1      6.243701
    9      5.894093

霉菌代码:

import plotly.express as px
fig = px.line(data, x="MachineID", y="Values")
fig.show()

上述代码的输出:

enter image description here

所需输出:

首先是具有高值的机器,依此类推


Tags: 数据代码机器id排序错误fig绘制
1条回答
网友
1楼 · 发布于 2024-09-27 09:37:23

如果要使用线图并首先显示具有最高值的机器,则必须:

  • 按最高值对df排序
  • 并告诉plotly使用fig.update_xaxes(type='category')

示例代码:

import pandas as pd
import plotly.express as px
    
data = {
    'MachineID': {0: 33, 1: 16, 2: 44, 3: 31, 4: 1, 5: 9},
    'Value': {0: 6.962754, 1: 6.955913, 2: 6.722355, 
              3: 6.320854, 4: 6.243701, 5: 5.894093},
}
    
df = pd.DataFrame(data)
  
# sort your df on highest value, descending  
df = df.sort_values(by='Value', ascending=False)
    
fig = px.line(df, x='MachineID', y='Value')

# set x-axis as categorical:
fig.update_xaxes(type='category')

结果图:

categorical x-axis line plot, highest value first

您可以在这里的分类轴上找到更多信息:
https://plotly.com/python/categorical-axes/

相关问题 更多 >

    热门问题