在python中创建饼图和数组时出错
我正在进行一项癌细胞研究,我正试图制作一个饼图来显示有丝分裂X死亡百分比。因此,我有一个名为有丝分裂事件的数组和另一个名为死亡事件的数组,下面是我的代码:在python中创建饼图和数组时出错,python,arrays,pie-chart,Python,Arrays,Pie Chart,我正在进行一项癌细胞研究,我正试图制作一个饼图来显示有丝分裂X死亡百分比。因此,我有一个名为有丝分裂事件的数组和另一个名为死亡事件的数组,下面是我的代码: import matplotlib.pyplot as plt mitotic_events[get_generation_number(cell)] += 1 death_events[len(cell)-1] += 1 #Simple Pie chart # The slices will be ordered and plotte
import matplotlib.pyplot as plt
mitotic_events[get_generation_number(cell)] += 1
death_events[len(cell)-1] += 1
#Simple Pie chart
# The slices will be ordered and plotted counter-clockwise.
labels = 'Mitosis', 'Deaths'
sizes = [mitotic_events, death_events]
colors = ['Green', 'Red' ]
explode = (0, 0.1) # only "explode" the 2nd slice (i.e. 'Hogs')
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.show()
我在控制台中得到这个错误:
TypeError: only length-1 arrays can be converted to Python scalars
我想知道解决办法是什么?我知道问题出在这方面:
sizes = [mitotic_events, death_events]
在advanced中感谢您,您的代码没有完全显示
有丝分裂事件
或死亡事件
的定义,因为这些事件使用的get\u generation\u number()
和cell
未在代码段中定义。您也不会显示前两个变量是如何创建的——您只会显示它们是如何更新的。然而,我们从声明中看到
mitotic_events[get_generation_number(cell)] += 1
death_events[len(cell)-1] += 1
有丝分裂事件和死亡事件都是列表。然后定义
sizes = [mitotic_events, death_events]
因此,size
是一个列表列表。然后尝试将size
作为第一个参数传递给pyplot的pie()
函数
但是,pie()
的第一个参数必须是数字数组或数字列表。这意味着,但并没有说得很清楚,但事实证明,情况必须如此。当pyplot读取size
时,它查看size
列表中的第一项,发现它不是一个数字(标量),而是一个列表。Pyplot显然试图将内部列表mitotic_events
更改为标量,但它是一个长度大于1的列表,因此转换失败。Pyplot然后会向您提供一条没有多大帮助的错误消息
解决方案是构造大小
,因此它是一个数字列表。也许你应该用
sizes = mitotic_events + death_events
要正确组合这两个列表,可能需要将其他参数更改为
pie()
。您没有提供足够的信息让我说得更多。请尝试至少用print调试您的代码。另外,你可以用谷歌搜索你的错误并找到答案。我显然用谷歌搜索了一下,但与我的请求无关+我知道错误在这一行“大小=[mitotic_events,death_events]”你的代码片段不完整,因为你没有显示mitotic_events
和death_events
和plt
(虽然最后一个是显而易见的)。看。@RoryDaulton我现在已经修复了它。我只是把错误文本放到谷歌上,然后找到类似的主题,你也可以这样做。