Search code examples
pythonplotlydata-scienceplotly-python

How to remove whitespace under dynamic Plotly table?


I have a dynamic Plotly table. She get dataframe from SQL query using Pandas. Height of table constantly changing and i don't set current value. After setting table she must send as photo using aiogram Telegram bot. How to remove whitespace under table, which arises if i don't set current height?

figure = go.Figure(data=[go.Table(
    columnwidth=[300, 200, 500, 500, 150, 400, 500, 150],
    header=dict(
        values=['<b>Date</b>', '<b>Time</b>', '<b>Client</b>', '<b>Service</b>', '<b>Price</b>', '<b>Tips</b>', '<b>Additional</b>', '<b>Work time</b>'],
        align=['center'],
        height=40
    ),
    cells=dict(
        values=dataframe.transpose().values.tolist(),
        align=['center'],
        height=30
    ),
)])
figure.update_layout(autosize=False, margin={'l': 0, 'r': 0, 't': 0, 'b': 0}, width=1280)
figure.write_image("db/records.png")

UPD: dataframe.head().to_dict() reuslt

{'0': {0: '2022-10-24'}, '1': {0: '15:00'}, '2': {0: 'Bob'}, '3': {0: 'Radiator replacement'}, '4': {0: '16'}, '5': {0: '4'}, '6': {0: 'No'}, '7': {0: '2.0 h'}}

Solution

  • I solved the problem. I multiplied the number of rows by the row height and added the header height to that. To avoid problems with cells that contain two lines, I went through the dataframe and determined experimentally how many characters are in a cell that contains two lines. Further, using these values, I determined the height of the table, roughly calculating that a cell that contains two lines is 1.6 more than a one-line cell.

    def get_table_height(dataframe):
        rows = []
        double_height = 0
    
        for index, data in dataframe.iterrows():
            rows.append(index)
            if len(data[2]) > 28 or len(data[3]) > 28 or len(data[5]) > 28 or len(data[6]) > 28:
                double_height += 1
    
        one_rows_count = (len(rows) - double_height)
        one_rows = one_rows_count * 30
        double_rows = double_height * 48
    
        return 40 + one_rows + double_rows