Unable to center-align column header text in dash table

I am unable to center align column header text. Anybody else experiencing this problem? I’m using the latest version off Dash .

from dash import Dash, dash_table
import pandas as pd
from collections import OrderedDict

data = OrderedDict(
    [
        ("Date", ["2015-01-01", "2015-10-24", "2016-05-10", "2017-01-10", "2018-05-10", "2018-08-15"]),
        ("Region", ["Montreal", "Toronto", "New York City", "Miami", "San Francisco", "London"]),
        ("Temperature", [1, -20, 3.512, 4, 10423, -441.2]),
        ("Humidity", [10, 20, 30, 40, 50, 60]),
        ("Pressure", [2, 10924, 3912, -10, 3591.2, 15]),
    ]
)

df = pd.DataFrame(data)

app = Dash(__name__)

app.layout = dash_table.DataTable(
    data=df.to_dict('records'),
    columns=[{'id': c, 'name': c} for c in df.columns],
    style_data={'border': '1px solid blue'},
    style_header={
        'border': '1px solid pink',
        'textAlign': 'center'},
    style_cell={
        'textAlign': 'center'
    }
)

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

Hi flyingcujo

Try with styles.

https://dash.plotly.com/datatable/style

from dash import Dash, html
import pandas as pd
from collections import OrderedDict

data = OrderedDict(
    [
        ("Date", ["2015-01-01", "2015-10-24", "2016-05-10", "2017-01-10", "2018-05-10", "2018-08-15"]),
        ("Region", ["Montreal", "Toronto", "New York City", "Miami", "San Francisco", "London"]),
        ("Temperature", [1, -20, 3.512, 4, 10423, -441.2]),
        ("Humidity", [10, 20, 30, 40, 50, 60]),
        ("Pressure", [2, 10924, 3912, -10, 3591.2, 15]),
    ]
)

df = pd.DataFrame(data)

def generate_table(dataframe, max_rows=1000):
    return html.Table([
        html.Thead(
            html.Tr([html.Th(col) for col in dataframe.columns])
        ),
        html.Tbody([
            html.Tr([
                html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
    ], style={'marginLeft': 'auto', 'marginRight': 'auto'})

app = Dash(__name__)

app.layout = html.Div([
    html.H1(id='Title1',children='Example Table with styles',style={'text-align':'center'}),
    generate_table(df)
])


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

image

While this does provide an alternate solution, I suspect there is a bug in Dash’s DataTable application (or lack thereof) of style_header. If style_cell will center align text, so should style_header.

flyingcujo

I think you’re right. The bug has been reported.

https://github.com/plotly/dash/issues/1914

Thanks! For some reason I didn’t see this bug submission prior to starting this thread!

1 Like

Hi flyingcujo

bug solved on the new version of plotly v2.2.0

https://github.com/plotly/dash/releases/tag/v2.2.0

  • Restores style_header text alignment in Dash Table #1914
1 Like

Sweet! Thanks @SamuelVT for the additional update!