如何在matplotlib中绘制图形上的字符串值?

2024-05-14 06:52:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做数据分割,我有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()    

Tags: 数据代码importfordataas图表绘制
1条回答
网友
1楼 · 发布于 2024-05-14 06:52:32

如果要传递类型为str的对象作为^{}方法的第一个参数,请确保字符串的格式为整数或浮点

您可以尝试:

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

但请注意链接文档:

Warning

This function is deprecated and will be removed in a future version. >Please adapt your code to use one of two new functions:

displot(), a figure-level function with a similar flexibility over the kind of plot to draw

histplot(), an axes-level function for plotting histograms, including with kernel density smoothing

相关问题 更多 >

    热门问题