Public account: You and the cabin by: Peter Editor: Peter

Visualization artifact Plotly beautification table

Sometimes see a table, without any color modification, always feel shortcomings of the aesthetic effect. In Excel, you can directly set the font color, size, etc., and fill in the cell color. There are two ways to beautify the table output in Plotly:

  • Use the go.table method
  • Use the creat_table method of figure_Factory

Serialized article by Plotly

Import libraries

import pandas as pd
import numpy as np

import plotly_express as px
import plotly.graph_objects as go  # method 1: go.table
import plotly.figure_factory as ff # Method 2: Graphic factory
Copy the code

Go. Table implementation

This method is similar to other charting methods in that it uses the go.Table method directly and then adds data to it

Basic form

Add data in table headers and cells

import plotly.graph_objects as go

fig = go.Figure(data=[go.Table(
    header=dict(values=['Chinese'.'mathematics']),  # table header: in list form

    cells=dict(values=[[100.90.140.123].# Cell add: first column element
                       [105.135.75.95]])) # second column element
                     ])
fig.show()
Copy the code

Personalized table Settings

import plotly.graph_objects as go

fig = go.Figure(data=[go.Table(
    header=dict(values=['Chinese'.'mathematics'].Table header: dictionary form
                line_color="darkslategray".# header line color
                fill_color="lightskyblue".Fill the header color
                align="center"  # text display position 'left', 'center', 'right'
               ), 

    cells=dict(values=[[100.90.140.123].# Cell add: first column element
                       [105.135.75.95]], # second column element
               line_color="darkslategray".# Cell line color
               fill_color="lightcyan".# Cell fill color
               align="center"  # Text display position
              ))])

fig.update_layout(width=600,height=400)

fig.show()
Copy the code

DataFrame is converted to a table

Turn DataFrame data into beautiful tables quickly

# drawing

fig = go.Figure(
    data=[go.Table(
        header=dict(values=list(data.columns),  The table header value is the data column attribute
                    fill_color='paleturquoise'.# Fill color and text position
                    align='left'),
        cells=dict(values=[data. gender,data. age, datA. grade],The value of the cell is the Series value of each column attribute
                   fill_color='lavender',
                   align='left'
                  )
        
    )]
)

fig.show()
Copy the code

Change the size of row and column

Sometimes cell data is too long, we need to adjust the cell size

import plotly.graph_objects as go

values = [["Li Bai tang Dynasty".Du Fu in the Tang Dynasty."Su Shi in song Dynasty"."Wang Anshi song Dynasty"].# first column data
          
          ["The moon before my bed, I suspect it is frost on the ground; Look up at the moon, look down and think of home."."The country is broken in the mountains and rivers, the city spring vegetation deep. Feeling flowers splash tears, hate don't bird startled. The beacon fire even in three months, the letter is worth ten thousand gold. The coquettish hair is shorter, and the lust is too numerous to pin."."Ten years of life and death two boundless, do not think, since unforgettable. Thousands of lonely grave, no words desolate. < BR > Even if meet should not know, dust, temples such as frost. < BR > At night, a deep dream suddenly returned home. Xiao Xuan Window was dressing. Speechless, but tears thousands of lines. "< BR > Expect every year intestines broken place, bright moon night, short pine hill."."Read the past, prosperous competition. Sigh outside the building, sad hate phase continued. Through the ages, he talks of glory and shame. < BR > The six Dynasties with the water, but cold smoke, grass set green. 

To this day, shang women still sing songs from the back court."
]] fig = go.Figure(data=[go.Table( columnorder = [1.2].# Order of column attributes columnwidth = [800.4000].The total size of the cell occupied by the element in the column attribute # header header = dict( values=[["Tang and Song Writers"], ["Representative works"]], # two headers line_color='darkslategray'.# Lines and fill colors fill_color='royalblue', align=['left'.'center'].# position font=dict(color='white', size=12), Table header text color and font size font_size=12, height=40 # height ), # Cell Settings cells = dict( values=values, # data line_color='darkslategray'.# Line color fill=dict(color=['paleturquoise'.'white']), align=['left'.'center'].Display position of two column attribute text font_size=12.# font size height=50)))#fig.update_layout(width=600,height=400) fig.show() Copy the code

Set the table gradient

import plotly.graph_objects as go

import pandas as pd

colors = ['rgb(239, 243, 255)'.The closer the RGB value is to 255, the closer it is to white
          'rgb(189, 215, 231)'.'rgb(107, 174, 214)'.'rgb(59, 130, 189)'.'rgb(9, 81, 156)']

data = {'Year' : [2015.2016.2017.2018.2019].'Color' : colors}

df = pd.DataFrame(data)

print(df)

fig = go.Figure(data=[go.Table(
    # header
  header=dict(
      values=["Color"."<b>YEAR</b>"].# table header name
      line_color='white', 
      fill_color='white',
      align='center', 
      font=dict(color='black', size=12)),# cell
  cells=dict(
      values=[df.Color, df.Year],  # Two column attributes
      line_color=[df.Color], 
      fill_color=[df.Color],
      align='center', 
      font=dict(color='black', size=13)
  ))
])

fig.show()
Copy the code

Tabular data slide

When there is too much data in the DataFrame, we can slide and view it:

student = pd.DataFrame({"Gender": ["Xiao Ming"."Little red"."Chou"."Note"."Little su"] * 100.# Scale up the data 100 times at the same time
                    "Age": [19.29.32.20.18] * 100."Gender": ["Male"."Female"."Male"."Female"."Male"] * 100."Performance": [590.588.601.670.555] * 100})
student
Copy the code

# drawing

fig = go.Figure(
    data=[go.Table(
        header=dict(values=list(student.columns),  The table header value is the data column attribute
                    fill_color='paleturquoise'.# Fill color and text position
                    align='left'),
        cells=dict(values=[student. Gender, age, grade],The value of the cell is the Series value of each column attribute
                   fill_color='lavender',
                   align='left'
                  )
        
    )]
)

fig.show()
Copy the code

creat_table

The second method is to use the creat_table method in the graph factory

Basic chart generation

DataFrame Data generation table

import plotly.figure_factory as ff
fig = ff.create_table(tips)   # Put the generated TIPS data in
fig.show()
Copy the code

Add links to data

Set the width

import plotly.figure_factory as ff

data = [['name'.'age'.'results'].# header
        
        ['Ming'.20.620].Each list represents a row of records
        ['little red'.22.677],
        ['little weeks'.19.606]]

fig = ff.create_table(data,height_constant=20)  # change width
#fig = ff.create_table(data,height_constant=50)

fig.show()
Copy the code

Change the width to look like:

Color Settings

import plotly.figure_factory as ff

# color Settings
colorscale = [[0.'#4d004c'], [. 5.'#f2e5ff'], [1.'#ffffff']]  Set 3 colors in the table
# colorscale = [[0, '# 4 d004c], [. 25,' # 0 ac37d], [. 5, '# f2e5ff], [. 75,' # afc271], [1, ff1ff '# 1']] # 5 kinds of color

fig = ff.create_table(tips, colorscale=colorscale)   

fig.show()
Copy the code

Font color Settings

import plotly.figure_factory as ff

data = [['name'.'rank'], ['Ming'.1], ['little red'.2], 
        ['little weeks'.3], ['zhang'.4], ['note:'.5], ['wang'.6]]

# color Settings
colorscale = [[0.'#272D31'], [. 5.'#ff9f9f'], [1.'#ffffff']]

# font color Settings
font=['#7CFCFC'.'#0FEE00'.'#008B00'.'#F04F00'.'#6A0000'.'#CD0000'.'#FF3030']

fig = ff.create_table(data,  # Add data, color
                      colorscale=colorscale, 
                      font_colors=font)

fig.layout.width=500  Set table width

fig.show()
Copy the code

Use graphs and tables together

Consumption data set tips was adopted

import plotly.graph_objs as go
import plotly.figure_factory as ff

# add table
fig = ff.create_table(tips)


# add graphics
fig.add_trace(go.Scatter(
    x=tips["tip"],
    y=tips["total_bill"],
    marker=dict(color='#9099ff'),  # mark color
    name="total_bill <br>tip",
    xaxis='x2', yaxis='y2'
))


fig.add_trace(go.Scatter(
    x=tips["size"],
    y=tips["total_bill"],
    marker=dict(color='#a099af'),
    name="total_bill <br>size",
    xaxis='x2', yaxis='y2'
))

fig.update_layout(
    title_text="Consumption data chart Federation.",
    height=500,
    margin={"t":75."b":100},
    xaxis = {'domain': [0.45.]},
    xaxis2 = {'domain': [0.6.1.]},
    yaxis2 = {'anchor': 'x2'.'title': 'tips'}
    
)

fig.show()
Copy the code

To arrange figures vertically:

import plotly.graph_objs as go
import plotly.figure_factory as ff

# add table
fig = ff.create_table(tips)

# add graphics
fig.add_trace(go.Scatter(
    x=tips["tip"],
    y=tips["total_bill"],
    marker=dict(color='#9099ff'),  # mark color
    name="total_bill <br>tip",
    xaxis='x2', yaxis='y2'
))

fig.add_trace(go.Scatter(
    x=tips["size"],
    y=tips["total_bill"],
    marker=dict(color='#a099af'),
    name="total_bill <br>size",
    xaxis='x2', yaxis='y2'
))

fig.update_layout(
    title_text="Consumption data chart Federation.",
    height=800,
    margin={"t":75."l":50},
    yaxis = {'domain': [0.. 5]},  Domain graphics ratio range
    xaxis2 = {'anchor': "y2"},  The # anchor represents the coordinate axis for the drawing along with y2
    yaxis2 = {'domain': [0.6.1].'anchor':'x2'.'title': 'tips'} 
)

fig.show()
Copy the code