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!

sequence21
  • 11
  • 1
  • 2
  • I have this issue also! plt.pie() returns the same error if there are any nans in the input array. – Takver Dec 16 '19 at 22:32

1 Answers1

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]
Dhruvit
  • 21
  • 2
  • thanks for the response, however I am still getting the same error. am i calling it right? sizes = zero_to_nan(sample) – sequence21 May 05 '18 at 15:17
  • and yes i have tried adding brackets, sizes = (zero_to_nan(sample)) and it still gives me ValueError: cannot convert float NaN to integer – sequence21 May 05 '18 at 16:10