Jim Chen
Jim Chen

Reputation: 3749

Print table in plotly dash with multiple lines in one cell

Currently I have a pandas dataframe :

df = pd.DataFrame({
    "date": ["20210613", "20210614", "20210615"],
    "user": ["A\nB", "C", "D"],
    "machine" : [1, 0, 3]
})

enter image description here

I wonder if there is any way to print this table to my dash app like this:

enter image description here

no matter using pure text print into dcc.Textarea or dash_table.DataTable are fine.

Currently I still can not figure out a good way to achieve this, many thanks.

Upvotes: 1

Views: 3649

Answers (1)

bas
bas

Reputation: 15462

You can do it in a DataTable by using the style_cell property on the DataTable like this:

import dash
import dash_table
import pandas as pd

df = pd.DataFrame(
    {
        "date": ["20210613", "20210614", "20210615"],
        "user": ["A\nB", "C", "D"],
        "machine": [1, 0, 3],
    }
)

app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id="table",
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict("records"),
    style_cell={"whiteSpace": "pre-line"},
)

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

You can make the datatable cells break when they encounter the \n character by setting the white-space CSS attribute for the cells in the table

I found this answer on this thread

Upvotes: 8

Related Questions