Search code examples
pythonplotlyplotly-dashplotly-python

Plotly Set Trace Position in a Figure


I'm a newbie in Plotly and I was wondering if there is a way to specify where a new trace needs to be centered within the Figure object.

Just to be more clear, this is an example:

import plotly.express as px
import plotly.graph_objects as go

df = pd.DataFrame(something)

fig = go.Figure()
for i in [40,45,50]:
    fig.add_shape(
        go.layout.Shape(
            type='line',
            xref='x',
            yref='y',
            x0=line_data[i]["min"],
            y0=i,
            x1=line_data[i]["max"],
            y1=i,
        ),
    )
    
fig.add_trace(
    go.Scatter(
        x=df.ColA.values, 
        y=df.ColB.values,
        mode='markers',
    )
)

This is the resultenter image description here

My goal is to build an histogram of the points in each horizontal line.

I don't know if there is a better and faster way, but my idea was to add more traces, each one with an histogram, and then center those traces in each line. Is there a way to do it? Maybe some position parameter for a trace, like (xcenter=7.5, ycenter=50)?

My ideal result should be:enter image description here


Solution

    • you describe histogram / frequency multiple observed items
    • have mapped these to y-axis using base
    import numpy as np
    import plotly.graph_objects as go
    df = pd.DataFrame({40:np.random.normal(5,2, 200).astype(int),50:np.random.normal(6,2, 200).astype(int),60:np.random.normal(6.5,2, 200).astype(int)})
    
    # change to frequency of observed values
    df2 = df[40].value_counts().to_frame().join(df[50].value_counts(), how="outer").join(df[60].value_counts(), how="outer")
    
    # plot bar of frequency,  setting base based on observation
    fig = go.Figure([go.Bar(x=df2.index, y=df2[c]/len(df2), base=c, name=c) for c in df2.columns])
    fig.update_layout(barmode="overlay")
    

    enter image description here