Search code examples
pythonmatplotlibtreemap

python float division by zero when plotting treemap chart


I'm new to python matplotlib and trying to plot a treemap chart, thanks in advance!

squarify.plot(sizes=df['vvmins'], label=df['category_name'], alpha=.8)
plt.axis('off')
plt.show()

then the 'float division by zero' error show up, my data set is like below(dummy): enter image description here


Solution

  • I ran into the same problem. Either of these options should work:

    1. Remove any 0 values in advance, as mentioned in the comments. For a Pandas dataframe, this can be accomplished by filtering for rows that do NOT have 0 values prior to plotting. (Currently commented out in code below). OR,
    2. If you want to retain the label that had a value of 0, you could add a very small fraction to all of your sizes.
    import pandas as pd
    import matplotlib
    import squarify
    df = pd.DataFrame(
        {"category_name": ["a", "c", "k", "s", "e", "d", "a", "d", "e", "s", "z", "k", "k", "k"],
         "vvmins": [4, 9, 2, 4, 5, 5, 9, 6, 3, 5, 7, 5, 2, 0],
        }
    )
    ##### OPTION 1 #####
    # Filter out rows with value of 0
    # df = df.loc[df["vvmins"] != 0]
    
    ##### OPTION 2 #####
    # Add a very small number to each element of size column
    df["vvmins"] = df["vvmins"].apply(lambda x: x + 0.000001)
    
    # Optional sorting of categories so like labels are together
    # Pairs well with OPTION 1
    # df.sort_values("category_name", inplace=True)
    
    # Plot as before
    squarify.plot(sizes=df["vvmins"], 
                  label=df["category_name"], 
                  alpha=0.8,
                  pad=True # adds white space; 0-value label more visible
                 )
    plt.axis("off")
    plt.show()