def test_bar_percent_difference(): bar = Bar() rng = [-3, -32, -39] bar.add('test1', rng) bar.add('test2', map(abs, rng)) bar.x_labels = map(str, rng) barpercent = Bar(percent_values=True) rng = [-3, -32, -39] barpercent.add('test1', rng) barpercent.add('test2', map(abs, rng)) barpercent.x_labels = map(str, rng) assert (bar != barpercent)
def test_bar_percent_difference(): """Tests the difference between percent labeled graphs and unlabeled graphs""" bar = Bar() rng = [-3, -32, -39] bar.add('test1', rng) bar.add('test2', map(abs, rng)) bar.x_labels = map(str, rng) barpercent = Bar(percent_values=True) rng = [-3, -32, -39] barpercent.add('test1', rng) barpercent.add('test2', map(abs, rng)) barpercent.x_labels = map(str, rng) assert (bar != barpercent)
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()
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")
def test_bar(): bar = Bar(dynamic_print_values=True, show_minor_x_labels=False) bar.add('1', [1, 2, 3]) bar.add('2', [4, 5, 6]) bar.x_labels = [2, 4, 6] bar.x_labels_major = [4] return bar.render_response()
def test_bar_links(): bar = Bar(style=styles['neon']) bar.js = ('http://l:2343/svg.jquery.js', 'http://l:2343/pygal-tooltips.js') bar.add('1234', [ {'value': 10, 'label': 'Ten', 'xlink': 'http://google.com?q=10'}, {'value': 20, 'tooltip': 'Twenty', 'xlink': 'http://google.com?q=20'}, 30, {'value': 40, 'label': 'Forty', 'xlink': 'http://google.com?q=40'} ]) bar.add('4321', [40, { 'value': 30, 'label': 'Thirty', 'xlink': 'http://google.com?q=30' }, 20, 10]) bar.x_labels = map(str, range(1, 5)) bar.logarithmic = True bar.zero = 1 return bar.render_response()
def test_bar(): bar = Bar(dynamic_print_values=True, show_minor_x_labels=False) bar.add('1', [1, 2, 3]) bar.add('2', [4, 5, 6]) bar.x_labels = [2, 4, 6] bar.x_labels_major = [4] return bar.render_response()
def test_bar_links(): bar = Bar(style=styles['neon']) bar.js = ('http://l:2343/svg.jquery.js', 'http://l:2343/pygal-tooltips.js') bar.add('1234', [{ 'value': 10, 'label': 'Ten', 'xlink': 'http://google.com?q=10' }, { 'value': 20, 'tooltip': 'Twenty', 'xlink': 'http://google.com?q=20' }, 30, { 'value': 40, 'label': 'Forty', 'xlink': 'http://google.com?q=40' }]) bar.add('4321', [ 40, { 'value': 30, 'label': 'Thirty', 'xlink': 'http://google.com?q=30' }, 20, 10 ]) bar.x_labels = map(str, range(1, 5)) bar.logarithmic = True bar.zero = 1 return bar.render_response()
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)
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()
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()
def test_unsorted(): bar = Bar(style=styles["neon"], human_readable=True) bar.add("A", {"red": 10, "green": 12, "blue": 14}) bar.add("B", {"green": 11, "blue": 7}) bar.add("C", {"blue": 7}) bar.add("D", {}) bar.add("E", {"blue": 2, "red": 13}) bar.x_labels = ("red", "green", "blue") return bar.render_response()
def test_unsorted(): bar = Bar(style=styles['neon']) bar.add('A', {'red': 10, 'green': 12, 'blue': 14}) bar.add('B', {'green': 11, 'blue': 7}) bar.add('C', {'blue': 7}) bar.add('D', {}) bar.add('E', {'blue': 2, 'red': 13}) bar.x_labels = ('red', 'green', 'blue') return bar.render_response()
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()
def test_unsorted(): bar = Bar(style=styles['neon']) bar.add('A', {'red': 10, 'green': 12, 'blue': 14}) bar.add('B', {'green': 11, 'blue': 7}) bar.add('C', {'blue': 7}) bar.add('D', {}) bar.add('E', {'blue': 2, 'red': 13}) bar.x_labels = ('red', 'green', 'blue') return bar.render_response()
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()
def test_ylabels(): chart = Bar() chart.x_labels = "Red", "Blue", "Green" chart.y_labels = [ {"value": 0.0001, "label": "LOL"}, {"value": 0.0003, "label": "ROFL"}, {"value": 0.0004, "label": "MAO"}, {"value": 0.00045, "label": "LMFAO"}, {"value": 0.0005, "label": "GMCB"}, ] chart.add("line", [0.0002, 0.0005, 0.00035]) return chart.render_response()
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
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
def test_difference(): bar = Bar(bar_values=False) rng = [-3, -32, -39] bar.add('test1', rng) bar.add('test2', map(abs, rng)) bar.x_labels = map(str, rng) bar_labelled = Bar(bar_values=True) rng = [-3, -32, -39] bar_labelled.add('test1', rng) bar_labelled.add('test2', map(abs, rng)) bar.labelled = map(str, rng) assert bar != bar_labelled
def test_difference(): """Tests the difference between labeled graphs and unlabeled graphs""" bar = Bar(bar_values=False) rng = [-3, -32, -39] bar.add('test1', rng) bar.add('test2', map(abs, rng)) bar.x_labels = map(str, rng) bar_labelled = Bar(bar_values=True) rng = [-3, -32, -39] bar_labelled.add('test1', rng) bar_labelled.add('test2', map(abs, rng)) bar.labelled = map(str, rng) assert bar != bar_labelled
def test_ylabels(): chart = Bar() chart.x_labels = 'Red', 'Blue', 'Green' chart.y_labels = [ {'value': .0001, 'label': 'LOL'}, {'value': .0003, 'label': 'ROFL'}, {'value': .0004, 'label': 'MAO'}, {'value': .00045, 'label': 'LMFAO'}, {'value': .0005, 'label': 'GMCB'}] chart.add('line', [.0002, .0005, .00035]) return chart.render_response()
def test_ylabels(): chart = Bar() chart.x_labels = 'Red', 'Blue', 'Green' chart.y_labels = [ {'value': .0001, 'label': 'LOL'}, {'value': .0003, 'label': 'ROFL'}, {'value': .0004, 'label': 'MAO'}, {'value': .00045, 'label': 'LMFAO'}, {'value': .0005, 'label': 'GMCB'}] chart.add('line', [.0002, .0005, .00035]) return chart.render_response()
def test_bar_links(): bar = Bar(style=styles["neon"]) bar.js = ("http://l:2343/svg.jquery.js", "http://l:2343/pygal-tooltips.js") bar.add( "1234", [ {"value": 10, "label": "Ten", "xlink": "http://google.com?q=10"}, {"value": 20, "tooltip": "Twenty", "xlink": "http://google.com?q=20"}, 30, {"value": 40, "label": "Forty", "xlink": "http://google.com?q=40"}, ], ) bar.add("4321", [40, {"value": 30, "label": "Thirty", "xlink": "http://google.com?q=30"}, 20, 10]) bar.x_labels = map(str, range(1, 5)) bar.logarithmic = True bar.zero = 1 return bar.render_response()
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.
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")
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')}))
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')
def test_bar(): bar = Bar() bar.add('1', [1, 2, 3]) bar.add('2', [4, 5, 6]) bar.x_labels = ['a'] return bar.render_response()
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')
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")
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")
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"))
def test_bar_none(): bar = Bar() bar.add('Lol', [2, None, 12]) bar.x_labels = range(1, 4) return bar.render_response()
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)
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')
def test_bar(): bar = Bar() bar.add("1", [1, 2, 3]) bar.add("2", [4, 5, 6]) bar.x_labels = ["a"] return bar.render_response()
def test_bar(): bar = Bar() bar.add('1', [1, 2, 3]) bar.add('2', [4, 5, 6]) bar.x_labels = ['a'] return bar.render_response()
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')
"""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')
def test_bar_none(): bar = Bar() bar.add('Lol', [2, None, 12]) bar.x_labels = range(1, 4) return bar.render_response()