【发布时间】:2021-12-12 01:18:24
【问题描述】:
我对 Pandas 和 Plotly 比较陌生。我将直接向 MWE 提出我想要做什么的问题:
import pandas
import plotly.express as px
df = pandas.DataFrame(
{
'n': [1,1,1,1,2,2,2,3,3,3,4,4],
'x': [0,0,0,0,1,1,1,2,2,2,3,3],
'y': [1,2,1,1,2,3,3,3,4,3,4,5],
}
)
mean_df = df.groupby(by=['n']).agg(['mean','std'])
fig = px.scatter(
mean_df,
x = ('x','mean'),
y = ('y','mean'),
error_y = ('y','std'),
)
fig.show()
这段代码没有做我想做的事。 mean_df 数据框如下所示:
x y
mean std mean std
n
1 0 0.0 1.250000 0.500000
2 1 0.0 2.666667 0.577350
3 2 0.0 3.333333 0.577350
4 3 0.0 4.500000 0.707107
我想使用plotly.express 绘制x_mean 与y_mean,误差线在y 中。当数据框中有子列时,我不确定如何执行此操作...
经过一番研究,我发现mean_df.columns = [' '.join(col).strip() for col in mean_df.columns.values] 将之前的数据帧转换为
x mean x std y mean y std
n
1 0 0.0 1.250000 0.500000
2 1 0.0 2.666667 0.577350
3 2 0.0 3.333333 0.577350
4 3 0.0 4.500000 0.707107
所以我现在可以做
fig = px.scatter(
mean_df,
x = 'x mean',
y = 'y mean',
error_y = 'y std',
)
获得想要的结果。然而,尽管这正是我想做的,但感觉不像是要走的路……
【问题讨论】: