Search code examples
pythonmatplotlibtypeerror

python: when plotting text, raise "TypeError: must be real number, not str"


I use matplotlib to plot text in each bar.

In Case 1 everything goes fine.Each bar will get a revenue number displays on its top.

but when I use Case 2 ,Error raise "TypeError: must be real number, not str".

Please can anyone help me to figure this out?

Case 1:

grouped_revenue _DF = revenue_DF.groupby(['industry']).sum()
sns.barplot(
    x = grouped_revenue _DF.index,
    y = 'Total revenue',
    data=grouped_revenue _DF,
    palette='viridis')
plt.title('Revenue (QoQ)2007-2017')
for a, b in zip(np.arange(len(grouped_revenue_DF.index)), 
grouped_revenue _DF['Total revenue']):
    plt.text(a, b + 1000000, '%.02f' % b, ha='center', va='top', fontsize=15,color='purple')
sns.despine()
plt.tight_layout()
plt.show()

Case 2: THIS RAISE ERROR

class plotpic():

    def plt(input_DF,y,palette,title):
        sns.barplot(x=input_DF.index,y=y,data=input_DF,palette=palette) 
        for a ,b in zip(np.arange(input_DF.shape[0]),y):
            plt.text(a, b , '%.02f' % b, ha='center', va='top',fontsize=15,color='purple')
        plt.title(title)
        sns.despine(top=True)
        plt.tight_layout()


y = 'Total revenue'
palette = 'viridis'
title = 'Revenue (QoQ)2007-2017'

plotpic.plt(grouped_revenue _DF,y,palette,row,col,num,title)    
plt.show()

Traceback (most recent call last):
  File "C:\Users\b\Downloads\Python-Data-Science\Data\Visualization\my_works.py", line 562, in <module>
    plotpic.plt(grouped_revenue _DF,y,title)
    plt.text(a, b , '%.02f' % b, ha='center', va='top', fontsize=15,color='purple')
TypeError: must be real number, not str

I searching for an answer for hours but could not get an answer for this, I sincerely need help.Thanks very much.


Solution

  • You have:

    y = 'Total revenue'
    

    Therefore, you iterate over each letter of this string:

    for a ,b in zip(np.arange(input_DF.shape[0]),y):
         plt.text(a, b , '%.02f' % b, ha='center', va='top',fontsize=15,color='purple')
    

    and try to format this letter with '%.02f' % b. This causes your error message because %f requires an number.

    You need to change your code to:

    for a ,b in zip(np.arange(input_DF.shape[0]), grouped_revenue _DF[y)]:
        plt.text(a, b , '%.02f' % b, ha='center', va='top',fontsize=15,color='purple')
    

    Now b is a number an can be formatted with '%.02f' % b.