张图南 发表于 2020-10-25 08:40:51

生成svg文件时报错,希望有人知道错误原因

写了一个掷骰子的代码,希望生成柱状图,但最后生成的svg文件是0kb。代码如下:
from random import randint

class Die():
    """a class of die"""
   
    def __init__(self,num_sides=6):
      """default 6 sides"""
      self.num_sides = num_sides
      
    def roll(self):
      """return a random number between 1 and die's sides"""
      return randint(1,self.num_sides)
…………………………………………………………
from die import Die
import pygal

#create a D6
die = Die()

#roll die a few times and restore result in a list
results = []
for roll_num in range(6000):
    result = die.roll()
    results.append(result)

#analsis result
frequencies = []
for value in range(1,die.num_sides+1):
    frequency = results.count(value)
    frequencies.append(frequency)


#visualize result
hist = pygal.Bar()

hist.title = "Results of rolling one D6 6000 times."
hist.x_labels = ['1','2','3','4','5','6']
hist.x_title = ["Result"]
hist.y_title = "Frenquency of Result"

hist.add('D6',frequencies)
hist.render_to_file('die_visual.svg')
发生了报错,报错代码如下:
Traceback (most recent call last):
File "die_visual.py", line 29, in <module>
    hist.render_to_file('die_visual.svg')
File "C:\Users\asus\AppData\Roaming\Python\Python38\site-packages\pygal\ghost.py", line 165, in render_to_file
    f.write(self.render(is_unicode=True, **kwargs))
File "C:\Users\asus\AppData\Roaming\Python\Python38\site-packages\pygal\ghost.py", line 121, in render
    return (self
File "C:\Users\asus\AppData\Roaming\Python\Python38\site-packages\pygal\ghost.py", line 114, in make_instance
    self._last__inst = self.cls(
File "C:\Users\asus\AppData\Roaming\Python\Python38\site-packages\pygal\graph\bar.py", line 37, in __init__
    super(Bar, self).__init__(*args, **kwargs)
File "C:\Users\asus\AppData\Roaming\Python\Python38\site-packages\pygal\graph\base.py", line 74, in __init__
    self._draw()
File "C:\Users\asus\AppData\Roaming\Python\Python38\site-packages\pygal\graph\base.py", line 291, in _draw
    self._compute_margin()
File "C:\Users\asus\AppData\Roaming\Python\Python38\site-packages\pygal\graph\base.py", line 159, in _compute_margin
    self.x_title = split_title(
File "C:\Users\asus\AppData\Roaming\Python\Python38\site-packages\pygal\util.py", line 435, in split_title
    title_lines = title.split("\n")
AttributeError: 'list' object has no attribute 'split'

suchocolate 发表于 2020-11-22 19:05:43

没用过这个库,不过这个似乎应该去掉[]:
hist.x_title = "Result"
页: [1]
查看完整版本: 生成svg文件时报错,希望有人知道错误原因