sequence21
sequence21

Reputation: 11

Not plotting 'zero' values in a list on a pie chart in matplotlib [Python,Jupyter NoteBooks]

I just need help with Not plotting 'zero' values on a pie chart in matplotlib as per title using python.

I have tried using the solution from Not plotting 'zero' in matplotlib or change zero to None [Python] from a different post but I keep getting cannot convert float NaN to integer error.

Solution from other post:

values = [3, 5, 0, 3, 5, 1, 4, 0, 9]

def zero_to_nan(values):
    """Replace every 0 with 'nan' and return a copy."""
    return [float('nan') if x==0 else x for x in values]

print(zero_to_nan(values))

This is a shortened down version of my code:

#For plotting and visualization
from IPython.display import display
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

#Possible solution - however i get error cannot convert float NaN to integer 
error

sample = [innercitybypass,others,kingsfordcount] ##E.g.[0,1,2]
def zero_to_nan(sample):
    return [float('nan') if x==0 else x for x in sample]

labels = ['InnerCityBypass','OtherRds','KingsfordRd']
###sizes = [innercitybypass,others,kingsfordcount]
sizes = zero_to_nan(sample)
#Set different colors
colors = ['green','red','blue']

plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', 
startangle=140)
plt.axis('equal')
plt.show()

Any help will be appreciated, thanks!

Upvotes: 1

Views: 3238

Answers (1)

Dhruvit
Dhruvit

Reputation: 21

Use numpy.nan (make sure you import numpy)

import numpy as np

def zero_to_nan(sample):
    return [np.nan if x==0 else x for x in sample]

Upvotes: 1

Related Questions