Rafael
Rafael

Reputation: 3196

plotly round decimals and add commas in figure_factory tables

I've created a table in pandas and would like to display it with plotly. However I want to do my number formatting with plotly instead of pandas.

How can I do this?

import pandas as pd
import numpy as np
import plotly.figure_factory as ff

df = pd.DataFrame({'num': [1, 2, 3],
                   'sqrt': pd.Series([1, 2, 3]) ** 0.5,
                  'exp': np.exp2(pd.Series([10, 11, 12]))})
fig = ff.create_table(df)
fig.show()

This shows current format

What can I change to get desired format

Upvotes: 1

Views: 674

Answers (1)

r-beginners
r-beginners

Reputation: 35205

I tried to update the annotations for figure_factory because the table contents are text, but an error occurred, so I used a graph object. The format can be set in the cells of the graph object, so specify it there. However, to change the display format for each individual cell, you need to list the appropriate format for each individual cell. I also changed the row colors, etc. to match the decorations in figure_factory.

import plotly.graph_objects as go
import numpy as np

fmt = np.array(['.2f' if len(str(v)) == 18 else None for v in df.values.T.flatten()]).reshape(3,3)

headerColor = 'midnightblue'
rowEvenColor = 'ghostwhite'
rowOddColor = 'whitesmoke'

fig = go.Figure(data=[go.Table(
    header=dict(
        values=[['<b>{}</b>'.format(h)] for h in df.columns],
        fill_color=headerColor,
        line_color='darkslategray',
        font=dict(color='white', size=12),
    ),
    cells=dict(
        values=df.values.T,
        format=fmt,
        fill_color = [[rowOddColor,rowEvenColor,rowOddColor]*3],
        height=25
    ))
                     ])
fig.show()

enter image description here

Upvotes: 2

Related Questions