所以我一直在尝试使用python和mathplotlib绘制直方图。 所以我有两个数据集,基本上是一个男性和女性样本的高度作为python中的列表,从csv文件导入。
我正在使用的代码:
import csv
import numpy as np
from matplotlib import pyplot as plt
men=[]
women=[]
with open('women.csv','r') as f:
r1=csv.reader(f, delimiter=',')
for row in r1:
women+=[row[0]]
with open('men.csv','r') as f:
r2=csv.reader(f, delimiter=',')
for row in r2:
men+=[row[0]]
fig = plt.figure()
ax = fig.add_subplot(111)
numBins = 20
ax.hist(men,numBins,color='blue',alpha=0.8)
ax.hist(women,numBins,color='red',alpha=0.8)
plt.show()
以及我得到的错误:
Traceback (most recent call last):
File "//MEME/Users/Meme/Miniconda3/Lib/idlelib/test.py", line 22, in <module>
ax.hist(men,numBins,color='blue',alpha=0.8)
File "\\MEME\Users\Meme\Miniconda3\lib\site-packages\matplotlib\__init__.py", line 1811, in inner
return func(ax, *args, **kwargs)
File "\\MEME\Users\Meme\Miniconda3\lib\site-packages\matplotlib\axes\_axes.py", line 5983, in hist
raise ValueError("color kwarg must have one color per dataset")
ValueError: color kwarg must have one color per dataset
答案 0 :(得分:1)
注意:假设您的文件包含多行(逗号分隔),每行中的第一个条目是高度。
错误是当你追加&#34;数据&#34;进入women
和men
列表。 row[0]
实际上是一个字符串。因此matplotlib很困惑。我建议你在绘制之前运行这段代码(python 2):
import csv
import numpy as np
from matplotlib import pyplot as plt
men=[]
women=[]
import pdb;
with open('women.csv','r') as f:
r1=csv.reader(f, delimiter=',')
for row in r1:
women+=[(row[0])]
with open('men.csv','r') as f:
r2=csv.reader(f, delimiter=',')
for row in r2:
men+=[(row[0])]
fig = plt.figure()
ax = fig.add_subplot(111)
print men
print women
#numBins = 20
#ax.hist(men,numBins,color='blue',alpha=0.8)
#ax.hist(women,numBins,color='red',alpha=0.8)
#plt.show()
示例输出
['1','3','3']
['2','3','1']
所以在循环中,你只需要从字符串转换为float或整数,例如women += [float(row[0])]
和men += [float(row[0])]