【问题标题】:Python Barplot ValueError: could not convert string to float:Python Barplot ValueError:无法将字符串转换为浮点数:
【发布时间】:2021-12-22 23:24:51
【问题描述】:

我尝试在 Python 中绘制一个简单的条形图,但是当我运行代码时:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x=['A','B','C','D','E','F','G','H','I','J']
y=[47, 23, 27,  0, 82,  7, 46, 92, 36, 76]
plt.bar(x,y)
plt.xlabel('Categories')
plt.ylabel("Values")
plt.title('Categories Bar Plot')
plt.show()

我收到一条错误消息:

ValueError: could not convert string to float: 'A'

我不知道为什么这不起作用,尤其是因为它是网站上一个应该可以工作的示例的精确副本。

【问题讨论】:

  • 这适用于当前版本的 matplotlib。我投票决定关闭它,因为它不可重现。

标签: python matplotlib bar-chart


【解决方案1】:

您使用的是哪个 pandas/matplotlib 版本?你确定使用干净的环境吗?

你的代码对我来说很好。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x=['A','B','C','D','E','F','G','H','I','J']
y=[47, 23, 27,  0, 82,  7, 46, 92, 36, 76]
plt.bar(x,y)
plt.xlabel('Categories')
plt.ylabel("Values")
plt.title('Categories Bar Plot')
plt.show()

输出:

【讨论】:

  • 好的,非常感谢,我会尝试关闭并重新启动一切
  • 这个错误很奇怪,因为“绘图”字母应该可以工作(尝试plt.bar(x,x)),因此我对matplotlib版本的问题
  • 这是因为我必须使用 matplotlib 1.5.1,在下面我发布了我的解决方法
  • 感谢您向社区提供反馈;)
【解决方案2】:

原来,我使用的是 matplotlib 1.5.1,但由于无法在这里写的原因,我无法升级它。 但我写了一个解决方法,想与社区分享:

x1=['A','B','C','D','E','F','G','H','I','J']
N=0
x2=[]
for i in range(len(x1)):
    x2.append(N)
    N+=1
y=[47, 23, 27,  0, 82,  7, 46, 92, 36, 76]
plt.bar(x2,y)
plt.xlabel('Categories')
plt.ylabel("Values")
plt.title('Categories Bar Plot')
plt.xticks(np.arange(0.5, len(x2)+0.5), list(x1), rotation=90, size = '10')
plt.show()

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2018-04-23
    • 2015-03-25
    • 2021-12-23
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多