Fork me on GitHub

可视化神器Plotly美化表格

可视化神器Plotly美化表格

有时候看到一份表格,没有任何的颜色修饰,总觉得缺点美观效果。在Excel中我们可以直接对字体的颜色、大小等进行设置,还可以进行单元格的颜色填充,在plotly中美化表格输出主要是有两种方式:

  • 使用go.Table方法
  • 使用figure_factory的creat_table方法

Plotly连载文章

导入库

1
2
3
4
5
6
import pandas as pd
import numpy as np

import plotly_express as px
import plotly.graph_objects as go # 方法1:go.Table
import plotly.figure_factory as ff # 方法2:图形工厂

go.Table实现

该方法类似其他的图表绘制,直接使用go.Table方法之后往其中加入数据

基础表格

添加表头和单元格中的数据

1
2
3
4
5
6
7
8
9
import plotly.graph_objects as go

fig = go.Figure(data=[go.Table(
header=dict(values=['语文', '数学']), # 表头:列表形式

cells=dict(values=[[100, 90, 140, 123], # 单元格添加:第一列元素
[105, 135, 75, 95]])) # 第二列元素
])
fig.show()

个性化表格设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import plotly.graph_objects as go

fig = go.Figure(data=[go.Table(
header=dict(values=['语文', '数学'], # 表头:字典形式
line_color="darkslategray", # 表头线条颜色
fill_color="lightskyblue", # 表头填充色
align="center" # 文本显示位置 'left', 'center', 'right'
),

cells=dict(values=[[100, 90, 140, 123], # 单元格添加:第一列元素
[105, 135, 75, 95]], # 第二列元素
line_color="darkslategray", # 单元格线条颜色
fill_color="lightcyan", # 单元格填充色
align="center" # 文本显示位置
))])

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

fig.show()

DataFrame转成表格

将DataFrame数据快速转成漂亮的表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 绘图

fig = go.Figure(
data=[go.Table(
header=dict(values=list(data.columns), # 表头取值是data列属性
fill_color='paleturquoise', # 填充色和文本位置
align='left'),
cells=dict(values=[data.性别,data.年龄,data.成绩], # 单元格的取值就是每个列属性的Series取值
fill_color='lavender',
align='left'
)

)]
)

fig.show()

改变row和column的大小

有时候单元格的数据太长,我们需要进行单元格大小的调整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import plotly.graph_objects as go

values = [["李白 唐代","杜甫 唐代","苏轼 宋代","王安石 宋代"], # 第一列数据

["床前明月,疑是地上霜;举头望明月,低头思故乡",
"国破山河在,城春草木深。感时花溅泪,恨别鸟惊心。<br>烽火连三月,家书抵万金。白头骚更短,浑欲不胜簪。",
"十年生死两茫茫,不思量,自难忘。千里孤坟,无处话凄凉。<br>纵使相逢应不识,尘满面,鬓如霜。<br>夜来幽梦忽还乡,小轩窗,正梳妆。相顾无言,惟有泪千行。<br>料得年年肠断处,明月夜,短松冈。",
"念往昔、繁华竞逐。叹门外楼头,悲恨相续。<br>千古凭高,对此谩嗟荣辱。<br>六朝旧事随流水,但寒烟、芳草凝绿。<br>至今商女,时时犹唱后庭遗曲。"
]]


fig = go.Figure(data=[go.Table(
columnorder = [1,2], # 列属性的顺序
columnwidth = [800,4000], # 列属性中元素所占单元格整体大小

# 表头
header = dict(
values=[["唐宋作家"],["代表作品"]], # 两个表头
line_color='darkslategray', # 线条和填充色
fill_color='royalblue',
align=['left','center'], # 位置
font=dict(color='white', size=12), # 表头文本的颜色和字体大小
font_size=12,
height=40 # 高度
),

# 单元格设置
cells = dict(
values=values, # 数据
line_color='darkslategray', # 线条颜色
fill=dict(color=['paleturquoise', 'white']),
align=['left', 'center'], # 两个列属性文本显示位置
font_size=12, # 字体大小
height=50))
])

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

fig.show()

设置表格渐变色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import plotly.graph_objects as go

import pandas as pd

colors = ['rgb(239, 243, 255)', # rgb值越接近255,越接近白色
'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=dict(
values=["Color", "<b>YEAR</b>"], # 表头名称
line_color='white',
fill_color='white',
align='center',
font=dict(color='black', size=12)
),

# 单元格
cells=dict(
values=[df.Color, df.Year], # 两个列属性
line_color=[df.Color],
fill_color=[df.Color],
align='center',
font=dict(color='black', size=13)
))
])

fig.show()

表格数据滑动

当DataFrame中的数据过多的时候,我们可以进行滑动展示和查看:

1
2
3
4
5
student = pd.DataFrame({"性别":["小明","小红","小周","小孙","小苏"] * 100,  # 将数据同时扩大100倍
"年龄":[19,29,32,20,18] * 100,
"性别":["男","女","男","女","男"] * 100,
"成绩":[590,588,601,670,555] * 100})
student

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 绘图

fig = go.Figure(
data=[go.Table(
header=dict(values=list(student.columns), # 表头取值是data列属性
fill_color='paleturquoise', # 填充色和文本位置
align='left'),
cells=dict(values=[student.性别,student.年龄,student.成绩], # 单元格的取值就是每个列属性的Series取值
fill_color='lavender',
align='left'
)

)]
)

fig.show()

creat_table

第二种方法是使用图形工厂中的creat_table方法来生成

基础图表生成

DataFrame数据生成表格

1
2
3
import plotly.figure_factory as ff
fig = ff.create_table(tips) # 将生成的tips数据放入
fig.show()

数据中添加链接

设置宽度

1
2
3
4
5
6
7
8
9
10
11
12
import plotly.figure_factory as ff

data = [['姓名', '年龄', '成绩'], # 表头

['小明', 20, 620], # 每个列表代表一行记录
['小红', 22, 677],
['小周', 19, 606]]

fig = ff.create_table(data,height_constant=20) # 改变宽度
#fig = ff.create_table(data,height_constant=50)

fig.show()

改变宽度后的样子:

颜色设置

1
2
3
4
5
6
7
8
9
import plotly.figure_factory as ff

# 颜色设置
colorscale = [[0, '#4d004c'],[.5, '#f2e5ff'],[1, '#ffffff']] # 表格中设置3种颜色
#colorscale = [[0, '#4d004c'],[.25,'#0ac37d'],[.5, '#f2e5ff'],[.75,'#afc271'],[1, '#1ff1ff']] # 5种颜色

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

fig.show()

字体颜色设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import plotly.figure_factory as ff

data = [['name', 'rank'], ['小明', 1], ['小红', 2],
['小周', 3], ['小张', 4], ['小孙', 5], ['小王', 6]]

# 颜色设置
colorscale = [[0, '#272D31'],[.5, '#ff9f9f'],[1, '#ffffff']]

# 字体颜色设置
font=['#7CFCFC', '#0FEE00', '#008B00', '#F04F00', '#6A0000', '#CD0000', '#FF3030']

fig = ff.create_table(data, # 添加数据、颜色
colorscale=colorscale,
font_colors=font)

fig.layout.width=500 # 表格整体宽度设置

fig.show()

图形和表格联用

采用的消费数据集tips

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import plotly.graph_objs as go
import plotly.figure_factory as ff

# 添加表格
fig = ff.create_table(tips)


# 添加图形
fig.add_trace(go.Scatter(
x=tips["tip"],
y=tips["total_bill"],
marker=dict(color='#9099ff'), # 标记颜色
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="消费数据图表联合",
height=500,
margin={"t":75,"b":100},
xaxis = {'domain': [0, .45]},
xaxis2 = {'domain': [0.6, 1.]},
yaxis2 = {'anchor': 'x2', 'title': 'tips'}

)

fig.show()

将图形竖直方向上排列:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import plotly.graph_objs as go
import plotly.figure_factory as ff

# 添加表格
fig = ff.create_table(tips)

# 添加图形
fig.add_trace(go.Scatter(
x=tips["tip"],
y=tips["total_bill"],
marker=dict(color='#9099ff'), # 标记颜色
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="消费数据图表联合",
height=800,
margin={"t":75,"l":50},
yaxis = {'domain': [0, .5]}, # domain 图形占比范围
xaxis2 = {'anchor': "y2"}, # anchor表示是和y2一起作为绘图的坐标轴
yaxis2 = {'domain': [0.6, 1], 'anchor':'x2', 'title': 'tips'}
)

fig.show()

本文标题:可视化神器Plotly美化表格

发布时间:2021年08月21日 - 16:08

原始链接:http://www.renpeter.cn/2021/08/21/%E5%8F%AF%E8%A7%86%E5%8C%96%E7%A5%9E%E5%99%A8Plotly%E7%BE%8E%E5%8C%96%E8%A1%A8%E6%A0%BC.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea