I am relatively new to Pandas and Plotly. I will pose my question directly with a MWE of what I want to do:
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()
This code is not doing what I want. The mean_df
dataframe looks like this:
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
I want to plot x_mean
vs y_mean
using plotly.express
. I am not sure how to do this when there are sub-columns in the data frameβ¦
After some research I have found that mean_df.columns = [' '.join(col).strip() for col in mean_df.columns.values]
converts the previous dataframe into
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
so now I can just do
fig = px.scatter(
mean_df,
x = 'x mean',
y = 'y mean',
error_y = 'y std',
)
to obtain the desired result. However, despite this does exactly what I want to do, it does not feel like the way to goβ¦
How can I tell plotly.express
to use the column ('x','mean')
for the x axis and ('y','mean')
for the y axis with the original mean_df
dataframe?