Search code examples
pythoncssplotlyplotly-dashdashboard

Dash+plotly+bootstrap help needed, arranging custom headers/labels to graph


I'd like to know how to get 10 headers spaced out evenly over a bootstrap column, the goal is to align them with the bars in my bar graph in the row/column above. I don't even know how to google for this, where should i start?

So it's kind of open ended question, is this something i could easily accomplish with CSS formatting on the headers ?(html.h1()) ? is there a way i can add spacing between headers based on screen size? like px vs. em etc... or should I dive deep into building my graph objects in plotly and making some custom label somehow.

So to re-iterate - the '12345678910' are on a seperate bootstrap row/column below the graph. I want each of the 10 headers to align centered with the 10 bars so i can create a custom data readout.

enter image description here


Solution

  • You can achieve what you're looking for, by adding the below snippet in your assets/style.css:

    .grid {
        display: grid;
        grid-template-columns: repeat(10, 1fr);
        grid-column-gap: 25px;
      }
    
    .alignCards {
        text-align: center;
        max-width: 86%;
        margin: 0px auto;
    }
    .cardBorders {
        border: 1px solid black;
    }
    

    and in your dash element, you need to add the classes you just created:

    html.Div([html.Div(html.H1(n), className="cardBorders") for n in range(10)], 
                     className="grid alignCards")
    

    Below is the full code that you can use to test:

    from dash import Dash, dcc, html, Input, Output
    import random
    import plotly.express as px
    import pandas as pd
    
    df=pd.DataFrame.from_dict([{"x":val, "y":random.random()} for val in range(10)])
    
    
    app = Dash(__name__)
    
    
    app.layout = html.Div(
        [
            dcc.Graph(figure=px.bar(df, x="x", y="y")),
            
            html.Div([html.Div(html.H1(n), className="cardBorders")for n in range(10)], 
                     className="grid alignCards"),
        ]
    )
    
    if __name__ == "__main__":
        app.run_server(debug=True)
    

    PS: Try to limit your container size to a specific width, and once it's done, will become easier to find the correct value to align the bars and the cards

    enter image description here

    I hope it can solve your problem, and if the answer was helpful, please, don't forget to vote up and flag it as the answer!

    Regards,
    Leonardo