python-3.xplotly-dash

How to Reduce the margin around the map in a Dash App


I am trying make a simple Dash app with a table and a map side by side. I am having trouble adjusting the map area occupy the full div space.

This is the code snippet.

import dash
from dash import dcc, html
from dash import dash_table
import plotly.express as px
import pandas as pd

# Sample DataFrame for the DataTable
data = {
    'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'],
    'Population': [8419600, 3980400, 2716000, 2328000, 1690000],
    'Latitude': [40.7128, 34.0522, 41.8781, 29.7604, 33.4484],
    'Longitude': [-74.0060, -118.2437, -87.6298, -95.3698, -112.0740]
}
df = pd.DataFrame(data)
df2 = px.data.gapminder()

# Create a map using Plotly Express
fig = px.scatter_mapbox(
    df,
    lat='Latitude',
    lon='Longitude',
    hover_name='City',
    size='Population',
    zoom=3,
    center={"lat": 37.0902, "lon": -95.7129},  # Centered on the USA
    mapbox_style="open-street-map"
)

# Initialize the Dash app
app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div([
        # Data Table
        dash_table.DataTable(
            id='data-table',
            columns=[{"name": i, "id": i} for i in df2.columns],
            data=df2.to_dict('records'),
            style_table={'height': '400px', 'overflowY': 'auto'},
            style_cell={'textAlign': 'left'},
        )
    ], style={'width': '50%', 'display': 'inline-block', 'vertical-align': 'top'}),

    html.Div([
        # Map
        dcc.Graph(
            id='map',
            figure=fig,
            style={'width': '100%', 'height': '100%', 'padding': '0px', 'border': '1px solid black',
                  'margin': '0px'}
        )
    ], style={
        'width': '50%',
        'display': 'inline-block',
        'padding': '0px',  # No padding
        'height': '400px',  # Same height as the data table
        'margin': '0px'
    })
])

if __name__ == '__main__':
    app.run_server(debug=True)

The output looks like this. Despite setting the margin, padding and border to 0, still there is so much space left around the map.

Please help.

enter image description here


Solution

  • The remaining space actually corresponds to the figure margins, which you can override by updating the figure layout :

    fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))