Search code examples
pythondataframeerrorbar

How to create an error bar plot with standard deviation from two data-frames with the same grouping variable?


I'm working with a dataset where I have to build an error bar plot similar to this.

enter image description here

I have two data frames, one with the means of the variables and the other with the standard deviations:

df_media = media_grupos[["LDH1", "LDH2", "CPK1", "CPK2", "AST1", "AST2", "FAL1", "FAL2", "PPT1", "PPT2", "GlutamatoDesh1", "GlutamatoDesh2", "Albumina1", "Albumina2"]]
df_desv = desv_grupos[["LDH1", "LDH2", "CPK1", "CPK2", "AST1", "AST2", "FAL1", "FAL2", "PPT1", "PPT2", "GlutamatoDesh1", "GlutamatoDesh2", "Albumina1", "Albumina2"]]

Each data frame is grouped by two groups 1 and 2, related to the type of feeding in terms of cereal and LDH1, LDH2, etc... are the data before and after the treatment. Data frame for the means of the variable is the following

enter image description here

And the data frame for the standard deviations is:

enter image description here

As the feeding groups are the same I do not know how to build an error bar plot with the standard deviation that shows in the x-axis the feeding group and in the bars the LDH1 vs LDH2, for example.


Solution

  • With pandas you can just do :

    df_media.plot.bar(yerr=df_desv, y=["LDH1", "LDH2"])
    

    But if you can use other packages, with plotly for example it is possible to have something more interactive :

    import plotly.graph_objects as go
    
    fig = go.Figure()
    for name in df_media.columns:
        fig.add_trace(
            go.Bar(
                x=["Group 1", "Group 2"],
                y=df_media[name],
                name=name,
                error_y=dict(type="data", array=df_desv[name]),
            )
        )
    fig.show()