def graph(): #Bar chart for CPU usage bar_chart = pygal.Bar(width=500, height=400, explicit_size=True, range=(0, 100)) bar_chart.title = 'CPU usage per core (%)' for i, v in cpu.items(): bar_chart.add('Core' + str(i), v) chart = bar_chart.render_data_uri() #Pie chart for disk usage pie_chart = pygal.Pie(width=500, height=400, explicit_size=True) pie_chart.title = 'Disk usage (GB)' for key, value in disk_usage.items(): pie_chart.add(key, value) dchart = pie_chart.render_data_uri() #H-bar for memory and swap memory hbar = pygal.HorizontalBar(width=500, height=400, explicit_size=True) hbar.title = 'Memory usage (GB)' for key, value in pmemory.items(): hbar.add(key, value) hbarchart = hbar.render_data_uri() hbarswap = pygal.HorizontalBar(width=500, height=400, explicit_size=True) hbarswap.title = 'Swap memory usage (GB)' for key, value in pswap.items(): hbarswap.add(key, value) hbarswapchart = hbarswap.render_data_uri() return render_template('graphs.html', chart=chart, dchart=dchart, hbarchart=hbarchart, hbarswapchart=hbarswapchart)
def index(): city_path = "../city.json" keyword_path = "..keyword.json" data_city = getData(city_path) data_keyword = getData(keyword_path) title = '51job职位分析' line_charCity = pygal.HorizontalBar() line_charCity.title = 'Python需求最高的十个城市' for item in data_city: line_charCity.add(item[0], item[1]) line_charKeyword = pygal.HorizontalBar() line_charKeyword.title = 'Python相关职位中提到最多的十项技能' for item in data_keyword: line_charKeyword.add(item[0], item[1]) html = """ <html> <head> <title>%s</title> </head> <body> %s <br> %s </body> </html> """ % (title, line_char.render(is_unicode=True), line_char2.render(is_unicode=True)) return html
def queryFileIncreInfo(ip, user, password, command): timeList = [] valfilesList = [] valsizeList = [] client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) client.connect(ip, port=22, username=user, password=password) stdin, stdout, stderr = client.exec_command(command) out = stdout.read() rows = out.split("\n") for row in rows[3::]: if (row.endswith('+') == False): cols = row.split("|") if (len(cols) > 3): timeList.append(cols[1]) valsizeList.append(float(cols[2])) valfilesList.append(float(cols[3])) line_chart6 = pygal.HorizontalBar(width=650, height=800) line_chart6.x_labels = timeList line_chart6.add('File Count', valsizeList) line_chart6.render_to_png('num_of_files.png') line_chart7 = pygal.HorizontalBar(width=650, height=800) line_chart7.x_labels = timeList line_chart7.add('Total size(G)', valfilesList) line_chart7.render_to_png('total_size_gb.png')
def region_cpu_instances(region_in): """ Flask route for resource counts per region """ kwargs = {} kwargs[u'width'] = 900 kwargs[u'height'] = 400 kwargs[u'explicit_size'] = True kwargs[u'print_values'] = True kwargs[u'style'] = self.custom_style title = u'Resource Usage for %s' % region_in # create instances and cpu chart resource_chart = pygal.HorizontalBar(title=title, **kwargs) for instance, instance_count in instances_by_region[ region_in].items(): resource_chart.add(instance, instance_count) for cpu, cpu_count in cpus_by_region[region_in].items(): resource_chart.add(cpu, cpu_count) # create memory and disk chart mem_disk_chart = pygal.HorizontalBar(title=title, **kwargs) for mem, mem_count in mem_by_region[region_in].items(): mem_disk_chart.add(mem, float(mem_count)) for disk, disk_count in disk_by_region[region_in].items(): mem_disk_chart.add(disk, disk_count) context = {} context[u'title'] = title context[u'resource_chart'] = resource_chart context[u'mem_disk_chart'] = mem_disk_chart return render_template('region.html', region_name=region_in, **context)
def stat(): items = get_models() line_chart1 = pygal.HorizontalBar() line_chart1.title = 'Companies' line_chart2 = pygal.HorizontalBar() line_chart2.title = 'Manufacturies' pie_chart3 = pygal.Pie() pie_chart3.title = 'OS' pie_chart4 = pygal.Pie() pie_chart4.title = 'Countries' data1 = dict() data2 = dict() data3 = dict() data4 = dict() for item in items: if item.Company not in data1: data1[item.Company] = 0 data1[item.Company] += 1 if item.Manufacture not in data2: data2[item.Manufacture] = 0 data2[item.Manufacture] += 1 if item.OS not in data3: data3[item.OS] = 0 data3[item.OS] += 1 for item in data1.keys(): line_chart1.add(item, data1[item]) for item in data2.keys(): line_chart2.add(item, data2[item]) for item in data3.keys(): pie_chart3.add(item, data3[item]) items = get_companies() for item in items: if item.country not in data4: data4[item.country] = 0 data4[item.country] += 1 for item in data4.keys(): pie_chart4.add(get_location(item).country, data4[item]) str1 = line_chart1.render_data_uri() str2 = line_chart2.render_data_uri() str3 = pie_chart3.render_data_uri() str4 = pie_chart4.render_data_uri() return render_template( "stat.html", graph_data1=str1, graph_data2=str2, graph_data3=str3, graph_data4=str4, year=datetime.now().year, )
def airquality_april_to_april(): df_apr_2019 = pd.DataFrame( parse_bcn_airquality_data_file("2019_04_Abril_qualitat_aire_BCN.csv")) df_apr_2019 = df_apr_2019.groupby(['date', 'type'], as_index=False)['daily_avg'].mean() df_apr_2019 = pd.pivot_table(df_apr_2019, index='date', columns='type', values='daily_avg', fill_value=0) df_apr_2020 = pd.DataFrame( parse_bcn_airquality_data_file("2020_04_Abril_qualitat_aire_BCN.csv")) df_apr_2020 = df_apr_2020.groupby(['date', 'type'], as_index=False)['daily_avg'].mean() df_apr_2020 = pd.pivot_table(df_apr_2020, index='date', columns='type', values='daily_avg', fill_value=0) # Build and render charts dates = df_apr_2020.index.tolist() # style = pygal.style.LightSolarizedStyle() # NO2 chart = pygal.HorizontalBar( title=u'Barcelona Air Quality - NO2 Apr 2019 vs 2020', x_title="micrograms per cubic meter air µg/m³", x_label_rotation=20, show_dots=False, style=style) chart.x_labels = dates chart.add('Apr 2019', df_apr_2019['NO2']) chart.add('Apr 2020', df_apr_2020['NO2']) chart.render_to_file(OUTPUT_DIR + 'airquality_apr19-20-NO2.svg') # PM10 chart = pygal.HorizontalBar( title=u'Barcelona Air Quality - PM10 Apr 2019 vs 2020', x_title="micrograms per cubic meter air µg/m³", x_label_rotation=20, show_dots=False, style=style) chart.x_labels = dates chart.add('Apr 2019', df_apr_2019['PM10']) chart.add('Apr 2020', df_apr_2020['PM10']) chart.render_to_file(OUTPUT_DIR + 'airquality_apr19-20-PM10.svg')
def pygal_bar_horizontal(data, chartname, file_name): bar_chart = pygal.HorizontalBar() bar_chart = pygal.HorizontalBar(print_values=True, style=DefaultStyle( value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', ))) bar_chart.title = chartname for ds in data: for key, value in ds.items(): bar_chart.add(key, value) bar_chart.render_to_file(file_name + '.svg') bar_chart.render_to_png(file_name + '.png') return True
def plot_guj_1(df): t = df['Detected District'].value_counts()[:10] line_chart = pygal.HorizontalBar() line_chart.title = 'Cities with Highest Cases' for i in range(len(t)): line_chart.add(t.index[i], t[i]) line_chart.render_to_file(paths['guj'])
def bar_graph(session, sq, percentage=True, sort=False): """ Generate a generic Bar graph from a SurveyQuestions """ results = get_sq_results(session, sq, percentage=percentage, sort=sort) count, avg_r, min_r, max_r = get_sq_stats(session, sq) if percentage: x_legend = "%" else: x_legend = "count" title = sq.text.replace("?", "?\n") if sq.question.type == "Multiple choice": stats = f"Stats: {avg_r} avg, max {max_r}" chart_title = f"NetDevOps Survey ({sq.survey_id})\n{title}\n{stats}" else: chart_title = f"NetDevOps Survey ({sq.survey_id})\n{title}" chart = pygal.HorizontalBar( legend_at_bottom=False, width=1920, height=1080, title=chart_title, style=Style(colors=COLORS, **style_args), x_title=x_legend, ) chart.show_legend = False chart.x_labels = map(str, list(results.index)) chart.add(sq.survey.id, list(results["value"])) return chart
def make_graphs(dist_dict,r): line_chart = pygal.Line(width=1200, height=600,explicit_size=True,disable_xml_declaration=True) line_chart.title = 'Pattern of derailment from planned trip v/s stop number' line_chart.x_title = "Stop number" line_chart.y_title = "Distance in meters" for i in dist_dict.keys(): line_chart.add(str(i), list(dist_dict[i].values())) line_chart.x_labels = map(str, range(1, r)) total_avg_dist_dict={} #Graph 2 for i in dist_dict.keys(): total_dist=0 for j in list(dist_dict[i].values()): total_dist+=float(j) total_dist=total_dist/len(list(dist_dict[i].values())) total_avg_dist_dict[i]=total_dist bar_chart = pygal.HorizontalBar(width=1200, height=600,explicit_size=True,disable_xml_declaration=True) bar_chart.title = 'Average distance from planned position v/s trip numbers' bar_chart.y_title = "Trip ID" bar_chart.x_title = "Distance in meters" for i in total_avg_dist_dict.keys(): bar_chart.add(str(i), total_avg_dist_dict[i]) return line_chart,bar_chart
def make_time_graph(time_dict): line_chart = pygal.Line(width=1200, height=600,explicit_size=True,disable_xml_declaration=True) line_chart.title = 'Time difference between planned and actual time at a stop on a given trip' line_chart.x_title = "Dots represent stops" line_chart.y_title = "Time in minutes" for i in time_dict.keys(): line_chart.add(str(i), list(time_dict[i].values())) line_chart.x_labels = map(str,[]) total_avg_time_dict={} for i in time_dict.keys(): total_time=0 for j in list(time_dict[i].values()): total_time+=int(j) total_time=total_time/len(list(time_dict[i].values())) total_avg_time_dict[i]=total_time bar_chart = pygal.HorizontalBar(width=1200, height=600,explicit_size=True,disable_xml_declaration=True) bar_chart.title = 'Average time delay in a trip' bar_chart.y_title = "Trip ID" bar_chart.x_title = "Time in minutes" for i in total_avg_time_dict.keys(): bar_chart.add(str(i), total_avg_time_dict[i]) return line_chart,bar_chart
def features_visualization(features): ''' features - a dictionary of track features prints a bar chart of selected features (on the same scale of 0-1) ''' feature_dict = copy.deepcopy(features) # exclude some features for feature in [ 'time_signature', 'mode', 'loudness', 'key', 'tempo', 'duration_ms', 'analysis_url', 'id', 'track_href', 'type', 'uri' ]: del feature_dict[feature] # customize chart style custom_style = Style(background='rgba(253, 247, 246, 0.4)', plot_background='rgba(249, 228, 225, 1)', foreground='rgba(0, 0, 0, 0.9)', foreground_strong='rgba(0, 0, 0, 0.9)', foreground_subtle='rgba(0, 0, 0, 0.5)', opacity='.6', opacity_hover='.9', colors=('#d94e4c', '#e5884f', '#39929a', lighten('#d94e4c', 10), darken('#39929a', 15), lighten('#e5884f', 17), darken('#d94e4c', 10), '#234547')) # create chart chart = pygal.HorizontalBar(style=custom_style) chart.title = 'Track Features' for feature, value in feature_dict.items(): chart.add(feature, value) chart.render() return chart.render_data_uri()
def chart(publications): pubs = publications.values('meshHeadings') #Data Generation and Formatting g = [] for y in pubs: text = re.sub('[^A-Za-z, ]', '', str(y['meshHeadings'].split(", "))) g.append(text) counts = [] for i in g: i = i.split(", ") counts.append(i) thingy = {} for a in counts: for b in a: if b in thingy: thingy[b] += 1 else: thingy[b] = 1 x = dict(Counter(thingy).most_common(10)) #Graph Creation bar_chart = pygal.HorizontalBar( legend_at_bottom=True, title=u'Top Research Interests by MeSH Headings', x_title='Frequency', y_title='MeSH Heading', print_values=True, print_labels=True, style=BlueStyle(value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', ))) for y in x: bar_chart.add(y, x[y]) bar_chart.render_to_file('./searchFunction/static/mesh_chart.svg')
def main(): all_url = [] queue = Queue.Queue() firsturl = raw_input('请输入音乐分类:') firsturl = urllib.quote(firsturl) first_url = 'http://music.163.com/discover/playlist/?cat=' + firsturl + '&order=hot' second_url = 'http://music.163.com/discover/playlist/?order=hot&cat=' + firsturl + '&limit=35&offset=' all_url.append(first_url) for i in range(42): last_url = second_url + (str((i + 1) * 35)) all_url.append(last_url) for url in all_url: queue.put(url) for i in range(10): t = GetAllcolum(queue) t.setDaemon(True) t.start() queue.join() # 制作成条形图(svg格式) line_chart = pygal.HorizontalBar() line_chart.title = u"网易云 " for i in range(len(injuries)): if injuries[i] > 100: line_chart.add(province[i], injuries[i]) line_chart.render_to_file('data_file/music_hot_cato.svg')
def open_data_progress(): client = pymongo.MongoClient(os.environ['MONGO_CASES_URI']) db = client.va_circuit_court_cases data = db.case_numbers.aggregate([{ '$sort': SON([('court', 1), ('name', 1)]) }, { '$group': { '_id': { 'court': '$court' }, 'firstName': { '$first': '$name' }, 'lastName': { '$last': '$name' }, 'count': { '$sum': 1 } } }, { '$sort': SON([('_id.court', 1)]) }])['result'] chart = pygal.HorizontalBar(style=pygal.style.RedBlueStyle, show_legend=False, height=1500) chart.x_labels = [x['_id']['court'] for x in data][::-1] chart.add('', [x['count'] for x in data][::-1]) return chart.render() + str( render_template('open_data_progress.html', data=data))
def main(reasons): chart = pygal.HorizontalBar() chart.title = 'Pikabu banned users statistics' for case in reasons: chart.add(case, reasons[case]) chart.render_to_file('data.svg') SVG(filename='data.svg')
def horizBar(name, graphdata): # Create horizontal bar chart object and set title chart = pygal.HorizontalBar(show_legend=False, style=custom_style, x_label_rotation=30, y_labels_major_every=1000) #chart.title = name # Turn data into respective data and label array x_labels = [] x_data = [] for data in graphdata: x_labels.append(data[0]) diction = {'value': data[1]} if len(data) > 2: diction['xlink'] = str(data[2]) x_data.append(diction) # Insert the data chart.add('', x_data) chart.x_labels = x_labels # Export to an svg file #chart.render_to_file('CarRentalCompany/templates/CarRentalCompany/Charts/' + name + '.svg') return chart.render(is_unicode=True)
def send_graph(bot, update): global comandi global chiamate global graph_file_counter chiamate[comandi.index("graph")] += 1 graph_file_counter = graph_file_counter + 1 if graph_file_counter == 10: graph_file_counter = 1 os.system("rm -f graph%d.png" % graph_file_counter) bot.sendMessage(update.message.chat_id, "Genero la statistica dei comandi ricevuti finora...") line_chart = pygal.HorizontalBar() line_chart.title = startup_time line_chart.add('rele', chiamate[comandi.index("rele")]) line_chart.add('foto', chiamate[comandi.index("foto")]) line_chart.add('video', chiamate[comandi.index("video")]) line_chart.add('logo', chiamate[comandi.index("logo")]) line_chart.add('pdf', chiamate[comandi.index("pdf")]) line_chart.add('music', chiamate[comandi.index("music")]) line_chart.add('dog', chiamate[comandi.index("dog")]) line_chart.add('jingle', chiamate[comandi.index("jingle")]) line_chart.add('graph', chiamate[comandi.index("graph")]) line_chart.render_to_png('graph%d.png' % graph_file_counter) bot.sendPhoto(update.message.chat_id, open('graph%d.png' % graph_file_counter))
def graph12(): """This graph about Compare graph of Classified by type og alcohol in 2544 - 2557""" sheet = workbook.sheet_by_index(5) data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)] for i in range(2, sheet.nrows): for k in range(1, 6): list_data[i - 2].append({ 'value': round((data[i][k] / sum(data[i][j] for j in range(1, 6))) * 100, 2), 'label': '%.2f%s' % (round( (data[i][k] / sum(data[i][j] for j in range(1, 6))) * 100, 2), '%') }) line_chart = pygal.HorizontalBar(print_labels=True, stack_from_top=False) line_chart.title = 'เปรียบเทียบรอยละของประชากรอายุ 15 ปขึ้นไปที่ดื่มสุราหรือเครื่องดื่มมึนเมา จำแนกตามประเภทของสุราที่ดื่มบ่อย ปี 2544 - 2557' line_chart.x_labels = [ 'เบียร์', 'สุราแช่พื้นบ้าน (สาโท อุ กระแช่)', 'สุราขาว, สุราสี, สุรากลั่น', 'ไวน์', 'อื่นๆ' ] line_chart.y_labels = map(int, range(0, 61, 10)) for i in range(4): line_chart.add(data_name[i], list_data[i]) line_chart.render_to_file( '12Compare graph of Classified by type og alcohol in 2544 - 2557.svg')
def graph11(): """This graph about Compare graph of Classified by frequency of drinking in 2544 - 2557""" sheet = workbook.sheet_by_index(4) data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)] for i in range(2, sheet.nrows): for k in range(1, 6): list_data[i - 2].append({ 'value': round((data[i][k] / sum(data[i][j] for j in range(1, 6))) * 100, 2), 'label': '%.2f%s' % (round( (data[i][k] / sum(data[i][j] for j in range(1, 6))) * 100, 2), '%') }) line_chart = pygal.HorizontalBar(print_labels=True, stack_from_top=False) line_chart.title = 'เปรียบเทียบรอยละของประชากรอายุ 15 ปขึ้นไปที่ดื่มสุราหรือเครื่องดื่มมึนเมา จําแนกตามความถี่ในการดื่มสุราหรือเครื่องดื่มมึนเมา ปี 2544 - 2557' line_chart.x_labels = [ "ดื่มทุกวัน", "5-6 วันต่อสัปดาห์", "3-4 วันต่อสัปดาห์", "1-2 วันต่อสัปดาห์", "ดื่มนานๆครั้ง" ] line_chart.y_labels = map(int, range(0, 71, 10)) for i in range(6): line_chart.add(data_name[i], list_data[i]) line_chart.render_to_file( '11Compare graph of Classified by frequency of drinking in 2544 - 2557.svg' )
def __init__(self): super(Chart, self).__init__() self.chart_types = { "pie": pygal.Pie(), "horizontal_bar": pygal.HorizontalBar() }
def rate_movies(): """ Create Rated of Movies horizontalbar_graph of movies in year 2000-2016 and Load Dataset title and revenue""" for year in range(2000, 2017): print(">> Year : %i" % year) # Start display print(">> [status] Create Graph Starting!") dataset = pd.read_csv("Data_Export/%i.csv" % (year)) title = dataset["title"].tolist() #Title Movies revenue = dataset["revenue"].tolist() #Revenue graph = pygal.HorizontalBar(x_title="Movie Name & Revenue") graph.title = "Revenue of Movies in year %i Dataset" % year for i in range(len(title)): if revenue[i] != 0: graph.add(title[i], revenue[i]) graph.render_to_file( "Graph_Export/Revenue_Movies/HorizontalBar/Revenue_of_Movies_%i.svg" % year) # End display print(">> [status] Created Graph Successful!") print() # Used time print(">> [status] Completed : Used time = %s seconds" % (time.time() - start_time))
def plotPermBarCharts(dataFilePath, outputPath): for short_name in US_STATES: with open(dataFilePath + short_name + '.csv', 'rb') as csvfile: stateData = list(csv.reader(csvfile)) darken_style = DarkenStyle('#ff8723', step=20) custom_style = Style(tooltip_font_size=18, legend_font_size=13, value_font_size=15, title_font_size=18) bar_chart = pygal.HorizontalBar( legend_box_size=10, hieght=100, style=darken_style, print_values=True, margin=20, # show_legend=False, legend_at_bottom=True, tooltip_fancy_mode=True, tooltip_border_radius=10) # bar_chart.title = 'Top 30 foreign-worker-friendly Companies in</br>' + US_STATE_SHORT_dic[short_name] topX = 20 if (short_name == 'MO'): topX = 17 for row in stateData[1:topX + 1]: bar_chart.add(str(row[0]), float(row[1]), rounded_bars=3) # bar_chart.render_in_browser() bar_chart.render_to_file(outputPath + short_name + '.svg')
def getProtocolPlot(filename): tcap = pyshark.FileCapture(filename, only_summaries=True) protocolList = {} for packet in tcap: line = str( packet ) # Each packet object (i.e a single line that will have the data of a specific packet we see in wireshark will be typecasted into a string and stored in a variable). formattedLine = line.split( " " ) # List of different columns of the packet capture file which will be splitted based on the seperator " "(i.e space) which is the default seperator of that data. # print(formattedLine) # if(formattedLine[4]=="ARP"):#Extracting all the ARP packet ID's. if (formattedLine[4] in protocolList.keys()): protocolList[formattedLine[4]] += 1 else: protocolList.update({formattedLine[4]: 1}) arp_packet_count = protocolList["ARP"] line_chart = pygal.HorizontalBar() line_chart._title = "Packet count" for i in protocolList: line_chart.add(i, int(protocolList[i])) chart = line_chart.render() #print(chart) html = """{}""".format(chart) return html, arp_packet_count
def graph(): try: if (session['adminlogin'] == True): candidates = Candidate.query.all() candiname = [] candivote = [] for i in candidates: candiname.append(i.Name) candivote.append(i.Count) line_chart = pygal.HorizontalBar() #bar graph line_chart.title = 'Vote Count' for i in range(len(candiname)): line_chart.add(candiname[i], candivote[i]) line_chart = line_chart.render_data_uri() voter_voted = Voter.query.filter(Voter.Voted.like('1')).all() voter_not_voted = Voter.query.filter(Voter.Voted.like('0')).all() pie_chart = pygal.Pie() pie_chart.title = "Voting Turnout" pie_chart.add('Voted', len(voter_voted)) pie_chart.add('Not Voted', len(voter_not_voted)) pie_chart = pie_chart.render_data_uri() return render_template("graph.html", line_chart=line_chart, pie_chart=pie_chart) else: return redirect('/') except: flash("Error Loading Graph!", "info") return render_template("graph.html")
def home(): if 'username' not in session: return redirect(url_for('login')) northCount = 0 westCount = 0 eastCount = 0 southCount = 0 stats = fireS.get('userInfo', None) print(stats) for i in stats: if stats[i]['region'] == 'North': northCount += 1 elif stats[i]['region'] == 'West': westCount += 1 elif stats[i]['region'] == 'East': eastCount += 1 elif stats[i]['region'] == 'South': southCount += 1 line_chart = pygal.HorizontalBar() line_chart.title = 'Numbers of users in Smart Kampung' line_chart.add('North', northCount) line_chart.add('East', eastCount) line_chart.add('West', westCount) line_chart.add('South', southCount) graph_data = line_chart.render_data_uri() return render_template("home.html",line_chart=graph_data)
def frequency_dist(data, n, title): #data should be a list of words #n is number of most common words dist = FreqDist(data) most_common = dist.most_common(n) words_ordered = [] frequencies_ordered = [] for word in most_common: words_ordered.append(word[0]) frequencies_ordered.append(word[1]) line_chart = pygal.Bar() line_chart.title = 'Word frequency' line_chart.x_labels = words_ordered line_chart = pygal.HorizontalBar() line_chart.title = title for i in range(len(words_ordered)): line_chart.add(words_ordered[i], frequencies_ordered[i]) return line_chart.render_data_uri()
def chart(publications): pubs = publications.values('authors') #Data Generation and Formatting g = [] for y in pubs: text = re.sub('[^A-Za-z, ]', '', str(y['authors'].split(", "))) g.append(text) counts = [] for i in g: i = i.split(", ") counts.append(i) thingy = {} for a in counts: for b in a: if b in thingy: thingy[b] += 1 else: thingy[b] = 1 x = dict( Counter(thingy).most_common(6)[1:] ) #The "[1:]" list slice here is because the most common researchers will always be themselves, so we remove the self-reference. #Graph Creation bar_chart = pygal.HorizontalBar( title=u'Top Co-authors', x_title='Number of papers co-authored', y_title='Co-author', print_values=True, print_labels=True, style=BlueStyle(value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', ))) for y in x: bar_chart.add(y, x[y]) bar_chart.render_to_file('./searchFunction/static/author_chart.svg')
def frequency_dist(data, n, title, stopwords=None): ''' Computes the word-frequency distribution graph and returns a base 64 encoded data uri version of it. Parameters ---------- data : list List of text tokens. Returns ---------- Word-frequency distribution graph in base 64 encoded data uri. ''' if stopwords is not None: data = [x for x in data if not x in stopwords] dist = FreqDist(data) most_common = dist.most_common(n) words_ordered = [] frequencies_ordered = [] for word in most_common: words_ordered.append(word[0]) frequencies_ordered.append(word[1]) line_chart = pygal.HorizontalBar() line_chart.title = title for i in range(len(words_ordered)): line_chart.add(words_ordered[i], frequencies_ordered[i]) return line_chart.render_data_uri()
def revenue_movies(): """ Create Top-20 Revenue of Movies bar_graph of movies in year 2000-2016 and Load Dataset title and rate""" for year in range(2000, 2017): # Start display print(">> Year : %i" % year) print(">> [status] Create Graph Starting!") dataset = pd.read_csv("Top-100_Export/Top-100_%i.csv" % (year)) title = dataset["title"].tolist() #Title Movies revenue = dataset["revenue"].tolist() #Revenue data = [] for j in range(len(title)): data.append([title[j], revenue[j]]) data.sort(key=lambda x: x[1], reverse=True) graph = pygal.HorizontalBar(x_title="Revenue") graph.value_formatter = lambda x: '{:.10g}M'.format(x) graph.title = "Top-20 Revenue of Movies in %i Dataset" % year for i in range(20): graph.add(data[i][0], data[i][1] / 1000000 // 0.01 / 100) graph.render_to_file( "Graph_Export/Top-20_Revenue/Top-20_Revenue_%i.svg" % year) # End display print(">> [status] Created Graph Successful!") # Used time print(">> [status] Completed : Used time = %s seconds" % (time.time() - start_time))