【发布时间】:2019-06-11 14:24:45
【问题描述】:
我是一个新手,正在尝试使用字典和 python 绘图。 我正在尝试创建一个简单的折线图,x 轴为国家名称,y 轴为人口。但是我收到此代码的错误:
#!/usr/bin/python
#
#Dictionary example
#
import sys
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
country_names = [ 'Germany', 'Italy', 'Netherlands', 'France'] #list of countries
capital_list =['Berlin', 'Rome', 'Amsterdam', 'Paris']#list of capitals to be mapped to countries
population_list= ['3.5','2.1', '0.3', '2.8'] #list of population of induvidual countries, all figures in Million
language_list=['German','Italian','Dutch','French'] #list of languages to be mapped to countries
dictionary_list = [ {'COUNTRY': country, 'CAPITAL': capital, 'POPULATION':population, 'LANGUAGE': lang} for country, capital, population, lang in zip(country_names, capital_list, population_list, language_list)]
#print(dictionary_list)
x = [d['CAPITAL'] for d in dictionary_list]
print x
y = [d['POPULATION'] for d in dictionary_list ]
print y
# create plot space upon which to plot the data
fig, ax = plt.subplots()
# add the x-axis and the y-axis to the plot
ax.plot(x, y);
这是错误:
['Berlin', 'Rome', 'Amsterdam', 'Paris']
['3.5', '2.1', '0.3', '2.8']
Traceback (most recent call last):
File "graph.py", line 29, in <module>
ax.plot(x, y);
File "/usr/lib/python2.7/dist-packages/matplotlib/__init__.py", line 1814, in inner
return func(ax, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 1425, in plot
self.add_line(line)
File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 1708, in add_line
self._update_line_limits(line)
File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 1730, in _update_line_limits
path = line.get_path()
File "/usr/lib/python2.7/dist-packages/matplotlib/lines.py", line 925, in get_path
self.recache()
File "/usr/lib/python2.7/dist-packages/matplotlib/lines.py", line 612, in recache
x = np.asarray(xconv, np.float_)
File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 482, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: could not convert string to float: Berlin
为什么 x 轴和 y 轴不能有不同的数据类型?为什么一定要把x轴转成float?
请帮忙。
谢谢
【问题讨论】:
标签: python matplotlib