When I saw the title, I thought Plotly was a library for drawing graphs, but what does it mean for drawing tables? Didn't you think so?
Actually, you can draw diagrams in the same way you draw graphs in plotly! With pandas output alone, you can't decorate tables or display them together with figures, but you can do that with Plotly!
There are several ways to draw a table, and this is the first one, how to draw a table in go.Table using "graph_object", which is often introduced in this blog!
- How to draw a table, basic version
- How to draw a table Application (Adding decoration)
How to draw a table, basic version
Here's a summary, explaining the process of creating the table below!
When you have successfully completed it, you should be able to swap the columns around! Drag the top row of the table below to the left or right to see!
The data we will use is LifeExp (life expectancy), pop (population), and gdpPercap (GDP per capita) by region and year.
The above graph can be written with the eight lines of code below!
The basic structure is the same as for other graphs: fig.add_trace to add a graph_object corresponding graph. In the case of tables, it is go.Table.
go.Table unique features
One unique feature of go.Table is that the argument consists of two major elements, "header" and "cells".
- header : Settings for the table header (first row) (values : 1D array/list)
- cells : Settings other than the header of the table (values : 2D array)
Each of them can add multiple elements in the dictionary type, but since the minimum element is the values to be displayed in the table (values), we will focus on values here. (If you want to know more about other configuration elements, please see the application section below!)
fig = go.Figure() fig.add_trace( go.Table( header = dict(values=['titile1','title2']), cells = dict(values=[[1,2],[3,4]]) ) ) fig.show()
Tips on generating tables from dataframes (pandas)
In the pandas data frame, it is in table form, so you can convert it directly into plotly table form by writing the following!
- header : you can use df.columns to get the column names of the dataframe (and list them in header values)
- cells : get all rows of the dataframe, one column at a time
With a few changes to the header and cells, it is possible to extract only those items that match the criteria, instead of retrieving all of them.
go.Table( header = dict(values=list(df.columns)), cells = dict(values=[df.iloc[:,num] for num in range(len(df.columns))]) )
The table presented above can be implemented with this code.
import plotly.graph_objects as go import pandas as pd # Data preparation df = px.data.gapminder() df= df.groupby(['continent','year']).mean().reset_index().drop('iso_num',axis=1) df = df.round(4) # To the fourth decimal place. # Draw a table fig = go.Figure() fig.add_trace( go.Table( header = dict(values=list(df.columns)), cells = dict(values=[df.iloc[:,num] for num in range(len(df.columns))]) ) ) fig.show()
How to draw a table Application (Adding decoration)
So far, we have focused on the minimum requirements for writing a table. But there are many more things you can do with tables! So, from here on, I will summarize what you can do by adding decorations to a table. The following is what we will cover in this article.
- Border color
- Background color of the table
- Center alignment, right/left alignment
- Height setting
- Alternating background color
Combining these, you can draw the diagram below!
By the way, "header" and "cells" are separate, so you can set them separately!
By the way, "header" and "cells" are separated, so you can set them separately! Please add the following settings to the dictionary type of header and cells, where you set only values earlier.
Border color (line_color)
You can set the color of the border in the table. The default is white, which can be hard to see in some places, so we recommend changing it for better visibility!
By the way, I recommend "darks late gray" (it looks like a black line!)
Background color of the table (fill_color)
This is the part to set the background color in the table.
In the example above, we set the background color of the header to 'royalblue'.
Centered, right/left aligned (align)
You can set the direction in which the text is aligned, column by column (default is center).
In the example table below, the first column is left-aligned, the second column is centered, and the third and subsequent columns are centered by default.
This function allows you to set the font size of the text used in the table.
Basically, you can use the dictionary type to set the color and size, but if you want to change only the font size, you can use font_size = 12 to change only the size! (By the way, if you don't specify a color, the font will default to black.)
font=dict(color='white', size=12) # Set only font_size (color to default black) font_size=12
Allows you to set the height of a row in a table.
Set alternate background colors (+α Practice)
Do you find it difficult to see a table when all the background colors are the same? Isn't that the case?
The solution is to change the background color of odd-numbered rows and even-numbered rows, as shown below!
The trick is to set the background color of the even-numbered lines and the background color of the odd-numbered lines respectively, and then repeat the process!
rowEvenColor = 'lightgrey' rowOddColor = 'white' fill_color = [[rowOddColor,rowEvenColor]*40],
The table presented so far can be implemented with this code.
import plotly.graph_objects as go import pandas as pd df = px.data.gapminder() df= df.groupby(['continent','year']).mean().reset_index().drop('iso_num',axis=1) df = df.round(4) # To the fourth decimal place. # Draw a table rowEvenColor = 'lightgrey' rowOddColor = 'white' fig = go.Figure() fig.add_trace( go.Table( header = dict( values=list(df.columns), line_color='darkslategray', fill_color='royalblue', align=['left','center'], font=dict(color='white', size=12), height=40 ), cells = dict( values=[df.iloc[:,num] for num in range(len(df.columns))], line_color='darkslategray', fill_color = [[rowOddColor,rowEvenColor]*40], align=['left', 'center'], font_size=12, height=30 ) ) ) fig.show()