【问题标题】:Unable to plot a bar chart using my dataframe无法使用我的数据框绘制条形图
【发布时间】:2021-03-05 23:15:54
【问题描述】:

我正在尝试将以下数据框绘制成条形图:

        JP_genre JP_sales
0         Action   159.95
1      Adventure    52.07
2       Fighting    87.35
3           Misc   107.76
4       Platform   130.77
5         Puzzle    57.31
6         Racing    56.69
7   Role-Playing   352.31
8        Shooter    38.28
9     Simulation    63.70
10        Sports   135.37
11      Strategy    49.46

当我输入以下代码时:

JP_df.plot(x = 'JP_genre', y = 'JP_sales', kind= 'bar')

我得到了错误

TypeError: no numeric data to plot

知道为什么会这样吗?

【问题讨论】:

  • 会不会是 JP_sales 列是字符串而不是浮点数?
  • 我重新创建了 excel 表并尝试了您的功能,它按预期工作。

标签: python dataframe matplotlib


【解决方案1】:

您的代码没有错误。这是我尝试过的:

import pandas as pd
import matplotlib.pyplot as plt

JP_df = pd.read_csv("temp.csv")
print(JP_df)
JP_df.plot(x='JP_genre', y='JP_sales', kind='bar')
plt.show()

将上面粘贴的数据保存到temp.csv后,运行完美。

您可能错的是 DataFrame 中 JP_sales 列的值的类型不是数值(即它们可以保存为字符串)。 在调用.plot() 之前,您可以尝试将第二列转换为浮点数,如下所示:

JP_df = JP_df.astype({"JP_genre": str, "JP_sales": float})
JP_df.plot(x='JP_genre', y='JP_sales', kind='bar')
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-24
    • 2015-10-09
    • 2018-08-04
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多