Esempio n. 1
0
def genSvg(fpath, mathd, biologyd):
    keys = ['0-59']
    [keys.append('%d-%d' % (val, val + 9 + (val / 90))) for val in range(60, 100, 10)]
    # print(keys, type(keys))
    # ['0-59', '60-69', '70-79', '80-89', '90-100'] <class 'list'>

    line_chart = Bar()
    # print(line_chart, type(line_chart))
    # <pygal.graph.bar.Bar object at 0x02F24330> <class 'pygal.graph.bar.Bar'>

    line_chart.title = 'Score Spread'
    # print(line_chart.title, type(line_chart.title))
    # Score Spread <class 'str'>

    line_chart.x_labels = keys
    # print(line_chart.x_labels, type(line_chart.x_labels))
    # ['0-59', '60-69', '70-79', '80-89', '90-100'] <class 'list'>

    line_chart.add('math', mathd.values())
    line_chart.add('biology', biologyd.values())
    # print(mathd, type(mathd))
    # {'0-59': 3, '60-69': 2, '70-79': 3, '80-89': 0, '90-100': 2} <class 'dict'>
    # print(mathd.values(), type(mathd.values()))
    # dict_values([3, 2, 3, 0, 2]) <class 'dict_values'>

    line_chart.render_to_file(fpath)
Esempio n. 2
0
def show_one_die_bar(numbers, num_sides=6):
    """投掷骰子numbers次,看每个面出现的次数,用直方图显示结果"""
    die = Die(num_sides)
    results = []
    title_num_sides = "D" + str(num_sides)

    # 投掷骰子,把结果保存在results中
    for number in range(numbers):
        results.append(die.roll())

    # 分析结果
    frequencies = []
    for value in range(1, die.num_sides+1):
        frequencies.append(results.count(value))

    # 显示结果在Console窗口
    #print(results)
    #print(frequencies)

    # 对结果可视化
    hist = Bar()
    
    hist.title = "Results of rolling one " + title_num_sides + " " + str(numbers) + " times"
    hist.x_labels = [str(num) for num in range(1,num_sides + 1)]
    hist.x_title = "Result"
    hist.y_title = "Frequency of Result"

    hist.add(title_num_sides, frequencies)
    hist.render_to_file("die_visual_" + title_num_sides + "_"
                        + str(numbers) + ".svg")
Esempio n. 3
0
    def getBar(self):
        from pygal import Bar
        path = os.path.join(base_path, 'pygal_js', 'javascripts', 'bar', 'bar_chart.svg')
        config.width = 500
        config.height = 400
        bar_chart = Bar(config, width=400, height=300, legend_box_size=10)
        bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])  # Add some values
        bar_chart.render_to_file(path)
        #fileio = StringIO()
        #im.save(fileio, 'svg')
        ##im.save('img.gif', 'gif')
        #im.show()
        #return ''.join(char), fileio

        return os.path.join(SVG_PATH, 'bar', 'bar_chart.svg')
Esempio n. 4
0
def main():
    # Set the dice up
    numSides = 20
    die1 = Die(numSides)
    die2 = Die(numSides)

    numRolls = 100000

    # Roll the die numRoll times and store the sum of the two.
    results = []

    for roll in range(numRolls):
        result = die1.roll() + die2.roll()
        results.append(result)

    # Anaylizing the results from above.
    frequencies = []

    maxResult = die1.numSides + die2.numSides
    for value in range(2, maxResult + 1):
        frequency = results.count(value)
        frequencies.append(frequency)

    # Create a graph from the results.
    graph = Bar()

    graph.title = f'Results of rolling two D{numSides} die {numRolls} times.'

    # Create the x labels
    graph.x_labels = []
    for x in range(2, maxResult + 1):
        graph.x_labels.append(f'{x}')

    # Add axii titles.
    graph.x_title = 'Result'
    graph.y_title = 'Frequency of Result'

    graph.add(f'D{numSides} + D{numSides}',
              frequencies)  # Add teh frequencies to the graph

    # Get the script directory and add the file name to it.
    filePath = f'{path.dirname(__file__)}/d{numSides}_dice_simulation.svg'
    graph.render_to_file(filePath)  # Create the visual file.
Esempio n. 5
0
def show_two_die_bar(numbers, num_sides1=6, num_sides2=6):
    """投掷骰子numbers次,看每个面出现的次数,用直方图显示结果"""
    die1 = Die(num_sides1)
    title_num_sides1 = "D" + str(num_sides1)

    die2 = Die(num_sides2)
    title_num_sides2 = "D" + str(num_sides2)

    results = []
    # 投掷两个骰子,把相加结果保存在results中
    for number in range(numbers):
        results.append(die1.roll() + die2.roll())

    # 分析结果
    max_result = num_sides1 + num_sides2
    min_result = 2

    frequencies = []
    for value in range(min_result, max_result+1):
        frequencies.append(results.count(value))

    # 显示结果在Console窗口
    #print(results)
    #print(frequencies)

    # 对结果可视化
    hist = Bar()
    
    if title_num_sides1 == title_num_sides2:
        hist.title = ("Results of rolling two " + title_num_sides1 
                      + " " + str(numbers) + " times")
    else:
        hist.title = ("Results of rolling one " + title_num_sides1
                     + " and one " + title_num_sides2 + " " + str(numbers) + " times")
        
    hist.x_labels = [str(num) for num in range(min_result, max_result+1)]
    hist.x_title = "Result"
    hist.y_title = "Frequency of Result"

    hist.add(title_num_sides1 + " + " + title_num_sides2, frequencies)
    hist.render_to_file("die_visual_" + title_num_sides1 + "_" 
                        + title_num_sides2 + "_" + str(numbers) + ".svg")
Esempio n. 6
0
class DiceGraph(PyDice):
    '''
    Utiliza a classe Pygal e PyDicepara gerar gráfico 
    baseado na frequência dos dados.
    '''
    def __init__(self, sides=6, dice=2, shooter=360):
        super().__init__(sides, dice, shooter)
        self.come_out_roll = self.come_out_roll()
        self.dice_freq = self.dice_freq()
        self.chart = Bar(print_values=True,
                         print_values_position='top',
                         print_zeroes=False,
                         style=custom_style)

    def dice_graphics(self):
        '''
        Retorna um gráfico de barras contído de média, mediana e
        desvio padrão.
        '''
        dice_mean = round(mean(self.dice_freq), 2)
        dice_median = round(median(self.dice_freq), 2)
        dice_desvpa = round(stdev(self.dice_freq), 2)

        self.chart.title = "Resultado obtido ao jogar " + str(self.dice) + \
            " dado(s) D" + str(self.sides) + " " + \
            str(self.shooter) + " vez(es)."

        self.chart.x_labels = list(range(self.dice, self.max_results + 1))
        self.chart.x_title = "Resultado\n" + "Média " + str(dice_mean) + "," \
            " Mediana " + str(dice_median) + "," \
            " Desvio padrão " + str(dice_desvpa) + "."

        self.chart.y_title = 'Frequência'
        self.chart.add('Dados', self.dice_freq)
        self.chart.render_to_file('rcg_chart_resultado.svg')

    def terminal(self):
        '''Classe que exibe os resultados em texto.'''
        print('Dados sorteados:      ' + str(self.come_out_roll[:11]))
        print('Frequência dos dados: ' + str(self.dice_freq))
Esempio n. 7
0
    def get(self):
        from pygal import Bar
        path = os.path.join(base_path, 'pygal_js', 'javascripts', 'bar', 'bar_chart.svg')
        config.width = 500
        config.height = 400
        #bar_chart = Bar(config, width=400, height=300, legend_box_size=10)
        args = self.args
        for k, v in args.items():
            if v.isdigit():
                args[k] = int(v)
        bar_chart = Bar(config, **args)
        data = self.args.get("data", "")
        x_labels = self.args.get("x_labels", "")
        bar_chart.add('Fibonacci', [int(i) for i in data.split(",")])  # Add some values
        bar_chart.x_labels = x_labels.split(",")
        bar_chart.render_to_file(path)
        #fileio = StringIO()
        #im.save(fileio, 'svg')
        ##im.save('img.gif', 'gif')
        #im.show()
        #return ''.join(char), fileio

        return self.write(simplejson.dumps({"data":os.path.join(SVG_PATH, 'bar', 'bar_chart.svg')}))
Esempio n. 8
0
            'xlink': f"https://news.ycombinator.com/item?id={id_article}"
        }
        articles.append(about_article)

# сортируем список статей по кол-ву комментариев
articles = sorted(articles, key=itemgetter('value'), reverse=True)
print(articles)

# формируем список из названий статей
names = []
for article in articles:
    names.append(article['label'])

# задание стилей для диаграммы
my_config = Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.truncate_label = 25  # сокращение длинных названий проектов
my_config.show_y_guides = False  # скроем горизонтальные линии
my_config.width = 1300
my_style = style.LightenStyle('#333366', base_style=style.LightColorizedStyle)
my_style.label_font_size = 16
my_style.major_label_font_size = 20

# построение визуализации
chart = Bar(my_config, style=my_style)
chart.title = "Активные обсуждения на Hack News"
chart.x_labels = names
chart.add('', articles)
chart.render_to_file("popular_articles_hack_news.svg")
Esempio n. 9
0
from die import Die
from pygal import Bar

die_1 = Die()
die_2 = Die()

times = 10**7

results = [die_1.roll() * die_2.roll() for _ in range(times)]

max_result = die_1.sides * die_2.sides
frequencies = [results.count(value) for value in range(1, max_result + 1)]

hist = Bar()

hist.title = 'Product among two D6 dice ' + str(times) + ' times'
hist.x_labels = [str(i) for i in range(1, max_result + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'

hist.add('D6 x D6', frequencies)
hist.render_to_file('md.svg')
Esempio n. 10
0
die_1 = Die()
die_2 = Die(10)

#Roll the dice some times and stores it in a list
results = []
for roll_num in range(50000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

#Analise the results
max_result = die_1.sides + die_2.sides
frequencies = []
for value in range(2, max_result + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

hist = Bar()

hist.title = 'Result of rolling a D6 and a D10 50.000 times'
hist.x_labels = [str(i) for i in range(2, max_result + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'

hist.add('D6 + D10', frequencies)
hist.render_to_file('different_dice_visual.svg')

sum = 0
for frequency in frequencies:
    sum += frequency

print(sum)
                          key=itemgetter('stargazers_count'),
                          reverse=True)

# получение данных для построения визуализации
names, stars_labels = [], []
for repository in all_repositories[:20]:
    names.append(f"{repository['name']} ({repository['language']})")
    stars_labels.append({
        'value': repository['stargazers_count'],
        'label': repository['description'],
        'xlink': repository['html_url']
    })

# задание стилей для диаграммы
my_config = Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.truncate_label = 15  # сокращение длинных названий проектов
my_config.show_y_guides = False  # скроем горизонтальные линии
my_config.width = 1300
my_style = style.LightenStyle('#333366', base_style=style.LightColorizedStyle)
my_style.label_font_size = 16
my_style.major_label_font_size = 20

# построение визуализации
chart = Bar(my_config, style=my_style)
chart.title = "Наиболее популярные проекты на разных языках (GitHub)"
chart.x_labels = names
chart.add('', stars_labels)
chart.render_to_file("popular_projects_on_github.svg")
Esempio n. 12
0
from die import Die
from pygal import Bar

die_1 = Die(8)
die_2 = Die(8)

times = 1000000

results = [die_1.roll() + die_2.roll() for _ in range(times)]

max_result = die_1.sides + die_2.sides
frequencies = [results.count(value) for value in range(2, max_result + 1)]

hist = Bar()

hist.title = 'Roll of a D8 and a D8 ' + str(times) + ' times'
hist.x_labels = [str(i) for i in range(2, max_result + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'

hist.add('D8 + D8', frequencies)
hist.render_to_file('d8.svg')
Esempio n. 13
0
from die import Die
from pygal import Bar

#Creates two D6 dice (D6 == die of 6 sides)
die = Die()

times = 1000

#Roll the die and store the results in a list
results = [die.roll() for roll_num in range(times)]

#Analize the results
frequencies = [results.count(value) for value in range(1, die.sides + 1)]

#Visualizes the results
hist = Bar()

hist.title = 'Results of rolling one D6 die ' + str(times) + ' times'
hist.x_labels = [str(i) for i in range(1, 7)]
hist.x_title = 'Sides'
hist.y_title = 'Frequency of Side'

#add will add automatically the y_labels
hist.add('D6', frequencies)
hist.render_to_file('die_visual.svg')
Esempio n. 14
0
 def show_walk(self):
     hist = Bar()
     hist.title = 'Random Walk'
     hist.add('X Values', self.x_values)
     hist.add('Y Values', self.y_values)
     hist.render_to_file('randomwalk.svg')
Esempio n. 15
0
xlab = []
items = []
begin = lb
end = ub
while count[begin] == 0:
    begin += 1
while count[end] == 0:
    end -= 1
for i in range(begin, end):
    xlab.append(i)
    dic = {"value": count[i],
           "label": f"Frequency: {count[i] / n:.2f}"}
    items.append(dic)
#
# Render
barch = Bar()
barch.title = f"Simulation for {n} rolls of the dice: {dice}"
barch.x_labels = xlab
barch.x_title = "Possible sums"
barch.y_title = "Counts"
barch.show_legend = False
barch.force_uri_protocol = "http"
barch.add('', items)
barch.style = Style(colors=("#228B22",),
                    label_font_size=12)
barch.render()
barch.render_to_file("dice_rolls.svg")
#
# Open browser window
open_new_tab("file://" + path.realpath("dice_rolls.svg"))
Esempio n. 16
0
                a_b_fighter_num[0] = 0

    if a_b_alive_num[0] > 0:
        print('a win!')
        return a_b_alive_num[0] * 1
    elif a_b_alive_num[1] > 0:
        print('b win!')
        return a_b_alive_num[1] * (-1)
    else:
        print('tie!')
        return 0


pygame.init()
screen = pygame.display.set_mode((600, 120))
pygame.display.set_caption('progress')
rect = pygame.Rect(10, 10, 0, 100)
result = [0 for num in range(0, 15)]
for num in range(0, 7000):
    check_event()
    rect.width = int(580 * (num + 1) / 7000)
    pygame.draw.rect(screen, (255, 255, 255), rect)
    result[check() + 7] += 1
    pygame.display.update()

hist = Bar()
hist.title = 'a:[[100,100,n],[5,5,p],[4,4,s],[3,3,st],[2,2,p],[7,700,pt],[6,6,pst]]\n' + 'b:[[5,5,p],[2,2,p],[4,4,s],[100,100,n],[3,3,st],[7,700,pt],[6,6,pst]]'

hist.add('result', result)
hist.render_to_file('result_1.svg')
Esempio n. 17
0
from throw_dice.die import Die
from pygal import Bar

# создание кубиков
die_1 = Die(8)
die_2 = Die(8)

# моделирование серии бросков с сохранением данных
max_throws = 10000
results = [die_1.roll() + die_2.roll() for roll_num in range(max_throws)]
print(results)

# анализ результатов
max_result = die_1.num_sides + die_2.num_sides
frequencies = [results.count(value) for value in range(2, max_result + 1)]
print(frequencies)

# визуализация результатов
histogram = Bar()
histogram.title = f"Результаты брасания двух кубиков {max_throws} раз"
histogram.x_labels = [num for num in range(2, max_result + 1)]
histogram.x_title = "Сумма выпадений"
histogram.y_title = "Количество выпадений"
histogram.add("Сумма граней кубиков", frequencies)
histogram.render_to_file('dice_visual.svg')
Esempio n. 18
0
from die import Die
from pygal import Bar

die_1 = Die()
# 十面骰子
die_2 = Die(10)
results = []
frequencies = []
for roll in range(10000):
    result = die_1.roll() + die_2.roll()
    results.append(result)
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

hist = Bar()
hist.title = "Results of rolling a D6 and a D10 10000 times."
# 随着数据的增大,最好利用循环生成x坐标列表
hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
hist.x_title = "Result"
hist.y_title = "Frequency of Results"
hist.add("D6+D10", frequencies)
hist.render_to_file("die_simulation_pro.svg")
Esempio n. 19
0
from gen import gen_results
from pygal import Bar



times = 5000000


results = [result for result in gen_results(times)]

max_result = 3 * 6
frequencies = [results.count(value) for value in range(3, max_result+1)]


hist = Bar()
hist.title = 'Roll of three D6 ' + str(times) + ' times'
hist.x_labels = [str(i) for i in range(3, max_result+1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of result'

hist.add('D6 + D6 + D6', frequencies)
hist.render_to_file('three_d6_visual.svg')





else:
    roll = 2000
    print(
        'Input was not provided or invalid, so the default value of 1,000 will be used.'
    )

L = sorted(L)

result = []
for i in range(roll):
    sums = 0
    for j in range(len(L)):
        sums += randint(1, L[j])
    result.append(sums)

range_of_sums = list(set(result))
counts = [result.count(i) for i in range_of_sums]
counts = [{
    'value': count,
    'label': f'Frequency: {count / roll:.2f}'
} for count in counts]

histogram = Bar(style=Style(colors=('#228B22', ), major_label_font_size=12),
                show_legend=False)
histogram.title = f'Simulation for {roll} rolls of the dice: {sorted(L)}'
histogram.x_labels = [str(i) for i in range_of_sums]
histogram.x_title = 'Possible sums'
histogram.y_title = 'Counts'
histogram.add('', counts)
histogram.render_to_file('dice_rolls.svg')
Esempio n. 21
0
    """Determine a value based on its percentage."""
    p_index = int(p * len(x))
    return str(sorted(x)[p_index])


##############
# Dispersion #
##############
def data_range(x):
    return str(max(x) - min(x))

# Execute tests and save the results.
with open('data.txt', 'w') as f:
    f.write('Two D6 Analysis')
    f.write('\nMean result: ' + mean(results))
    f.write('\nMedian result: ' + median(results))
    f.write('\nQuantile result: ' + quantile(results, .90))
    f.write('\nData Range: ' + data_range(results))


# Visualize the results.
hist = Bar()

hist.title = 'Results of rolling 2d6 1,000,000 times.'
hist.x_labels = [i for i in range(2, die1.num_sides * 2 + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'

hist.add('2d6', frequencies)
hist.render_to_file('test.svg')