【问题标题】:Python: Plotting strings on x axis of matplot scatterplot yields "could not convert string to float"Python:在 matplot 散点图的 x 轴上绘制字符串会产生“无法将字符串转换为浮点数”
【发布时间】:2014-09-02 18:49:42
【问题描述】:

我有一个字典aggregate_dict,其中有字母 a:z 作为键,每个键都有一个列表,其中正好包含 11 个介于 0 和 1 之间的数值作为其关联值。我希望使用这些数据创建一个散点图,其中字母表中的字母在 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

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

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:
    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

    【讨论】:

    • 优秀的@tcaswell!有没有办法为 x 轴上的每个刻度或值绘制多个值,以便 x 轴上的每个字母有 3+ 个值?
    • plot 在每个 (x, y) 对上放置一个点,只是将 x 值增加三倍(所以它看起来像 x = [97, 97, 97, 98, 98, 98]y = range(6)
    • 完美——让我到达那里!我没有意识到使用 ord() 将 str 转换为 int 是多么容易!多么有用的方法!谢谢!
    • 对不起,应该包括那个细节
    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 2019-03-01
    • 2021-01-11
    • 2018-04-23
    • 2020-11-19
    相关资源
    最近更新 更多