前言
大家好。
今天给大家分享一个专门可视化表格神器plottable库,结合pandas库在可视化表格方面可谓再无敌手。提供对应的python代码,干货满满。 如果对你有帮助,还请点赞关注转发~
老规矩,本文涉及的python库版本信息如下:
# !pip install plottable==0.1.5 pyjanitor==0.26.0
# !pip install mpl_font==1.1.0
import numpy as np
import pandas as pd
import janitor
import matplotlib
print(f"pandas : {pd.__version__}") #pandas: 2.2.0
print("numpy:", np.__version__) #numpy: 1.26.3
本文目录
plottable库介绍
绘图技巧总结
列区域不同样式设置汇总
小数数据类型显示不同格式汇总
显示不同图标&&风格汇总
对单元格和字体的用法介绍总结
精美表格案例展示
对表格数据显示进度条、五角星、百分比,使得数据展示精美直观
将pandas的表格显示热力图
为不同行配置不同颜色
参考文档
plottable库介绍
plottable库(其官方github:https://github.com/znstrider/plottable)是专门可视化表格展示的神器,其底层是基于matplotlib开发的,展示效果惊艳,修改代码少,非常好用。
绘图技巧总结
今天将plottable库常用的显示核心语法汇总介绍给大家,并配置对应的案例代码。
列区域不同样式设置汇总
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from plottable import ColumnDefinition, ColDef, Table
from plottable.formatters import decimal_to_percent
import mpl_font.noto
from plottable.cmap import normed_cmap
np.random.seed(2024)
d = pd.DataFrame(np.random.random((5, 5)), columns=["A", "B", "C", "D", "E"]).round(2)
fig, ax = plt.subplots(figsize=(6, 5))
tab = Table(d,ax=ax
, column_definitions=[
ColumnDefinition(name="index",
title="索引",
width=2, #设置单元空格的宽度
textprops={"ha": "left", "weight": "bold"} #设置属性靠左,加粗
),
ColumnDefinition(name="A", title="Title A",formatter=decimal_to_percent),
ColumnDefinition(name="B", title="梯度图"
, cmap=plt.cm.cool # 设置背景梯度图
,text_cmap=plt.cm.Reds # 设置文字背景梯度图
,textprops={"ha": "center"} #设置属性居中
),
ColDef(name="C", group="对照组", formatter="{:.2e}"),
ColumnDefinition(name="D",title='百分比', group="对照组",formatter="{:.1%}"),
ColumnDefinition(
name="E",
width=0.75,
textprops={
"ha": "center",
"bbox": {"boxstyle": "circle", "pad": 0.35},
},
cmap=normed_cmap(d["E"], cmap=plt.cm.winter, num_stds=2.5),
group="实验组",
),
]
)
plt.show()
可视化结果:
小数数据类型显示不同格式汇总
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from plottable import ColumnDefinition, ColDef, Table
from plottable.formatters import decimal_to_percent
import mpl_font.noto
np.random.seed(2024)
d = pd.DataFrame(np.random.random((5, 5)), columns=["A", "B", "C", "D", "E"]).round(4)
fig, ax = plt.subplots(figsize=(8, 4))
tab = Table(d, column_definitions=[ColDef(name="A", title="2 Decimals", formatter="{:.2f}"),
ColDef(name="B", title="Percentage", formatter="{:.1%}"),
ColDef(name="C", title="Exponent\nNotation", formatter="{:.2e}")])
plt.show()
fig.savefig("demo.png", facecolor=ax.get_facecolor(), dpi=200)
输出结果:
显示不同图标&&风格汇总
!git clone https://github.com/znstrider/plottable
from pathlib import Path
from plottable.plots import *
path = list(Path("./plottable/docs/example_notebooks/country_flags").glob("*.png"))[0]
import mpl_font.noto
np.random.seed(2024)
fig, axes = plt.subplots(1,7,figsize=(10, 1))
bars = percentile_bars(axes[0], val=72, color="#b0db7c", background_color="#f0f0f0", is_pct=False
,rect_kw={"lw": 0.5,},)
axes[0].set_title("条形进度条")
image(axes[1], path)
axes[1].set_title("矩形图片")
im = circled_image(axes[2], path)
axes[2].set_title("圆形图片")
im = circled_image(axes[3], path, linewidth=2, visible=True, edgecolor="#999999")
axes[3].set_title("边框圆形图片")
b = bar(axes[4], 0.5, plot_bg_bar=True, cmap=plt.cm.cool, annotate=True, lw=1, height=0.35)
axes[4].set_title("进度条")
stars = percentile_stars(axes[5], 70, background_color="#f0f0f0")
axes[5].set_title("五角星")
donut = progress_donut(axes[6], 73, textprops={"fontsize": 14})
axes[6].set_title("仪表盘")
plt.show()
fig.savefig("demo.png", facecolor=ax.get_facecolor(), dpi=200)
输出结果:
对单元格和字体的用法介绍总结
table.columns[column_name].set_facecolor("#f0f0f0")
table.rows[0].set_facecolor("#f0f0f0")
单元格区域属性设置方法
set_alpha:设置透明度
set_color:设置填充颜色
set_edgecolor:设置边框颜色
set_facecolor:设置面(填充)颜色
set_fill:设置是否填充,即开启或关闭填充效果
set_hatch:设置填充图案样式(如斜线、点状等)
set_linestyle:设置边框线条样式
set_linewidth:设置边框线条宽度
字体属性设置方法
set_fontcolor:设置字体颜色
set_fontfamily:设置字体家族(字体类型)
set_fontsize:设置字体大小
精美表格案例展示
对表格数据显示进度条、五角星、百分比,使得数据展示精美直观
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap
import mpl_font.noto
from plottable import ColumnDefinition, Table
from plottable.formatters import decimal_to_percent
from plottable.plots import bar, percentile_bars, percentile_stars, progress_donut
# cmap = LinearSegmentedColormap.from_list(
# name="bugw", colors=["#ffffff", "#f2fbd2", "#c9ecb4", "#93d3ab", "#35b0ab"], N=256
# )
np.random.seed(2024)
pf = pd.DataFrame(np.random.random((5, 4)), columns=["A", "B", "C", "D"]).round(2)
pf.index.set_names("序号",inplace=True)
fig, axes = plt.subplots(1,2,figsize=(10,5),dpi=100)
Table(pf,ax=axes[0]
,odd_row_color="#f0f0f0"
, even_row_color="#e0f6ff"
)
axes[0].set_title("原始数据如下")
Table(pf
,ax=axes[1],
cell_kw={
"linewidth": 0,
"edgecolor": "k",
},
textprops={"ha": "center"},
column_definitions=[
ColumnDefinition("index", textprops={"ha": "left"}),
ColumnDefinition("A", plot_fn=percentile_bars, plot_kw={"is_pct": True}),
ColumnDefinition(
"B", width=1.5, plot_fn=percentile_stars, plot_kw={"is_pct": True}
),
ColumnDefinition(
"C",
plot_fn=progress_donut,
plot_kw={
"is_pct": True,
"formatter": "{:.0%}"
},
),
ColumnDefinition(
"D",
width=1.25,
plot_fn=bar,
plot_kw={
"cmap": plt.cm.cool,
"plot_bg_bar": True,
"annotate": True,
"height": 0.5,
"lw": 0.5,
"formatter": decimal_to_percent,
},
),
],
)
axes[1].set_title("经过精美化后数据展示")
plt.show()
输出结果:
将pandas的表格显示热力图
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap
from plottable import ColDef, Table
np.random.seed(2024)
cities = [
"TORONTO",
"VANCOUVER",
"HALIFAX",
"CALGARY",
"OTTAWA",
"MONTREAL",
"WINNIPEG",
"EDMONTON",
"LONDON",
"ST. JONES",
]
months = [
"1月","2月","3月","4月","5月","6月",
"7月", "8月", "9月", "10月", "11月", "12月",
]
# months = ["JAN","FEB","MAR","APR","MAY","JUN"
# ,"JUL","AUG","SEP","OCT","NOV","DEC",]
data = np.random.random((10, 12)) + np.abs(np.arange(12) - 5.5)
data = (1 - data / (np.max(data)))
d = pd.DataFrame(data, columns=months, index=cities).round(2)
fig, ax = plt.subplots(figsize=(14, 5))
column_definitions = [
ColDef(name, cmap=plt.cm.cool, formatter='{:.2f}') for name in months
] + [ColDef("index", title="", width=1.5, textprops={"ha": "right"})]
tab = Table(
d,
column_definitions=column_definitions,
row_dividers=False,
col_label_divider=False,
textprops={"ha": "center"},
cell_kw={
"edgecolor": "w",
"linewidth": 0,
},
)
tab.col_label_row.set_facecolor("k")
tab.col_label_row.set_fontcolor("w")
tab.columns["index"].set_facecolor("k")
tab.columns["index"].set_fontcolor("w")
tab.columns["index"].set_linewidth(0)
plt.show()
fig.savefig(
"demo.png",
facecolor=fig.get_facecolor(),
dpi=200,
)
可视化结果:
为不同行配置不同颜色
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from plottable import ColDef, Table
from plottable.plots import image
import mpl_font.noto
np.random.seed(2024)
pf = pd.DataFrame(np.random.random((18, 5)), columns=["成都", "西安", "北京", "上海", "重庆"]).round(2)
pf['rank'] = list(range(1, 19))
fig, ax = plt.subplots(figsize=(14, 12),dpi=100)
path = list(Path("./plottable/docs/example_notebooks/country_flags").glob("*.png"))[0]
table_col_defs = [
ColDef("rank", border="right",width=0.5, title=""),
ColDef("成都", width=0.5, title=""),
ColDef("西安", width=0.35, title=""),
ColDef("北京", width=0.6, title="北京", textprops={"ha": "center"}),
ColDef("上海", width=0.5, title="上海", formatter="{:+}"),
ColDef("重庆", border="left", title="重庆"),
]
row_colors = {
"top4": "#2d3636",
"top6": "#516362",
"playoffs": "#8d9386",
"relegation": "#c8ab8d",
"even": "#627979",
"odd": "#68817e",
}
bg_color = row_colors["odd"]
text_color = "#e0e8df"
table_cols =['成都', '西安', '北京', '上海', '重庆']
plt.rcParams["text.color"] = text_color
fig.set_facecolor(bg_color)
ax.set_facecolor(bg_color)
table = Table(
pf,
column_definitions=table_col_defs,
row_dividers=True,
col_label_divider=False,
footer_divider=True,
index_col="rank",
columns=table_cols,
even_row_color=row_colors["even"],
footer_divider_kw={"color": bg_color, "lw": 2},
row_divider_kw={"color": bg_color, "lw": 2},
column_border_kw={"color": bg_color, "lw": 2},
textprops={"fontsize": 16, "ha": "center"},
)
for idx in [0, 1, 2, 3]:
table.rows[idx].set_facecolor(row_colors["top4"])
for idx in [4, 5]:
table.rows[idx].set_facecolor(row_colors["top6"])
table.rows[15].set_facecolor(row_colors["playoffs"])
for idx in [16, 17]:
table.rows[idx].set_facecolor(row_colors["relegation"])
table.rows[idx].set_fontcolor(row_colors["top4"])
plt.show()
fig.savefig(
"demo.png",
facecolor=fig.get_facecolor(),
dpi=200,
)
可视化结果:
参考文档
https://github.com/znstrider/plottable
https://plottable.readthedocs.io/en/latest/notebooks/plots.html
z先生说
今天给大家分享plottable库结合pandas来对表格数据进行精美可视化,并提供对应的python可视化代码,干货满满。大家在实际过程中,可根据自己的喜好来定制对应的风格展示突出你数据重点。如果本文对你有帮助,还请你点赞关注转发。
-------- End --------
推荐👇同名微信视频号
图解Pandas
图文00-内容框架介绍 | 图文01-数据结构介绍 | 图文02-创建数据对象 | 图文03-操作Excel文件 | 图文04-常见的数据访问 | 图文05-常见的数据运算 | 图文06-常见的数学计算 | 图文07-常见的数据统计 | 图文08-常见的数据筛选 | 图文09-常见的缺失值处理 | 图文10-数据合并操作 | 图文11-Groupby分组操作