示例#1
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()
示例#2
0
 def test_long_labels():
     bar = Bar()
     bar.add("Long", [2, None, 12])
     bar.title = "1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890"
     bar.x_labels = "a" * 100, "b " * 50, "cc ! " * 20
     bar.x_label_rotation = 45
     return bar.render_response()
示例#3
0
def static_pcap():
    if request.method == 'POST':
        #temporarily store upload pcap file
        print request
        traceFile = request.files['file']
        traceFile.save("temporary/temp_pcap_file.pcap")

        ft = filter_static.Static_Filter(
            fileName="temporary/temp_pcap_file.pcap")
        device_traffic_dict = ft.detect_Device()

        #line chart for individual device data sent historys
        pkt_line = XY(width=800, height=600, explicit_size=True)
        pkt_line.title = 'Device Package Curve'
        for key, list in device_traffic_dict.iteritems():
            pkt_line.add(key, list)
        chart = pkt_line.render()

        # bar chart for device data sent summary
        pkt_Bar = Bar(width=800, height=600, explicit_size=True)
        pkt_Bar.title = 'Device Package Sum'
        for key, list in device_traffic_dict.iteritems():
            zipped = map(sum, zip(*list))
            pkt_Bar.add(key, zipped[1])
        pkt_Bar = pkt_Bar.render()

        del ft
        html = """{} {}""".format(chart, pkt_Bar)
        return html

    else:
        return current_app.send_static_file('static.html')
示例#4
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)
示例#5
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")
示例#6
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()
示例#7
0
def statistics():
    """ Page display data visualization about statistics for the recipes """

    # Count how many recipes have each meal time to send to the pie chart
    breakfast = mongo.db.recipes.find({'meal_time': 'breakfast'}).count()
    lunch = mongo.db.recipes.find({'meal_time': 'lunch'}).count()
    dinner = mongo.db.recipes.find({'meal_time': 'dinner'}).count()

    # Build pie chart
    pie_chart = Pie()
    pie_chart.title = 'Meal Times'
    pie_chart.add('Breakfast', breakfast)
    pie_chart.add('Lunch', lunch)
    pie_chart.add('Dinner', dinner)
    pie_chart = pie_chart.render_data_uri()

    # Count how many recipes have each training type to send to line chart
    endurance = mongo.db.recipes.find({'training_type': 'endurance'}).count()
    speed = mongo.db.recipes.find({'training_type': 'speed'}).count()
    strength = mongo.db.recipes.find({'training_type': 'strength'}).count()
    power = mongo.db.recipes.find({'training_type': 'power'}).count()

    # Build line chart
    line_chart = Bar()
    line_chart.title = 'Training Types'
    line_chart.add('Endurance', [{'value': endurance, 'label': 'Endurance'}])
    line_chart.add('Strength', [{'value': strength, 'label': 'Strength'}])
    line_chart.add('Power', [{'value': power, 'label': 'Power'}])
    line_chart.add('Speed', [{'value': speed, 'label': 'Speed'}])
    line_chart = line_chart.render_data_uri()

    return render_template('statists.html',
                           title='Statistics',
                           pie_chart=pie_chart,
                           line_chart=line_chart)
示例#8
0
文件: tests.py 项目: wuzesheng/pygal
 def test_long_labels():
     bar = Bar()
     bar.add('Long', [2, None, 12])
     bar.title = (
         '1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890')
     bar.x_labels = 'a' * 100, 'b ' * 50, 'cc ! ' * 20
     bar.x_label_rotation = 45
     return bar.render_response()
示例#9
0
 def test_long_labels():
     bar = Bar()
     bar.add('Long', [2, None, 12])
     bar.title = (
         '1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890')
     bar.x_labels = 'a' * 100, 'b ' * 50, 'cc ! ' * 20
     bar.x_label_rotation = 45
     return bar.render_response()
示例#10
0
def test_chart_renders():
    line_chart = Bar(print_values=True, percent_values=True, print_values_position='top')
    line_chart.title = 'Browser usage evolution (in %)'
    line_chart.x_labels = map(str, range(2002, 2013))
    line_chart.add('Firefox', [None, None, 0, 16.6, 25, 31, 36.4, 45.5, 46.3, 42.8, 37.1])
    line_chart.add('Chrome', [None, None, None, None, None, None, 0, 3.9, 10.8, 23.8, 35.3])
    line_chart.add('IE', [85.8, 84.6, 84.7, 74.5, 66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1])
    line_chart.add('Others', [14.2, 15.4, 15.3, 8.9, 9, 10.4, 8.9, 5.8, 6.7, 6.8, 7.5])
    assert line_chart.render()
示例#11
0
def test_chart_renders():
    """Tests that print values and percent values renders"""
    line_chart = Bar(print_values=True, percent_values=True, print_values_position='top')
    line_chart.title = 'Browser usage evolution (in %)'
    line_chart.x_labels = map(str, range(2002, 2013))
    line_chart.add('Firefox', [None, None, 0, 16.6, 25, 31, 36.4, 45.5, 46.3, 42.8, 37.1])
    line_chart.add('Chrome', [None, None, None, None, None, None, 0, 3.9, 10.8, 23.8, 35.3])
    line_chart.add('IE', [85.8, 84.6, 84.7, 74.5, 66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1])
    line_chart.add('Others', [14.2, 15.4, 15.3, 8.9, 9, 10.4, 8.9, 5.8, 6.7, 6.8, 7.5])
    assert line_chart.render()
示例#12
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")
示例#13
0
文件: test_bar.py 项目: signed0/pygal
def test_simple_bar():
    bar = Bar()
    rng = [-3, -32, -39]
    bar.add('test1', rng)
    bar.add('test2', map(abs, rng))
    bar.x_labels = map(str, rng)
    bar.title = "Bar test"
    q = bar.render_pyquery()
    assert len(q(".axis.x")) == 1
    assert len(q(".axis.y")) == 1
    assert len(q(".legend")) == 2
    assert len(q(".plot .series rect")) == 2 * 3
示例#14
0
def test_simple_bar():
    bar = Bar()
    rng = [-3, -32, -39]
    bar.add("test1", rng)
    bar.add("test2", map(abs, rng))
    bar.x_labels = map(str, rng)
    bar.title = "Bar test"
    q = bar.render_pyquery()
    assert len(q(".axis.x")) == 1
    assert len(q(".axis.y")) == 1
    assert len(q(".legend")) == 2
    assert len(q(".plot .series rect")) == 2 * 3
示例#15
0
 def test_long_title():
     bar = Bar()
     bar.add('Looooooooooooooooooooooooooooooooooong', [2, None, 12])
     bar.title = (
         '1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890 '
         '12345678901 123456789012 1234567890123 12345678901234 '
         '123456789012345 1234567890123456 12345678901234567 '
         '123456789012345678 1234567890123456789 12345678901234567890 '
         '123456789012345 1234567890123456 12345678901234567 '
         '12345678901 123456789012 1234567890123 12345678901234 '
         '1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890')
     return bar.render_response()
示例#16
0
文件: tests.py 项目: wuzesheng/pygal
 def test_long_title():
     bar = Bar()
     bar.add('Looooooooooooooooooooooooooooooooooong', [2, None, 12])
     bar.title = (
         '1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890 '
         '12345678901 123456789012 1234567890123 12345678901234 '
         '123456789012345 1234567890123456 12345678901234567 '
         '123456789012345678 1234567890123456789 12345678901234567890 '
         '123456789012345 1234567890123456 12345678901234567 '
         '12345678901 123456789012 1234567890123 12345678901234 '
         '1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890')
     return bar.render_response()
示例#17
0
 def test_long_title():
     bar = Bar()
     bar.add("Looooooooooooooooooooooooooooooooooong", [2, None, 12])
     bar.title = (
         "1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890 "
         "12345678901 123456789012 1234567890123 12345678901234 "
         "123456789012345 1234567890123456 12345678901234567 "
         "123456789012345678 1234567890123456789 12345678901234567890 "
         "123456789012345 1234567890123456 12345678901234567 "
         "12345678901 123456789012 1234567890123 12345678901234 "
         "1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890"
     )
     return bar.render_response()
示例#18
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.
示例#19
0
def bar_route():
    projects = Project.select()
    bar_chart = Bar()
    bar_chart.title = 'Bar graphs (in %)'

    # instatiating two variables internal and external
    title = 0
    amount = 0

    for project in projects:
        if (project.type == 'title'):
            title += 1
        else:
            amount += 1
    bar_chart.add('title', title)
    bar_chart.add('amount', amount)

    bar_chart.render()
    chart = bar_chart.render_data_uri()

    return render_template('index.html',
                           projects_to_send=projects,
                           chart=chart)
示例#20
0
文件: tests.py 项目: arthru/pygal
 def test_long_title():
     bar = Bar()
     bar.add('Lol', [2, None, 12])
     bar.title = '123456789 ' * 30
     return bar.render_response()
示例#21
0
 def dessiner_graph_course(self):
     graph = Bar(style=style.BlueStyle)
     graph.title = "Course du %s/%s/%s"  % (course.date.day, course.date.month, course.date.year)
     graph.add ([ (str(x), _get_vitesse(x)) for x in range (0, length(tours)) ])
     return graph
示例#22
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')
示例#23
0
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 = 1000

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': 'Frequency: {:.2f}'.format(count / nb_of_rolls)
} for count in counts]
histogram = Bar(style=Style(colors=('#228B22', ), major_label_font_size=12),
                show_legend=False)
histogram.title = 'Simulation for {} rolls of the dice: {}'.format(
    nb_of_rolls, 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')
                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')
示例#25
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')
示例#26
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')
                          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")
示例#28
0
文件: Task5.py 项目: YawenRiva/UNSW
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"))
示例#29
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")
示例#30
0
from die import Die
from pygal import Bar

#Creates two D6 dice
die_1 = Die()
die_2 = Die()

times = 1000

#Roll the dice one thousand times
results = [die_1.roll() + die_2.roll() for _ in range(times)]

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

#Visualize the results
hist = Bar()

hist.title = 'Results of rolling a two D5 dice ' + str(times) + ' times'
hist.x_labels = [str(i) for i in range(2, 13)]
hist.x_title = 'Sum of Sides'
hist.y_title = 'Frequency of Sum'

hist.add('D6 + D6', frequencies)
hist.render_to_file('dice_visual.svg')
示例#31
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')
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')
示例#33
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")
示例#34
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()
示例#35
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')
示例#36
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')





示例#37
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)
示例#38
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')
示例#39
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')