【问题标题】:How to plot the string values on the graph in matplotlib?如何在 matplotlib 的图形上绘制字符串值?
【发布时间】:2021-08-11 10:00:11
【问题描述】:

我正在做数据分割,我有 1200 行和 17 列的大量数据。我想为国家和人口的整个数据绘制图表。

当我尝试使用以下代码时出现错误:

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

代码:

import pandas as pd # for dataframes
import matplotlib.pyplot as plt # for plotting graphs
import seaborn as sns # for plotting graphs
import datetime as dt

data = pd.read_excel("TestData.xls")

plt.figure(1, figsize=(15, 6))
n=0

for x in ['Country', 'Product', 'Sales']:
    n += 1
    plt.subplot(1,3,n)
    plt.subplots_adjust(hspace=0.5, wspace=0.5)
    sns.distplot(data[x], bins=20)
    plt.title('Displot of {}'.format(x))
plt.show()    

【问题讨论】:

  • 错误太简单了,你不能使用 distplot 绘制分类值,你可以使用 countplot 来绘制分类特征
  • 请显示TestData.xls的上下文。
  • 另外请记住,seaborn distplot 很快就会被弃用。您可能想切换到displothistplot

标签: python pandas dataframe matplotlib data-science


【解决方案1】:

如果您将str 类型的对象作为seaborn.distplot() 方法中的第一个参数传递,请确保字符串的格式为整数或浮点数。

你可以试试:

import pandas as pd # for dataframes
import matplotlib.pyplot as plt # for plotting graphs
import seaborn as sns # for plotting graphs
import datetime as dt

data = pd.read_excel("TestData.xls")

plt.figure(1, figsize=(15, 6))
n=0

for x in ['Country', 'Product', 'Sales']:
    n += 1
    plt.subplot(1,3,n)
    plt.subplots_adjust(hspace=0.5, wspace=0.5)
    a = data[x]
    if a.replace('.', '', 1).isdigit():
        sns.distplot(a, bins=20)
    else:
        print(f"{a} is not a float.")
    plt.title('Displot of {}'.format(x))
plt.show()    

但请注意链接文档:

警告

此功能已弃用,将在未来版本中删除。 >请调整您的代码以使用两个新功能之一:

displot(),一个图形级函数,在绘制的绘图类型上具有类似的灵活性

histplot(),用于绘制直方图的轴级函数,包括核密度平滑

【讨论】:

  • 嗨,我遇到了错误。 f'对于参数“{arg_name}”预期类型 bool,接收到 'ValueError:对于参数“就地”预期类型 bool,接收类型 int。
  • @ADSKUL 这有帮助吗? stackoverflow.com/q/49265766/13552470
  • 让我看看@Ann Zen。
猜你喜欢
  • 2012-02-24
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 2016-09-22
  • 2020-02-28
  • 2014-11-02
相关资源
最近更新 更多