【问题标题】:python: when plotting text, raise "TypeError: must be real number, not str"python:绘制文本时,引发“TypeError:必须是实数,而不是str”
【发布时间】:2018-01-02 01:57:08
【问题描述】:

我使用 matplotlib 在每个栏中绘制文本。

案例 1 中一切正常。每个栏的顶部都会显示一个收入数字。

但是当我使用 Case 2 时,错误 raise "TypeError: must be real number, not str". please anyone can help me to figure out.

案例一:

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()

案例 2:此引发错误

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

我找了几个小时的答案,但找不到答案,我真诚地需要帮助。非常感谢。

【问题讨论】:

  • 请忽略案例2中的参数('row,col,num')
  • 你不认为重新定义plt会导致问题吗?

标签: python matplotlib typeerror


【解决方案1】:

你有:

y = 'Total revenue'

因此,您遍历此字符串的每个字母:

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')

并尝试使用'%.02f' % b 格式化这封信。 这会导致您的错误消息,因为%f 需要一个数字。

您需要将代码更改为:

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')

现在b 是一个可以用'%.02f' % b 格式化的数字。

【讨论】:

  • 新年快乐! ?
猜你喜欢
  • 2020-11-22
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多