[英]matplotlib.pyplot.plot, ValueError: could not convert string to float: A
I want to plot the bar plot, here is the data: 我想绘制条形图,这是数据:
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]
And I want to plot 2 subplots to show each letters' number in each list, so here is my code 我想绘制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)
But it returned the following error: 但它返回以下错误:
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
How can I fix this problem? 我该如何解决这个问题? Thank you!
谢谢!
It tells you exactly what the problem is -- it's trying to convert the first argument to a number. 它确切地告诉您问题出在哪里-它正在尝试将第一个参数转换为数字。 Have a look at the documentation for
matplotlib.pyplot.bar
. 看一下
matplotlib.pyplot.bar
的文档 。 It's a bit unintuitive, but the first argument is a coordinate for the left side of the bar, not the label of the bar. 这有点不直观,但是第一个参数是条形图左侧的坐标,而不是条形图的标签。 I'm not sure, but you probably needing the
tick_label
argument to name the bars. 我不确定,但是您可能需要使用
tick_label
参数来命名条。
Try something like 尝试类似
# 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)
Like danielu13 says. 就像danielu13所说。 Something like this should work.
这样的事情应该起作用。
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.