Can't add title to pie chart (matplotlib)

2019-07-26 20:24发布

问题:

plt.title('Survival Rate')
plt.pie(total_survival, labels=[str(survival_percent) + "% " + "survived", str(100- survival_percent) + "% " + "died"])

I am trying to add a title to a pie chart but am getting this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-250-7e0f3cd8c625> in <module>()
----> 1 plt.title('Survival Rate')
  2 plt.pie(total_survival, labels=[str(survival_percent) + "% " + "survived", str(100- survival_percent) + "% " + "died"])
  3 

TypeError: 'str' object is not callable

All resources that I have seen online write their title as a string within parentheses and don't include it as an argument in plt.pie() so I'm not sure where I am going wrong.

回答1:

The following code works fine:

import matplotlib.pyplot as plt
survival_percent = 67
total_survival = [67,33]
plt.title('Survival Rate')
plt.pie(total_survival, labels=[str(survival_percent) + "% " + "survived", str(100- survival_percent) + "% " + "died"])

plt.show()

The error you get is therefore produced by part of the code that you don't show here. We can now only guess, but the error 'str' object is not callable suggests, that you have redefined plt.title to a string. This could happen if for example somewhere in your code you wrote something like

plt.title = 'Survival Rate'

(which is of course not reasonable) then later on calling (correctly)

plt.title('Survival Rate') would result in the error you get.



回答2:

I was getting the same error. What you'd want to do is restart your kernel (if you're running it in Jupiter notebooks) and run your code again. It should fix it.