1

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!

1
  • I have this issue also! plt.pie() returns the same error if there are any nans in the input array. Commented Dec 16, 2019 at 22:32

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the response, however I am still getting the same error. am i calling it right? sizes = zero_to_nan(sample)
and yes i have tried adding brackets, sizes = (zero_to_nan(sample)) and it still gives me ValueError: cannot convert float NaN to integer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.