Search code examples
pandasdataframenumpydatatablemplfinance

How to wrap text in a dataframe's table (converted to .png)


enter image description here

I am having an issue where I cannot format my tables. The text is too long to just edit the dimensions or the text size. How can I quickly change this so you can see all the text when I have the data for each column more filled in? I am looking for a wrap text kind of function but I don't know if that is possible the way I'm doing it. Is there another way you'd recommend? I'm changing the table into a .png to insert into an Excel file. It has to be a .png so it's an object and doesn't mess with the size of the rows and columns in Excel.

import matplotlib.pyplot as plt 
import xlsxwriter as xl
import numpy as np
import yfinance as yf
import pandas as pd 
import datetime as dt
import mplfinance as mpf 
import pandas_datareader 
from pandas_datareader import data as pdr
yf.pdr_override()
import numpy as np

Individualreport = "C:\\Users\\Ashley\\FromPython.xlsx"
Ticklist = pd.read_excel("C:\\Users\\Ashley\\Eyes Trial Data Center.xlsx",sheet_name='Tickers', header=None)
stocks = Ticklist.values.ravel()
PipelineData = pd.read_excel("C:\\Users\\Ashley\\Eyes Trial Data Center.xlsx", sheet_name='Pipeline', header=None)
writer = pd.ExcelWriter(Individualreport, engine='xlsxwriter')

for i in stocks:

    #write pipeline data
    t = PipelineData.loc[(PipelineData[0]==i)]
    print(t)
   
    def render_mpl_table(data, col_width=10, row_height=1, font_size=10, wrap=True,
                     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 mpl_table._cells.items():
            cell.set_edgecolor(edge_color)
            if k[0] == 0 or k[1] < header_columns:
                cell.set_text_props(weight='bold', color='w')
                cell.set_facecolor(header_color)
            else:
                cell.set_facecolor(row_colors[k[0]%len(row_colors) ])
        return ax.get_figure(), ax


    fig,ax = render_mpl_table(t, header_columns=0, col_width=2.0)
    fig.savefig(str(i)+'pipe.png')

Solution

  • I think I needed to use an additional package, haven't tried with this example, but worked in another similar example I did.

    from textwrap import wrap
    label = ("label text that is getting put in the graph")
    label = [ '\n'.join(wrap(l, 20)) for l in label ] 
    
    #20 is number of characters per line