pythonpercentagesquarify

How to add a % symbol on a Squarify treemap


I'm trying to plot a treemap with Squarify. But i don't realize how could i add a "%" to a float value.

ListaCryptos = ['BTC', 'ETH']
tamaños2 = [61,755, 32,992]

sq.plot(sizes=np.around(tamaños2, decimals=2),
            label=ListaCryptos,
            value=np.around(tamaños2, decimals=2),
            color=colores,
            pad=True,
            alpha=0.9,
            bar_kwargs=dict(linewidth=2, edgecolor="white"),
            text_kwargs={'fontsize': 32})

    plt.title("Rentabilidad", fontsize=32, fontweight="bold")
    plt.axis('off')
    plt.show()

Then in the plot i need to the values express like 61,75% 32,99%

How could i add a percent symbol to my float values.


Solution

  • First: [61,755, 32,992] means four values: 61 and 755 and 32 and 992.
    To have two values you have to use dot (.) in 61.755 and 32.992


    To display % you have to convert float to string and add %.

    Using f-string you can create string with % and you can even round value.

    value=[f'{x:.2f}%' for x in tamaños2],
    

    Minimal working code

    import squarify as sq
    import matplotlib.pyplot as plt
    import numpy as np
    
    cryptos = ['BTC', 'ETH']   # PEP8: `lower_case_names` for variables
    values = [61.755, 32.992]  # PEP8: English names for variables
    
    sq.plot(sizes=np.around(values, decimals=2),
            label=cryptos,
    
            value=[f'{x:.2f}%' for x in values],  # <---
    
            #color=colores,
            pad=True,
            alpha=0.9,
            bar_kwargs=dict(linewidth=2, edgecolor="white"),
            text_kwargs={'fontsize': 32})
    
    plt.title("Rentabilidad", fontsize=32, fontweight="bold")
    plt.axis('off')
    plt.show()
    

    enter image description here


    PEP 8 -- Style Guide for Python Code