Python 使用多条线从pandas dataframe绘制折线图
这是我的输入数据帧:Python 使用多条线从pandas dataframe绘制折线图,python,python-3.x,pandas,dataframe,plotly,Python,Python 3.x,Pandas,Dataframe,Plotly,这是我的输入数据帧: labels percentile_5 percentile_25 median percentile_75 percentile_98 0 0 21 25 27 30 34 1 1 49 52 56 61 71 2 2
labels percentile_5 percentile_25 median percentile_75 percentile_98
0 0 21 25 27 30 34
1 1 49 52 56 61 71
2 2 34 36 39 43 48
我已尝试使用以下代码进行转换
:
t = df.T.reset_index()
t.columns = t.iloc[0]
t = t.iloc[1:]
输出:
labels 0 1 2
1 percentile_5 21 49 34
2 percentile_25 25 52 36
3 median 27 56 39
4 percentile_75 30 61 43
5 percentile_98 34 71 48
使用这个,我可以创建只有一条线的折线图
fig = px.line(t, x="labels", y=0)
fig.show()
我试着这样画,x轴=标签,图例=0,1,2
我需要在dataframe或中做哪些更改
有没有什么简单的方法可以使用第一个数据帧进行绘图?如果我理解正确,您不必做任何更改。只需运行:
fig = px.line(df, x='labels', y = df.columns)
这应该是您正在寻找的,因为您已经指定了x=labels
和legend=0,1,2
完整代码
import pandas as pd
import plotly.express as px
df = pd.DataFrame({'labels': {1: 'percentile_5',
2: 'percentile_25',
3: 'median',
4: 'percentile_75',
5: 'percentile_98'},
'0': {1: 21, 2: 25, 3: 27, 4: 30, 5: 34},
'1': {1: 49, 2: 52, 3: 56, 4: 61, 5: 71},
'2': {1: 34, 2: 36, 3: 39, 4: 43, 5: 48}})
fig = px.line(df, x='labels', y = df.columns)
fig.show()