簡體   English   中英

matplotlib.pyplot.plot,ValueError:無法將字符串轉換為float:A

[英]matplotlib.pyplot.plot, ValueError: could not convert string to float: A

我想繪制條形圖,這是數據:

large_letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
large_num = [52909, 52911, 52912, 52911, 52912, 52912, 52912, 52912, 52912, 52911]
small_letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
small_num = [1872, 1873, 1873, 1873, 1873, 1872, 1872, 1872, 1872, 1872]

我想繪制2個子圖,以在每個列表中顯示每個字母的數字,所以這是我的代碼

import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.bar(large_letter, large_num)
ax2.bar(small_letter, small_num)

但它返回以下錯誤:

ValueErrorTraceback (most recent call last)
<ipython-input-90-e23f798dd50c> in <module>()
     20 fig, (ax1, ax2) = plt.subplots(1, 2)
---> 21 ax1.bar(large_letter, large_num)
     22 ax2.bar(small_letter, small_num)

/usr/lib64/python2.7/site-packages/matplotlib/__init__.pyc in inner(ax, *args, **kwargs)
   1817                     warnings.warn(msg % (label_namer, func.__name__),
   1818                                   RuntimeWarning, stacklevel=2)
-> 1819             return func(ax, *args, **kwargs)
   1820         pre_doc = inner.__doc__
   1821         if pre_doc is None:

/usr/lib64/python2.7/site-packages/matplotlib/axes/_axes.pyc in bar(self, left, height, width, bottom, **kwargs)
   2085                 edgecolor=e,
   2086                 linewidth=lw,
-> 2087                 label='_nolegend_'
   2088                 )
   2089             r.update(kwargs)

/usr/lib64/python2.7/site-packages/matplotlib/patches.pyc in __init__(self, xy, width, height, angle, **kwargs)
    638         Patch.__init__(self, **kwargs)
    639 
--> 640         self._x = float(xy[0])
    641         self._y = float(xy[1])
    642         self._width = float(width)

ValueError: could not convert string to float: A

我該如何解決這個問題? 謝謝!

它確切地告訴您問題出在哪里-它正在嘗試將第一個參數轉換為數字。 看一下matplotlib.pyplot.bar文檔 這有點不直觀,但是第一個參數是條形圖左側的坐標,而不是條形圖的標簽。 我不確定,但是您可能需要使用tick_label參數來命名條。

嘗試類似

# Specify the width of each of the bars since we need it for calculating left of
# bars. The default is 0.8
width = 1.0

# Find the lefts of the bars. You can change this to leave a gap between bars
lefts = [x * width for x, _ in enumerate(large_num)]

# Create bar graph
ax1.bar(lefts, large_num, width=width, tick_label=large_letter)

就像danielu13所說。 這樣的事情應該起作用。

ax1.bar(range(len(large_letter)), large_num, tick_label=large_letter)
ax2.bar(range(len(small_letter)), small_num, tick_label=small_letter)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM