Example #1
0
 def test_bar():
     bar = Bar()
     bar.add('1', [1, 2, 3])
     bar.add('2', [4, 5, 6])
     return bar.render_response()
Example #2
0
 def test_multiline_title():
     bar = Bar()
     bar.add('Looooooooooooooooooooooooooooooooooong', [2, None, 12])
     bar.title = ('First line \n Second line \n Third line')
     return bar.render_response()
Example #3
0
 def test_bar_none():
     bar = Bar()
     bar.add('Lol', [2, None, 12])
     return bar.render_response()
Example #4
0
        except ValueError:
            dice.append(6)
            incorrect_input = True
    if incorrect_input:
        print('Some of the values, incorrect, have been replaced with the default value of 6.')
else:
    print('You did not enter any value, a single standard six-sided die will be rolled.')
    dice = [6]
print()

try:
    nb_of_rolls = int(input('Enter the desired number of rolls: '))
    if nb_of_rolls < 1:
        raise ValueError
except ValueError:
    print('Input was not provided or invalid, so the default value of 1,000 will be used.')
    nb_of_rolls = 1_000

rolls = [sum(randint(1, nb_of_sides) for nb_of_sides in dice) for _ in range(nb_of_rolls)]
range_of_sums = range(len(dice), sum(dice) + 1)
counts = [rolls.count(i) for i in range_of_sums]
counts = [{'value': count, 'label': f'Frequency: {count / nb_of_rolls:.2f}'} for count in counts]
histogram = Bar(style = Style(colors = ('#228B22',), major_label_font_size = 12),
                show_legend = False)
histogram.title = f'Simulation for {nb_of_rolls} rolls of the dice: {sorted(dice)}'
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')
Example #5
0
 def test_bar_none():
     bar = Bar()
     bar.add('Lol', [2, None, 12])
     bar.x_labels = range(1, 4)
     return bar.render_response()
Example #6
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')
Example #7
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')
Example #8
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')
Example #9
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")
Example #10
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"))