通过将 pandas 数据框绘制到 matplotlib 表中,如何将图像添加到每一列

问题描述 投票:0回答:1

我正在创建一个 Discord 机器人,它使用 Python 从足球 API 中提取与足球相关的数据来获取联赛数据,并且它将以表格格式组织这些数据,以表格图像显示排名。该表还包括队徽图像。

首先,我创建一个 pandas 数据框,并将从 API 检索到的所有数据存储在其中。然后我使用 matplotlib 库将它们转换成表格。

数据包括位置数据、团队名称、点和团队徽章的 url (cresturl),我可以绘制前 3 列,但绘制图像是我需要帮助的地方。我可以先将图像绘制到数据帧中,然后将它们转换为 matplotlib 表,也可以在将数据帧转换为 matplotlib 表后将它们添加到空列中。问题是我不知道如何同时做到这两点。

然后我将它们转换为 png 文件,但由于我不想将 png 文件存储在我的硬盘中,所以我将它们存储为 BytesIO 图像变量

@client.event
async def on_message(message):
    #I'm gonna leave the part where I verify if the user message is a valid code
    table_image = get_table(code)
    await.message.channel.send(table_image)

def get_table(code):
    df = pd.DataFrame(columns=['Position', 'Team', 'Points', 'emblem'])
    url = ~~~{code}~~~
    conn = requests.get(url, headers = headers)
    data = conn.json()
 
    images = []
    #data includes position_data, team_name, point and a url of team crest (cresturl)
    for each_team in data:
            new_row = {'Position': (position_data), 'Team':(team_name)],'Points':(points)}
            images.append(crestUrl)
            df.loc[len(df)] = new_row
    
    #converts it into a matplotlib table object
    table = render_table(df, images,header_column = 0, col_width = 2.0)
    # saved as BytesIO image variable so they are not saved as png files in my hard drive
    table_image = BytesIO()
    plt.savefig(table_image, format='png')
    return table_image

def render_table(data, images, ~~~~~~)
    fig, ax = plt.subplots(figsize=size)
    ax.axis('off')
    mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)

最后我希望桌子看起来像

是的。

python pandas matplotlib discord discord.py
1个回答
0
投票

尝试这样的事情:

@client.event
async def on_message(message):
    #I'm gonna leave the part where I verify if the user message is a valid code
    table_image = get_table(code)
    await.message.channel.send(table_image)
    
# convert your links to html tags 
def path_to_image_html(path):
    return '<img src="'+ path + '" width="60" >'

def get_table(code):
    df = pd.DataFrame(columns=['Position', 'Team', 'Points', 'emblem'])
    url = ~~~{code}~~~
    conn = requests.get(url, headers = headers)
    data = conn.json()
 
    #data includes position_data, team_name, point and a url of team crest (cresturl)
    for each_team in data:
        imgUrl = path_to_html(crestUrl)
        new_row = {'Position': (position_data), 'Team':(team_name),'Points':(points), 'emblem': imgUrl}
        df.loc[len(df)] = new_row
    
    html_data = df.to_html(escape=False, formatters=format_dict, index=False)

    # saved as BytesIO image variable so they are not saved as png files in my hard drive
    table_image = BytesIO()
    table_image.write(html_data.encode('utf-8'))
    return table_image
© www.soinside.com 2019 - 2024. All rights reserved.