在matplotlib表中换行 [英] Wrap text in matplotlib table

查看:20
本文介绍了在matplotlib表中换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用matplotlib从词典列表中创建一个表.

为此,我使用了以下功能,我在本网站的另一个答案中找到了该功能:

 将matplotlib.pyplot导入为plt从matplotlib.externals导入六个导入 matplotlibmatplotlib.rc('font',family ='Arial')def render_mpl_table(data,col_width = 3.0,row_height = 2,font_size = 10,header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',bbox=[0, 0, 1, 1], header_columns=0,ax = None,** kwargs):如果ax为None:大小 = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])无花果,ax = plt.subplots(figsize = size)ax.axis('off')mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)mpl_table.auto_set_font_size(False)mpl_table.set_fontsize(font_size)对于 k,单元格中的六个.iteritems(mpl_table._cells):cell.set_edgecolor(edge_color)如果k [0] == 0或k [1]<标题列:cell.set_text_props(weight ='bold',color ='w',wrap = True)cell.set_facecolor(header_color)别的:cell.set_facecolor(row_colors[k[0]%len(row_colors)])返回斧头

问题是,即使我将属性放在 cell.set_text_props(weight ='bold',color ='w',wrap = True),我也无法将文本包装在单元格中

示例图片:

感谢您的帮助!

解决方案

最简单的方法是在文本中使用 '\n',然后调整列宽和行高.它不是内置功能.<​​/p>

I need to create a table using matplotlib from a list of dictionaries.

For this I use the following function, which I found in another answer on this site:

import matplotlib.pyplot as plt
from matplotlib.externals import six
import matplotlib
matplotlib.rc('font', family='Arial')

def render_mpl_table(data, col_width=3.0, row_height=2, font_size=10,
                     header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
                     bbox=[0, 0, 1, 1], header_columns=0,
                     ax=None, **kwargs):
    if ax is None:
        size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])
        fig, ax = plt.subplots(figsize=size)
        ax.axis('off')

    mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)

    mpl_table.auto_set_font_size(False)
    mpl_table.set_fontsize(font_size)

    for k, cell in six.iteritems(mpl_table._cells):
        cell.set_edgecolor(edge_color)
        if k[0] == 0 or k[1] < header_columns:
            cell.set_text_props(weight='bold', color='w', wrap=True)
            cell.set_facecolor(header_color)
        else:
            cell.set_facecolor(row_colors[k[0]%len(row_colors) ])
    return ax

The problem is that I cannot wrap the text inside a cell, even though I put the properties at cell.set_text_props(weight='bold', color='w', wrap=True).

Example image:

Thanks for any help!

解决方案

The easiest way to do this is to just use '\n' in your text and then play with column width and row height. It is not a built in feature.

这篇关于在matplotlib表中换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆