gpt4 book ai didi

python - 如何使用 matplotlib 从值列表生成直方图?

转载 作者:行者123 更新时间:2023-11-28 18:29:09 27 4
gpt4 key购买 nike

所以我一直在尝试使用 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

最佳答案

注意:假设您的文件包含多行(逗号分隔)并且每行的第一个条目是高度。

错误是当您将“数据”附加到 womenmen 列表时。 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])]

关于python - 如何使用 matplotlib 从值列表生成直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38873259/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com