Skip to main content
 首页 » 编程设计

Python:在 matplot 散点图的 x 轴上绘制字符串会产生 "could not convert string to float"

2024年10月25日28bluestorm

我有一个字典 aggregate_dict,它以字母 a:z 作为键,每个键都有一个列表,其中正好包含 0 到 1 之间的 11 个数值作为其关联值。我希望使用这些数据创建一个散点图,其中字母表中的字母在 x 轴上从 a 到 z 排列,给定字母的每个值在 y 轴上排列,如下所示:

我通常会在一秒钟内用 R 解决这个问题,但我正在使用的机器上没有 R,而且我没有管理员权限,所以我只能用 Python 来完成。我正在尝试通过以下方式解决这个问题(使用下面的简化字典):

from matplotlib import pyplot 
 
def scatterplot(x,y): 
    pyplot.plot(x,y,'b.') 
    pyplot.ylim(0,1) 
    pyplot.title("Relative Frequency of Letters") 
    pyplot.show() 
 
x_vals = [] 
y_vals = [] 
 
aggregate_dict = {'a':[.1,.2,.3],'b':[.2,.3,.4]} 
 
for u in aggregate_dict: 
    x_vals.append(u) 
    y_vals.append(aggregate_dict[u]) 
 
scatterplot( x_vals, y_vals ) 

不幸的是,这种方法会产生以下痕迹:

Traceback (most recent call last): 
  File "C:/Users/dduhaime/Desktop/letter_distributions_each_section_tale.py", line 74, in <module> 
    scatterplot(x_vals, y_vals ) 
  File "C:/Users/dduhaime/Desktop/letter_distributions_each_section_tale.py", line 56, in scatterplot 
    pyplot.plot(x,y,'b.') 
  File "C:\Python27\ArcGIS10.2\lib\site-packages\matplotlib\pyplot.py", line 2987, in plot 
    ret = ax.plot(*args, **kwargs) 
  File "C:\Python27\ArcGIS10.2\lib\site-packages\matplotlib\axes.py", line 4138, in plot 
    self.add_line(line) 
  File "C:\Python27\ArcGIS10.2\lib\site-packages\matplotlib\axes.py", line 1497, in add_line 
    self._update_line_limits(line) 
  File "C:\Python27\ArcGIS10.2\lib\site-packages\matplotlib\axes.py", line 1508, in _update_line_limits 
    path = line.get_path() 
  File "C:\Python27\ArcGIS10.2\lib\site-packages\matplotlib\lines.py", line 743, in get_path 
    self.recache() 
  File "C:\Python27\ArcGIS10.2\lib\site-packages\matplotlib\lines.py", line 420, in recache 
    x = np.asarray(xconv, np.float_) 
  File "C:\Python27\ArcGIS10.2\lib\site-packages\numpy\core\numeric.py", line 320, in asarray 
    return array(a, dtype, copy=False, order=order) 
ValueError: could not convert string to float: a 

有谁知道我如何解决这个错误并继续我的计划?如果您能提供任何建议,我将不胜感激!

请您参考如下方法:

import matplotlib.pyplot as plt 
from matplotlib.ticker import FuncFormatter, MultipleLocator 
 
x_data = np.arange(97, 110) 
y_data = np.random.rand(len(x_data)) 
 
def ord_to_char(v, p=None): 
    return chr(int(v)) 
 
fig, ax = plt.subplots() 
ax.plot(x_data, y_data, 'x') 
ax.xaxis.set_major_formatter(FuncFormatter(ord_to_char)) 
ax.xaxis.set_major_locator(MultipleLocator(1)) 
plt.show() 

相关文档:http://matplotlib.org/api/ticker_api.html#module-matplotlib.ticker