比较(七)利用python绘制表格

比较(七)利用python绘制表格

表格(Table)简介

1

表格是数据在行和列中的结构化排列,允许进行方便的排序、过滤和分析。表格的优点在于可以清晰、有组织的呈现信息,便于快速比较和解读信息。

快速绘制

  1. 基于pandas

    可能需要更新jinja2:pip install --upgrade jinja2

    import pandas as pd
    import matplotlib as mpl
    import numpy as np
    
    # 自定义数据
    sample_size = 6
    
    new_york = np.random.uniform(20,60,sample_size)
    paris = np.random.uniform(20,40,sample_size)
    london = np.random.uniform(5,30,sample_size)
    
    df = pd.DataFrame({'new_york': new_york,
                       'paris': paris,
                       'london': london},
                     index=pd.date_range(start="2020-01-01", periods=sample_size).strftime("%d-%m-%Y"))
    
    
    
    # 自定义风格函数
    def custom_table(styler):
        styler.background_gradient(cmap="Blues", axis=None) # 色阶
        styler.format(precision=2)
    
        # 文本格式
        styler.applymap(lambda x: 'text-align: center; font-size: 14px;') 
        return styler
    
    agg_metrics = df.agg(["mean", "max"]) # 增加统计数据
    pd.concat([df, agg_metrics]).style.pipe(custom_table)
    

    2

  2. 基于plottable

    import matplotlib.pyplot as plt
    import pandas as pd
    from plottable import Table
    
    # 自定义数据
    data = {'Score': [8, 6, 10, 3, 9],
            'Value': [50.42, 17.01, 42.90, 6.83, 92.06],
            'Comment': ['Nice', 'Cool', 'Fun', 'Bad', 'Okay']}
    df = pd.DataFrame(data)
    
    # 初始布局
    fig, ax = plt.subplots(figsize=(5, 5))
    
    # 绘制表
    tab = Table(df)
    
    plt.show()
    

    3

  3. 基于matplotlib

    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    
    # 自定义数据
    data = {'Freeze': [ 66386, 174296,  75131, 577908,  32015],
            'Wind': [ 58230, 381139,  78045,  99308, 160454],
            'Flood': [ 89135,  80552, 152558, 497981, 603535],
            'Quake': [ 78415,  81858, 150656, 193263,  69638],
            'Hail': [139361, 331509, 343164, 781380,  52269],
            'rows': ['%d year' % x for x in (100, 50, 20, 10, 5)]}
    df = pd.DataFrame(data)
    
    values = np.arange(0, 2500, 500)
    value_increment = 1000
    
    # 调色板
    colors = plt.cm.BuPu(np.linspace(0, 0.5, len(df)))
    n_rows = len(df)
    
    index = np.arange(len(df.columns)-1) + 0.3
    bar_width = 0.6
    
    # 条形堆叠图的垂直便宜
    y_offset = np.zeros(len(df.columns)-1)
    
    # 绘制条形图并为表格创建文本标签列表
    cell_text = []
    for row in range(n_rows):
        plt.bar(index, df.iloc[:, row], bar_width, bottom=y_offset, color=colors[row])
        y_offset = y_offset + df.iloc[:, row]
        cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
    
    # 反转颜色和文本标签以在顶部显示最后一个值
    colors = colors[::-1]
    cell_text.reverse()
    
    # 在轴的底部添加一个表格
    the_table = plt.table(cellText=cell_text,
                          rowLabels=df['rows'],
                          rowColours=colors,
                          colLabels=df.columns,
                          loc='bottom')
    
    # 调整布局以为表格腾出空间
    plt.subplots_adjust(left=0.1, bottom=0.1)
    
    # 修改刻度标签
    plt.ylabel(f"Loss in ${value_increment}'s")
    plt.yticks(values * value_increment, ['%d' % val for val in values])
    plt.xticks([])
    
    
    plt.show()
    

    4

定制多样化的表格

自定义表格一般是结合使用场景对相关参数进行修改,并辅以其他的绘图知识。参数信息可以通过官网进行查看,其他的绘图知识则更多来源于实战经验,大家不妨将接下来的绘图作为一种学习经验,以便于日后总结。

plottable主要利用Table绘制表格,可以通过plottable了解更多用法

# 导入相关库
import matplotlib.pyplot as plt
import pandas as pd
from plottable import Table
from plottable import ColumnDefinition
from matplotlib.cm import Blues
from plottable.plots import image, circled_image, bar, percentile_bars, percentile_stars, progress_donut
from plottable.formatters import decimal_to_percent
import matplotlib as mpl

plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签

# 自定义数据
data = {'Score': [8, 6, 10, 3, 9],
        'Value': [50.42, 17.01, 42.90, 6.83, 92.06],
        'Comment': ['Nice', 'Cool', 'Fun', 'Bad', 'Okay']}
df = pd.DataFrame(data)

df.head()

5

  1. 不同的修改行列方式

    fig = plt.figure(figsize=(12,4))
    
    
    # 单列修改:column_definitions
    plt.subplot(1, 3, 1) 
    
    column_definitions = [ColumnDefinition(name='Score',
                                           title='Score custom', # 自定义列名
                                           textprops={"ha": "left", "weight": "bold"} # 文本格式
                                          )]
    tab = Table(df, column_definitions=column_definitions)
    plt.title('单列修改:column_definitions')
    
    
    # 全部列修改:Table参数
    plt.subplot(1, 3, 2) 
    
    tab = Table(df, textprops={"ha": "left", "weight": "bold"}, # 文本格式
                row_dividers=False, # 删除行之间的线
                footer_divider=True, # 尾部添加参考线
        )
    plt.title('全部列修改:Table参数')
    
    
    # 细节修改
    plt.subplot(1, 3, 3) 
    
    tab = Table(df)
    tab.columns["Score"].set_facecolor('lightblue') # 自定义列
    tab.rows[1].set_fontcolor('green') # 修改颜色
    plt.title('细节修改')
    
    
    plt.show()
    

    6

  2. 自定义颜色

    fig = plt.figure(figsize=(12,8))
    
    # 修改单列颜色
    plt.subplot(3, 2, 1) 
    tab = Table(df)
    tab.columns['Value'].set_facecolor("lightblue")
    tab.columns['Score'].set_fontcolor("green")
    plt.title('修改单列颜色')
    
    # 修改全部颜色
    plt.subplot(3, 2, 2) 
    tab = Table(df)
    for col in df.columns:
        tab.columns[col].set_facecolor("lightblue")
        tab.columns[col].set_fontcolor("red")
    plt.title('修改单列颜色')
    
    
    # 修改单行颜色
    plt.subplot(3, 2, 3) 
    tab = Table(df)
    tab.rows[1].set_facecolor("lightblue")
    tab.rows[2].set_fontcolor("red")
    plt.title('修改单行颜色')
    
    
    # 修改全部行颜色
    plt.subplot(3, 2, 4) 
    tab = Table(df,
                even_row_color='lightgrey',
                odd_row_color='orange')
    plt.title('修改全部行颜色')
    
    
    # 单列渐变色
    plt.subplot(3, 2, 5) 
    tab = Table(df,
                column_definitions=[ColumnDefinition(name="Score", cmap=Blues)])
    plt.title('单列渐变色')
    
    plt.show()
    

    7

  3. 插入图片

    # 自定义数据
    data = {'Score': [3, 12, 5, 7, 10],
            'Comment': ['Fun', 'Okay', 'Nice', 'Bad', 'Cool'],
            'Image': ['python', 'apple', 'apple', 'python', 'apple']}
    df = pd.DataFrame(data)
    
    # 修改Image,增加前后缀拼出路径
    df['Image'] = df['Image'].apply(lambda x: x+'.png' if '.png' not in x else x)
    df['Image'] = df['Image'].apply(lambda x: 'pic/'+x if 'pic/' not in x else x)
    
    
    fig = plt.figure(figsize=(8,5))
    
    # 插入图片
    plt.subplot(1, 2, 1) 
    plt.title('插入图片')
    coldef = [ColumnDefinition(name="Image",
                               textprops={"ha": "center"},
                               width=0.5,
                               plot_fn=image)]
    tab = Table(df, column_definitions=coldef)
    
    
    # 插入图片-圆形图像
    plt.subplot(1, 2, 2)
    plt.title('插入图片-圆形图像')
    coldef = [ColumnDefinition(name="Image",
                               textprops={"ha": "center"},
                               width=0.5,
                               plot_fn=circled_image)]
    tab = Table(df, column_definitions=coldef)
    
    
    
    plt.show()
    

    8

  4. 在表格中绘图

    # 自定义数据
    data = {'Score': [82, 68, 17, 39, 91],
            'Value': [82, 68, 17, 39, 91],
            'Metric': [82, 68, 17, 39, 91],
            'KPI': [82, 68, 17, 39, 91]}
    df = pd.DataFrame(data)
    df = df/100
    
    
    fig = plt.figure(figsize=(12,8))
    
    # 绘制bar百分比
    plt.subplot(3, 2, 1) 
    plt.title('绘制bar百分比')
    tab = Table(df,
                textprops={"ha": "center"},
                column_definitions=[ColumnDefinition("Score",
                                                     plot_fn=percentile_bars,
                                                     plot_kw={"is_pct": True})]
               )
    
    
    # 绘制星星百分比
    plt.subplot(3, 2, 2) 
    plt.title('绘制星星百分比')
    tab = Table(df, cell_kw={"linewidth": 0,  "edgecolor": "k"},
                textprops={"ha": "center"},
                column_definitions=[ColumnDefinition("Value",
                                                     plot_fn=percentile_stars,
                                                     plot_kw={"is_pct": True})]
               )
    
    # 绘制甜甜圈进度
    plt.subplot(3, 2, 3) 
    plt.title('绘制甜甜圈进度')
    tab = Table(df, 
                textprops={"ha": "center"},
                column_definitions=[ColumnDefinition("Metric",
                                                     plot_fn=progress_donut,
                                                     plot_kw={"is_pct": True,
                                                              "formatter": "{:.0%}"})])
    
    # 绘制进度条
    plt.subplot(3, 2, 4) 
    plt.title('绘制进度条')
    
    cmap = plt.get_cmap('viridis')
    tab = Table(df,
                textprops={"ha": "center"},
                column_definitions=[ColumnDefinition("KPI",
                                                     plot_fn=bar,
                                                     plot_kw={"cmap": cmap,
                                                              "plot_bg_bar": True,
                                                              "lw": 0.5})]
               )
    
    # 各种百分比进度条
    plt.subplot(3, 2, 5) 
    plt.title('各种百分比进度条')
    
    cmap = plt.get_cmap('viridis')
    col_defs = [ColumnDefinition("Metric", plot_fn=progress_donut, plot_kw={"is_pct": True,
                                                                            "formatter": "{:.0%}"}),
                   ColumnDefinition("Value", plot_fn=percentile_stars, plot_kw={"is_pct": True}),
                   ColumnDefinition("Score", plot_fn=percentile_bars, plot_kw={"is_pct": True}),
                   ColumnDefinition("KPI", plot_fn=bar, plot_kw={"cmap":cmap,
                                                                 "plot_bg_bar": True,
                                                                 "lw": 0.5})
               ]
    tab = Table(df, cell_kw={"linewidth": 0,  "edgecolor": "k"},
                textprops={"ha": "center"},
                column_definitions=col_defs)
    
    plt.show()
    

    download-5

总结

以上通过pandas的styler方法绘制独具风格的表格,这里推荐使用plottable快速绘制表格,并通过相关方法和参数自定义多样化的表格。

共勉~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值