def city_profile(): form = city_profile_form() print(request.method) render_data = [] overall_graph_data = [] print(request) if request.method == 'POST': cityName = request.form['city'] print(cityName) values = get_city_and_value(cityName) names = get_11_parameters_names() bar_chart = pygal.HorizontalStackedBar() bar_chart.title = cityName bar_chart.x_labels = map(str, names) bar_chart.add("", values) overall_graph_data = bar_chart.render_data_uri() parameters_names = get_11_parameters_names() render_data = [] for majorParameterName in parameters_names: values1 = get_data_by_city_parameter(cityName, majorParameterName) bar_chart = pygal.HorizontalStackedBar() bar_chart.title = majorParameterName bar_chart.x_labels = map(str, names) bar_chart.add("", values1) render_data.append(bar_chart.render_data_uri()) return render_template("city_profile.html", form=form, graph_data=overall_graph_data, render_data=render_data)
def horizontal_stacked_bar(): chart = pygal.HorizontalStackedBar() chart.title = 'horizontal_stacked_bar' chart.x_labels = map(str, range(size)) chart.add('Number 1 Test one', get_random_data(size)) chart.add('Number 2 Test two', get_random_data(size)) chart.render_to_file(get_file_name(inspect.stack()[0][3]))
def votesgroupes(): #return json_response(list(mdb.groupes.find({},{'_id':None,'groupe_abrev':1,'groupe_uid':1}))) libelles = {'FI':u'France Insoumise', 'LAREM':u'République en Marche', 'UDI-AGIR': u'UDI, Agir et Indépendants', 'GDR':u'Gauche Démocratique et Républicaine', 'NG':u'Nouvelle Gauche', 'MODEM':u'Mouvement Démocrate', 'LR':u'Les Républicains', 'NI':u'Députés Non Inscrits' } #return json_response(mdb.votes.find_one()) pgroup = {} pgroup['n'] = {'$sum':1} pgroup['_id'] = { 'groupe':'$groupe_abrev','position':'$vote_position'} pipeline = [{'$group':pgroup}] grps = {} for v in mdb.votes.aggregate(pipeline): g = v['_id']['groupe'] p = v['_id']['position'] n = v['n'] if g=='LC': g='UDI-AGIR' if not g in grps: grps[g] = { 'absent':0,'pour':0,'contre':0,'abstention':0 } grps[g][p] += n stats = [] for g in grps: stat = dict(g=g) tot = sum(grps[g].values()) for p in ('pour','contre','abstention','absent'): stat[p]=100*float(grps[g][p])/tot stats.append(stat) stats.sort(key=lambda x:x['absent'],reverse=True) from pygal.style import Style custom_style = Style( font_family="'Montserrat', sans-serif;", major_label_font_size=15, colors=['#25a87e','#e23d21','#213558','#bbbbbb'] ) histo_chart = pygal.HorizontalStackedBar(x_label_rotation=0,width=1024,height=512,human_readable=True, x_title='%',y_title="Groupes parlementaires",style=custom_style) histo_chart.title = u'Votes des députés aux scrutins publics\n par groupe parlementaire (au %s)' % (datetime.datetime.now().strftime('%d/%m/%Y')) for x in 'pour','contre','abstention','absent': histo_chart.add('%s' % x, [stat[x] for stat in stats]) histo_chart.x_labels = [libelles[stat['g']] for stat in stats] histo_chart.y_labels = [] #histo_chart.x_labels_major = majors from StringIO import StringIO chart = StringIO() histo_chart.render_to_png(chart) return image_response('png',chart.getvalue()) return json_response(stats)
def test(): bar_chart = pygal.HorizontalStackedBar() bar_chart.title = "Remarquable sequences" bar_chart.x_labels = map(str, range(11)) bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12]) chart = bar_chart.render(is_unicode=True) return render_template('chart.html', chart=chart)
def datetime_chart # To install, just type as superuser: # !sudo pip install pygal #------------------------------------------------------------------- import pygal #------------------------------------------------------------------- bar_chart = pygal.Bar() #------------------------------------------------------------------- #lxml which can improve rendering speed (except on pypy). #!pip3 install lxml import lxml #cairosvg, tinycss, cssselect to render png. #!pip3 install cairosvg import cairosvg #!pip3 install tinycss import tinycss #!pip3 install cssselect import cssselect #------------------------------------------------------------------- # Time from datetime import datetime, timedelta date_chart = pygal.Line(x_label_rotation=20) date_chart.x_labels = map(lambda d: d.strftime('%Y-%m-%d'), [ datetime(2013, 1, 2), datetime(2013, 1, 12), datetime(2013, 2, 2), datetime(2013, 2, 22)]) date_chart.add("bb106", [300, 412, 823, 672]) date_chart.render() bar_chart = pygal.HorizontalStackedBar() bar_chart.title = "bb106" bar_chart.x_labels = map(str, range(11)) bar_chart.add('positive', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) bar_chart.add('negative', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12]) #bar_chart.render() bar_chart.render_to_file('555.svg') bar_chart.render_to_png(filename='555555.png') #if __name__== '__main__': # main() if __name__ == '__main__': main()
def stacked_graph_gsq(session, sq, results_order=None): """ Generate HorizontalStackedBar graphs for a Survey Question of type `Multiple choice grid` if results_order is provided, the results will be display in this order """ results = get_gsq_results(session, sq, percentage=True) # convert index to lowercase to simplify mapping # Will convert it to Title just before rendering results.index = [idx.lower() for idx in results.index] # if results_order has been provided # First order the index based on the list provided # then order the columns by the value of the last element of the list if results_order: order_lower = [idx.lower() for idx in results_order] results = results.reindex(order_lower, axis=0) results = results.sort_values(by=order_lower[-1], axis=1) for c in results.columns: if "(" in c: results = results.rename(columns={c: c.split("(")[0]}) title = sq.text.replace("?", "?\n") if len(results.index) == 3: colors = LANGUAGE_COLOR else: colors = TRENDS_COLOR chart = pygal.HorizontalStackedBar( legend_at_bottom=True, stack_from_top=True, width=1920, height=1080, title=f"NetDevOps Survey ({sq.survey_id}) \n {title}", style=Style(colors=colors, **style_args), ) chart.x_labels = map(str, results.columns) for idx in results.index: chart.add(idx.title().replace("Don'T", "don't"), list(results.loc[idx])) return chart
def export_stackedBars(data, title, filename): values = list(data[0]) xLabels = list(data[1]) valuesTags = list(data[2]) today = datetime.date.today() stackedbar_chart = pygal.HorizontalStackedBar(label_font_size=8, legend_at_bottom=True) stackedbar_chart.title = title + today.strftime(' (%Y/%m/%d)') stackedbar_chart.x_labels = xLabels for tag, value in zip(valuesTags, values): stackedbar_chart.add(tag, value) saveChart(stackedbar_chart, filename)
def hello_world(): pie_chart = pygal.Pie() pie_chart.title = 'services vs products in percentage' pie_chart.add('products', InventoryModel.getCountType("Product")) pie_chart.add('sales', InventoryModel.getCountType("Service")) graph_data = pie_chart.render_data_uri() conn = psycopg2.connect( "dbname='ims' user='******' host='localhost' password='******'") cur = conn.cursor() cur.execute( """SELECT (sum(i.bp * s.quantity)) as subtotal, EXTRACT(MONTH FROM s.created_date)as sales_month FROM sales as s join inventories as i on s.inv_id = i.id GROUP BY sales_month ORDER BY sales_month""") rows = cur.fetchall() # print(rows) x = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ] y = [] for r in rows: # x.append(r[1]) y.append(r[0]) line_chart = pygal.Line() line_chart.title = 'Subtotal of a period in %' line_chart.x_labels = map(str, x) line_chart.add('Subtotal', y) line_data = line_chart.render_data_uri() line_some = pygal.HorizontalStackedBar() line_some.title = 'Subtotal of a period in %' line_some.x_labels = map(str, x) line_some.add('Subtotal', y) line_some = line_some.render_data_uri() return render_template("index.html", graph_data=graph_data, line_data=line_data, line_some=line_some)
def compare_results_over_time_sbar(session, q, results_order=None): """ Generate a HorizontalStackedBar graph to compare results over time for a specific Multiple choice grid option """ results = get_q_results_over_time(session, q, percentage=True, min_count=2) # convert index to lowercase to simplify mapping # Will convert it to Title just before rendering results.index = [idx.lower() for idx in results.index] # if results_order has been provided # First order the index based on the list provided # then order the columns by the value of the last element of the list if results_order: order_lower = [idx.lower() for idx in results_order] results = results.reindex(order_lower, axis=0) results = results.sort_values(by=order_lower[-1], axis=1) # order columns too cols = sorted(list(results.columns)) results = results[cols] title = q.desc.replace("?", "?\n") if q.parent_id: pq = session.query(Questions).get(q.parent_id) title = pq.desc + ": " + title nbr_edition = len(list(results.columns)) chart = pygal.HorizontalStackedBar( legend_at_bottom=True, stack_from_top=True, width=1920, height=320 + nbr_edition * 160, title=f"NetDevOps Survey \n {title}", style=netdevops_style_trends, ) chart.x_labels = map(str, results.columns) for idx in results.index: chart.add(idx.title().replace("Don'T", "don't"), list(results.loc[idx])) return chart
def render_bar_chart(self, data, file_name='untitled_chart', title=''): ''' Function: Render bar chart ''' # Chart Initialization chart = pygal.HorizontalStackedBar() # Chart Data if isinstance(data, list): total = sum(data) chart.add( 'Scored', [{ 'value': i, 'label': '{}/{} ({:.2f}%)'.format(i, total, 100 * i / total) } for i in data]) elif isinstance(data, dict): total = sum([sum(data[category]) for category in data]) for category in data: chart.add(category, [{ 'value': i, 'label': '{}/{} ({:.2f}%)'.format(i, total, 100 * i / total) } for i in data[category]]) # Chart Labels if isinstance(data, list): chart.x_labels = [i for i in range(1 - (len(data) == 11), 11, 1)] chart.y_labels = self.get_y_labels(0, max(data)) elif isinstance(data, dict): chart.x_labels = [ i for i in range(1 - (len(data[[j for j in data][0]]) == 11), 11, 1) ] data_r = [data[i] for i in data] data_r = [[data_r[j][i] for j in range(len(data_r))] for i in range(len(data_r[0]))] data_r = [sum(i) for i in data_r] chart.y_labels = self.get_y_labels(0, max(data_r)) # Finish Chart self.finish_chart(chart, file_name=file_name, show_legend=isinstance(data, dict), title=title)
def draw(self): self.chart = pygal.HorizontalStackedBar(self.config, style=self.style, fill=True, legend_at_bottom=True, legend_at_bottom_columns=4) self.chart.title = self.title self.chart.x_title = "Persentase Medali" average_medal, remainders, deficits, sport_names = self.fill_data() self.chart.x_labels = sport_names self.chart.add("Rata-rata perolehan medali", average_medal) self.chart.add("Perbedaan", remainders) self.chart.add("Defisit", deficits)
def display_Cereals(self): data = pd.read_excel("cereal.xlsx", sheet_name='Modified_Cereal', index_col=0) self.bar_chart = pygal.HorizontalStackedBar() self.bar_chart.title = "Nutrient composition of cereals" self.bar_chart.add('protein', data['protein']) self.bar_chart.add('calories (X100)', data['calories'] / 100) self.bar_chart.add('fat', data['fat']) self.bar_chart.add('sodium (X100)', data['sodium'] / 100) self.bar_chart.add('fiber', data['fiber']) self.bar_chart.add('carbohydrates', data['carbo']) self.bar_chart.add('sugar', data['sugars']) self.bar_chart.add('potassium (X100)', data['potass'] / 100) self.bar_chart.add('vitamins (X10)', data['vitamins'] / 10) self.bar_chart.render_to_file('HorizontalStackedBar.svg') display(SVG(self.bar_chart.render(disable_xml_declaration=True)))
def date_chart(): # Time from datetime import datetime, timedelta date_chart = pygal.Line(x_label_rotation=20) date_chart.x_labels = map(lambda d: d.strftime('%Y-%m-%d'), [ datetime(2013, 1, 2), datetime(2013, 1, 12), datetime(2013, 2, 2), datetime(2013, 2, 22) ]) date_chart.add("bb106", [300, 412, 823, 672]) date_chart.render() bar_chart = pygal.HorizontalStackedBar() bar_chart.title = "bb106" bar_chart.x_labels = map(str, range(11)) bar_chart.add('positive', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) bar_chart.add('negative', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12]) #bar_chart.render() bar_chart.render_to_file('555.svg') bar_chart.render_to_png(filename='555555.png')
def history(player_id=None): if current_user.Player_ID is None and player_id is None: return redirect(url_for('main.index')) if player_id: p = player_id else: p = current_user.Player_ID player_detail = db.session.query(Player.Surname, MatchUp.OpponentRank, func.count(MatchUp.idmatchup).label('MatchesPlayed'), func.sum(MatchUp.MyPlayerActual).label('ActRacksWon'), func.sum(MatchUp.OpponentActual).label('ActRacksLost'), (func.sum(MatchUp.MyPlayerActual) / (func.sum(MatchUp.OpponentActual) + func.sum(MatchUp.MyPlayerActual))).label('RackPct'), (func.sum(func.IF(MatchUp.WinLose == 'W', 1, 0)) / func.count(MatchUp.WinLose)).label('WinPct')). \ join(MatchUp, MatchUp.Player_ID == Player.idplayer).group_by(MatchUp.OpponentRank). \ filter_by(Player_ID=p).order_by(MatchUp.OpponentRank).all() player_graph = db.session.query(Season.SeasonName, Season.SeasonStart, Season.idseason, func.count(MatchUp.idmatchup).label('MatchesPlayed'), func.sum(func.IF(MatchUp.WinLose == 'W', 1, 0)).label('Wins'), func.sum(func.IF(MatchUp.WinLose == 'L', 1, 0)).label('Loses'), (func.sum(func.IF(MatchUp.WinLose == 'W', 1, 0)) / func.count(MatchUp.WinLose)).label('WinPct'), Player.idplayer). \ join(Match, Season.idseason == Match.Season_ID). \ join(MatchUp, Match.idmatch == MatchUp.Match_ID). \ join(Player, MatchUp.Player_ID == Player.idplayer). \ filter_by(idplayer=p). \ group_by(Player.idplayer, Season.SeasonName, Season.SeasonStart, Season.idseason). \ order_by(Season.SeasonStart).all() # Configure horizontal bar chart of player history against the wire chart = pygal.HorizontalStackedBar(show_legend=False, tooltip_fancy_mode=False, print_values=True, width=800, height=300) labels = [] wins = [] loses = [] # Create series lists for the chart.add command # PYGAL_URL is localhost:5000 for testing, main URL for AWS for season in player_graph: labels.append(season.SeasonName) wins.append({ 'value': int(season.Wins), 'color': 'MediumSeaGreen', 'xlink': { 'href': '{}{}'.format( current_app.config['PYGAL_URL'], url_for('main.drilldown', player_id=season.idplayer, season_id=season.idseason, win_loss='W')), 'target': '_parent' }, 'label': "Pct {:.0%}".format(season.WinPct) }) loses.append({ 'value': int(season.Loses), 'color': 'Orange', 'xlink': { 'href': '{}{}'.format( current_app.config['PYGAL_URL'], url_for('main.drilldown', player_id=season.idplayer, season_id=season.idseason, win_loss='L')), 'target': '_parent' }, 'label': "Pct {:.0%}".format(1 - season.WinPct) }) # Build the graph itself chart.x_labels = labels chart.add("Wins", wins) chart.add("Loses", loses) chart = chart.render_data_uri() player_summary = db.session.query(Player.Surname, MatchUp.MyPlayerRank, func.count(MatchUp.idmatchup).label('MatchesPlayed'), func.sum(MatchUp.MyPlayerActual).label('ActRacksWon'), func.sum(MatchUp.OpponentActual).label('ActRacksLost'), (func.sum(MatchUp.MyPlayerActual) / (func.sum(MatchUp.OpponentActual) + func.sum(MatchUp.MyPlayerActual))).label('RackPct'), (func.sum(func.IF(MatchUp.WinLose == 'W', 1, 0)) / func.count(MatchUp.WinLose)).label('WinPct')). \ join(MatchUp, MatchUp.Player_ID == Player.idplayer).group_by(MatchUp.MyPlayerRank).filter_by(Player_ID=p).all() player = Player.query.filter_by(idplayer=p).first() player_history = db.session.query(Match, MatchUp). \ join(MatchUp, Match.idmatch == MatchUp.Match_ID). \ filter(MatchUp.Player_ID == p). \ order_by(Match.MatchDate).all() return render_template('history.html', history=player_history, player=player, details=player_detail, summary=player_summary, chart=chart)
def pandas_to_pygal_StackedMultiBar(data, groupby1, groupby2, aggregate, absolute_values=True, colourstyle=colour_dict["DefaultStyle"], decimal_places=0, fill=False, horizontal=False, print_values=False, rounded_bars=0, stacked=False, title="Test Grouped Bar Chart", value_suffix="", x_label_rotation=0, legend_at_bottom=False, legend_at_bottom_columns=3, agg_type="sum"): ''' Create pygal object ''' if horizontal == True and stacked == True: pyg = pygal.HorizontalStackedBar() elif horizontal == True and stacked == False: pyg = pygal.HorizontalBar() elif horizontal == False and stacked == True: pyg = pygal.StackedBar() else: pyg = pygal.Bar() ''' Transform data for pygal object ''' groupby1_distinct = sorted(data[groupby1].unique()) groupby2_distinct = sorted(data[groupby2].unique()) dict = {} for name in groupby2_distinct: dict[name] = [] for name in groupby2_distinct: for name2 in groupby1_distinct: subset_data = data[(data[groupby1] == name2) & (data[groupby2] == name)] rows_in_subset_data = subset_data.shape[0] aggregate_value = return_aggregate_series(subset_data[aggregate], agg_type) if rows_in_subset_data > 0: dict[name].append(aggregate_value) else: dict[name].append(None) if absolute_values == False: totals = [] dict_values_lists = list(dict.values()) number_of_lists = len(dict_values_lists) number_of_items_per_list = len(dict_values_lists[0]) for index in range(number_of_items_per_list): total = 0 for index2 in range(number_of_lists): current_value = dict_values_lists[index2][index] if current_value is not None: total = total + current_value totals.append(total) percentage_dict = {} for key in dict.keys(): percentage_dict[key] = [] for key in dict.keys(): for index in range(len(dict[key])): numerator = dict[key][index] denominator = totals[index] if numerator is not None and denominator is not None: percentage_dict[key].append(numerator / denominator * 100) else: percentage_dict[key].append(None) ''' Add data to pygal object ''' if absolute_values == True: for key in dict.keys(): pyg.add(key, dict[key]) else: for key in percentage_dict.keys(): pyg.add(key, percentage_dict[key]) ''' Chart configuration options ''' pyg.config.rounded_bars = rounded_bars pyg.config.legend_at_bottom = legend_at_bottom pyg.config.legend_at_bottom_columns = legend_at_bottom_columns pyg.config.style = colourstyle pyg.config.x_labels = groupby1_distinct pyg.config.fill = fill pyg.config.title = title pyg.config.x_label_rotation = x_label_rotation pyg.config.print_values = print_values formatter = "{:,." + str(decimal_places) + "f} " + str(value_suffix) pyg.config.formatter = lambda x: formatter.format(x) ''' Return chart object ''' return pyg
def build_image_temp(coin, start, end, email): # 近期行情 if coin == 'BTC': hq = BitcoinChartsDatas.objects.using('btc').order_by('hisdate') else: hq = LitecoinChartsDatas.objects.using('ltc').order_by('hisdate') hq = hq.filter(hisdate__gte=start, hisdate__lte=end) hq_date = map(lambda x: x.hisdate, hq) if coin == 'BTC': hq_data = map(lambda x: x.price, hq) else: hq_data = map(lambda x: x.price_usd, hq) custom_css = ''' {{ id }}.graph > .background { fill: rgba(255,255,255,0); } {{ id }}.plot > .background { fill: rgba(255,255,255,0); } {{ id }}.title { font-family: Songti; } {{ id }}text { font-family: Songti; } {{ id }}.legends .legend text { font-family: Songti; } {{ id }}.axis text { font-family: Songti; } {{ id }}.axis.y text { font-family: Songti; } {{ id }}#tooltip text { font-family: Songti; } ''' custom_css_file = '/tmp/pygal_temp_custom_style.css' with open(custom_css_file, 'w') as f: f.write(custom_css) config = pygal.Config() config.css.append('file://' + custom_css_file) config.x_value_formatter = lambda x: x.strftime('%-m/%-d') config.max_scale = 7 config.min_scale = 7 config.legend_at_bottom = True hq_chart = pygal.Line(config, title=u'{}行情'.format(coin_name(coin)), show_legend=False) hq_chart.x_labels = hq_date hq_chart.add('', hq_data) hq_path = u'{}chart/{}_hq_{}_{}.png'.format(settings.MEDIA_ROOT, coin, start, end) hq_chart.render_to_png(hq_path) # 账户买卖比例 if coin == 'BTC': qs1 = TBitSpecialAddress.objects.using('btc').filter( address_type=1).only('address') qs2 = TBitSpecialAddress.objects.using('btc').filter( address_type=2).only('address') table = 'blockchain_db.bitcoin_cashflow_output' cursor = connections['btc'].cursor() else: qs1 = TLiteSpecialAddress.objects.using('ltc').filter( address_type=1).only('address') qs2 = TLiteSpecialAddress.objects.using('ltc').filter( address_type=2).only('address') table = 'ltc_db.litecoin_cashflow_output' cursor = connections['ltc'].cursor() addresses1 = map(lambda x: x.address, qs1) addresses2 = map(lambda x: x.address, qs2) sell_sql = ''' SELECT count(*) FROM {0} WHERE (output_value - input_value) < 0 AND address IN %s AND block_time > %s AND block_time < %s ORDER BY block_time DESC '''.format(table) buy_sql = ''' SELECT count(*) FROM {0} WHERE (output_value - input_value) > 0 AND address IN %s AND block_time > %s AND block_time < %s ORDER BY block_time DESC '''.format(table) cursor.execute(sell_sql, [tuple(addresses1), start, end]) sell1 = cursor.fetchone()[0] cursor.execute(sell_sql, [tuple(addresses2), start, end]) sell2 = cursor.fetchone()[0] cursor.execute(buy_sql, [tuple(addresses1), start, end]) buy1 = cursor.fetchone()[0] cursor.execute(buy_sql, [tuple(addresses2), start, end]) buy2 = cursor.fetchone()[0] bar_chart = pygal.HorizontalStackedBar(config, print_values=True, title=u'聪明账户与韭菜账户买卖比例') bar_chart.x_labels = ('', u'聪明账户', u'韭菜账户', '') if buy1 and buy2: bar_chart.add(u'买', (buy1 / (sell1 + buy1), buy2 / (sell2 + buy2))) bar_chart.add(u'卖', (sell1 / (sell1 + buy1), sell2 / (sell2 + buy2))) bar_chart_path = u'{}chart/{}_bar_{}_{}.png'.format( settings.MEDIA_ROOT, coin, start, end) bar_chart.render_to_png(bar_chart_path) # 前5大交易所充值提现 if coin == 'BTC': top5 = [19, 124, 84, 107, 602] recharge = BitExchangeRecharge.objects.using('btc').filter(groupind__in=top5, trans_date__gte=start, trans_date__lte=end)\ .values('trans_date').annotate(sum_recharge=Sum('tot_recharge')).order_by('trans_date') withdraw = BitExchangeWithdraw.objects.using('btc').filter(groupind__in=top5, trans_date__gte=start, trans_date__lte=end)\ .values('trans_date').annotate(sum_withdraw=Sum('tot_withdraw')).order_by('trans_date') else: top5 = [21, 1, 110, 101, 28] recharge = LiteExchangeRecharge.objects.using('ltc').filter(groupind__in=top5, trans_date__gte=start, trans_date__lte=end)\ .values('trans_date').annotate(sum_recharge=Sum('tot_recharge')).order_by('trans_date') withdraw = LiteExchangeWithdraw.objects.using('ltc').filter(groupind__in=top5, trans_date__gte=start, trans_date__lte=end)\ .values('trans_date').annotate(sum_withdraw=Sum('tot_withdraw')).order_by('trans_date') recharge_data = map(lambda x: x.get('sum_recharge'), recharge) x_labels = map(lambda x: x.get('trans_date'), recharge) withdraw_data = map(lambda x: x.get('sum_withdraw'), withdraw) tran_chart = pygal.Line(config, title=u'前5大交易所充值提现') tran_chart.x_labels = x_labels tran_chart.add(u'充值', recharge_data) tran_chart.add(u'提现', withdraw_data) tran_chart_path = u'{}chart/{}_tran_{}_{}.png'.format( settings.MEDIA_ROOT, coin, start, end) tran_chart.render_to_png(tran_chart_path) # 前1000持仓变化 if coin == 'BTC': qs = TBitBalanceRank1000His.objects.using('btc').filter(his_date__gte=start, his_date__lte=end)\ .values('his_date').annotate(sum_balance=Sum('balance')).order_by('his_date') address_qs = TBitBalanceRank1000His.objects.using('btc').filter(his_date__gte=start, his_date__lte=end)\ .values('address').annotate(count=Count('address')).order_by('address') addresses = set(map(lambda x: x.get('address'), address_qs)) org_qs = BitKnewAddress2.objects.using('btc').filter( onoroff=1, address__in=addresses) org_address = map(lambda x: x.address, org_qs) org_exclude_qs = TBitBalanceRank1000His.objects.using('btc').filter(his_date__gte=start, his_date__lte=end).exclude(address__in=org_address)\ .values('his_date').annotate(sum_balance=Sum('balance')).order_by('his_date') else: qs = TLiteBalanceRank1000His.objects.using('ltc').filter(his_date__gte=start, his_date__lte=end)\ .values('his_date').annotate(sum_balance=Sum('balance')).order_by('his_date') address_qs = TLiteBalanceRank1000His.objects.using('ltc').filter(his_date__gte=start, his_date__lte=end)\ .values('address').annotate(count=Count('address')).order_by('address') addresses = set(map(lambda x: x.get('address'), address_qs)) org_qs = LiteKnewAddress2.objects.using('ltc').filter( onoroff=1, address__in=addresses) org_address = map(lambda x: x.address, org_qs) org_exclude_qs = TLiteBalanceRank1000His.objects.using('ltc').filter(his_date__gte=start, his_date__lte=end).exclude(address__in=org_address)\ .values('his_date').annotate(sum_balance=Sum('balance')).order_by('his_date') hold_data = map(lambda x: x.get('sum_balance'), qs) org_exclude_hold_data = map(lambda x: x.get('sum_balance'), org_exclude_qs) x_labels = map(lambda x: x.get('his_date'), qs) hold_chart = pygal.Line(config, fill=True, title=u'前1000地址累计持仓') hold_chart.x_labels = x_labels hold_chart.add(u'前1000持仓', hold_data) hold_chart.add(u'前1000(排除交易所)', org_exclude_hold_data) hold_chart_path = u'{}chart/{}_hold_{}_{}.png'.format( settings.MEDIA_ROOT, coin, start, end) hold_chart.render_to_png(hold_chart_path) # 用户类型持仓 if coin == 'BTC': all_balance = TBitBalanceRank1000His.objects.using('btc').filter(his_date__gte=start, his_date__lte=end)\ .aggregate(sum_balance=Sum('balance')).get('sum_balance') address_qs = TBitBalanceRank1000His.objects.using('btc').filter(his_date__gte=start, his_date__lte=end)\ .values('address').annotate(count=Count('address')).order_by('address') addresses = set(map(lambda x: x.get('address'), address_qs)) miner_qs = BitMinerlist.objects.using('btc').filter( address__in=addresses) miner_address = map(lambda x: x.address, miner_qs) org_qs = BitKnewAddress2.objects.using('btc').filter( onoroff=1, address__in=addresses) org_address = map(lambda x: x.address, org_qs) org_balance = TBitBalanceRank1000His.objects.using('btc').filter(his_date__gte=start, his_date__lte=end).filter(address__in=org_address)\ .aggregate(sum_balance=Sum('balance')).get('sum_balance', 0) miner_balance = TBitBalanceRank1000His.objects.using('btc').filter(his_date__gte=start, his_date__lte=end).filter(address__in=miner_address)\ .aggregate(sum_balance=Sum('balance')).get('sum_balance', 0) else: all_balance = TLiteBalanceRank1000His.objects.using('ltc').filter(his_date__gte=start, his_date__lte=end)\ .aggregate(sum_balance=Sum('balance')).get('sum_balance') address_qs = TLiteBalanceRank1000His.objects.using('ltc').filter(his_date__gte=start, his_date__lte=end)\ .values('address').annotate(count=Count('address')).order_by('address') addresses = set(map(lambda x: x.get('address'), address_qs)) miner_qs = LiteMinerlist.objects.using('ltc').filter( address__in=addresses) miner_address = map(lambda x: x.address, miner_qs) org_qs = LiteKnewAddress2.objects.using('ltc').filter( onoroff=1, address__in=addresses) org_address = map(lambda x: x.address, org_qs) org_balance = TLiteBalanceRank1000His.objects.using('ltc').filter(his_date__gte=start, his_date__lte=end).filter(address__in=org_address)\ .aggregate(sum_balance=Sum('balance')).get('sum_balance', 0) miner_balance = TLiteBalanceRank1000His.objects.using('ltc').filter(his_date__gte=start, his_date__lte=end).filter(address__in=miner_address)\ .aggregate(sum_balance=Sum('balance')).get('sum_balance', 0) pie_chart = pygal.Pie(config, print_values=True, title=u'用户类型持仓占比') pie_chart.value_formatter = lambda x: '{:.2%}'.format(x) pie_chart.legend_at_bottom_columns = 3 if all_balance: org_data = org_balance / all_balance miner_data = miner_balance / all_balance pie_chart.add(u'交易所', org_data) pie_chart.add(u'矿机', miner_data) pie_chart.add(u'其他', 1 - org_data - miner_data) pie_chart_path = u'{}chart/{}_pie_{}_{}.png'.format( settings.MEDIA_ROOT, coin, start, end) pie_chart.render_to_png(pie_chart_path) send_mail_files(u'{}至{}{}模版'.format(start, end, coin_name(coin)), [ email, ], [ hq_path, bar_chart_path, tran_chart_path, hold_chart_path, pie_chart_path ])
def tfhoursbar(self): #datSearchStartDate = datetime(2015, 11, 6, 11, 30) #datSearchEndDate = datetime(2015, 11, 6, 21, 0) datSearchEndDate = datetime.now() datSearchStartDate = datSearchEndDate - timedelta(days=1) try: intFrom = int(self.request.vars['fromdate']) intTo = int(self.request.vars['todate']) datSearchStartDate = (datetime(1970, 1, 1) + timedelta(0, intFrom)) datSearchEndDate = (datetime(1970, 1, 1) + timedelta(0, intTo)) except: pass intRegStartNr = 0 intRegEndNr = 0 intMachineID = int(self.request.vars['machineid']) intCountryNr = int(self.request.vars['countrynr']) intPlantNr = int(self.request.vars['plantnr']) intSubPlantNr = int(self.request.vars['subplantnr']) intDepartmentNr = int(self.request.vars['departmentnr']) self.response.headers['Content-Type'] = 'image/svg+xml' style = Style(background='transparent', \ no_data_font_size=12) tfhourbar_chart = pygal.HorizontalStackedBar(style = style, \ height=90, \ width=1000, \ show_x_labels=True, \ show_y_labels=False, \ show_legend=False, \ show_y_guides=False) try: intRegStartNr = self.dboee((self.dboee.tblOee_Reg.fldOeeMachineID == intMachineID) & \ (self.dboee.tblOee_Reg.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_Reg.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeDepartmentID == intDepartmentNr) & \ ((self.dboee.tblOee_Reg.fldOeeStartDateTime <= datSearchStartDate) & \ (self.dboee.tblOee_Reg.fldOeeEndDateTime >= datSearchStartDate))).select(self.dboee.tblOee_Reg.ALL, \ orderby=self.dboee.tblOee_Reg.fldOeeRegNr, \ limitby=(0,1))[0].fldOeeRegNr except: rows = self.dboee((self.dboee.tblOee_Reg.fldOeeMachineID == intMachineID) & \ (self.dboee.tblOee_Reg.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_Reg.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeDepartmentID == intDepartmentNr) & \ (self.dboee.tblOee_Reg.fldOeeStartDateTime <= datSearchStartDate)).select(self.dboee.tblOee_Reg.ALL, \ orderby=~self.dboee.tblOee_Reg.fldOeeRegNr, \ limitby=(0,1)) for row in rows: intRegStartNr = row.fldOeeRegNr try: intRegEndNr = self.dboee((self.dboee.tblOee_Reg.fldOeeMachineID == intMachineID) & \ (self.dboee.tblOee_Reg.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_Reg.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeDepartmentID == intDepartmentNr) & \ (self.dboee.tblOee_Reg.fldOeeStartDateTime <= datSearchEndDate) & \ (self.dboee.tblOee_Reg.fldOeeEndDateTime >= datSearchEndDate)).select(self.dboee.tblOee_Reg.ALL, \ orderby=self.dboee.tblOee_Reg.fldOeeRegNr, \ limitby=(0,1))[0].fldOeeRegNr except: rows = self.dboee((self.dboee.tblOee_Reg.fldOeeMachineID == intMachineID) & \ (self.dboee.tblOee_Reg.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_Reg.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeDepartmentID == intDepartmentNr) & \ (self.dboee.tblOee_Reg.fldOeeStartDateTime <= datSearchEndDate)).select(self.dboee.tblOee_Reg.ALL, \ orderby=~self.dboee.tblOee_Reg.fldOeeRegNr, \ limitby=(0,1)) for row in rows: intRegEndNr = row.fldOeeRegNr try: intRowCount = self.dboee((self.dboee.tblOee_Reg.fldOeeMachineID == intMachineID) & \ (self.dboee.tblOee_Reg.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_Reg.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeDepartmentID == intDepartmentNr) & \ (self.dboee.tblOee_Reg.fldOeeRegNr >= intRegStartNr) & \ (self.dboee.tblOee_Reg.fldOeeRegNr <= intRegEndNr)).count() except: intRowCount = 0 rows = self.dboee((self.dboee.tblOee_Reg.fldOeeMachineID == intMachineID) & \ (self.dboee.tblOee_Reg.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_Reg.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_Reg.fldOeeDepartmentID == intDepartmentNr) & \ (self.dboee.tblOee_Reg.fldOeeRegNr >= intRegStartNr) & \ (self.dboee.tblOee_Reg.fldOeeRegNr <= intRegEndNr)).select(self.dboee.tblOee_Reg.ALL, \ orderby=self.dboee.tblOee_Reg.fldOeeRegNr) datStart = datetime.now() datEnd = datetime.now() intSeconds = 0 intX = 0 strTest = "" for row in rows: if intX == 0: datEnd = row.fldOeeStartDateTime intX += 1 datStart = row.fldOeeStartDateTime datDifference = datStart - datEnd intSeconds = datDifference.seconds if intSeconds >= 10: tfhourbar_chart.add('No registered data', [{ 'value': intSeconds / 60, 'color': 'rgba(115, 77, 77, 1)' }]) try: datEnd = row.fldOeeEndDateTime if datEnd is None: datEnd = row.fldOeeStartDateTime + timedelta( minutes=int(row.fldOeeActivityDuration) / 60) except: datEnd = row.fldOeeStartDateTime strColor = self.mfColor(row.fldOeeMachineStatusID, row.fldOeeActivityGroupID) if intX == intRowCount - 1: datEnd = datSearchEndDate datDifference = datEnd - datStart intSeconds = datDifference.seconds bar_chart.add('SQL data', [{ 'value': intSeconds / 60, 'color': strColor }]) else: strColor = self.mfColor(row.fldOeeMachineStatusID, row.fldOeeActivityGroupID) tfhourbar_chart.add(row.fldOeeActivityDescription, [{ 'value': (row.fldOeeActivityDuration / 60), 'color': strColor }]) return tfhourbar_chart.render()
import pygal #创建水平叠加柱状图 bar = pygal.HorizontalStackedBar() #设置标题 bar.title = 'Fruit Sale Analysis' #添加数据 years = [str(i) for i in range(2011, 2020)] print(years) banana = [17.89, 18.23, 20.45, 19.25, 20.35, 21.23, 19.84, 20.12, 19.88] apple = [12.89, 15.56, 16.45, 14.89, 13.98, 15.23, 14.89, 16.01, 15.98] orange = [8.89, 9.23, 10.45, 11.25, 11.35, 11.23, 15.84, 17.12, 20.11] bar.add('Banana', banana) bar.add('Apple', apple) bar.add('Orange', orange) bar.x_labels = years bar.y_title = 'Year' bar.x_title = 'Sale(KRMB)' #设置X轴标签选择度数 bar.x_label_rotation = -45 #设置图例放在下面 #bar.legend_at_bottom = True #设置四周的页边距(也可单独设置:margin_bottom, margin_top, margin_left, margin_right) bar.margin = 5 #显示Y轴的网格线 bar.show_y_guides = True #显示X轴的网格线 bar.show_x_guides = True #输出图片 bar.render_to_file('fruit3.svg')
def game(): # Is the game active? If tags have not been added, exit gracefully by redirecting to the home page if current_user.link is None: return redirect(url_for('index')) web_link = request.args.get('u') if web_link is not None: # If a link was provided target_user = User.query.filter(User.link == web_link).first() if target_user is None: flash('Invalid code', 'danger') else: # Find the tag this_tag = Tag.query.filter( and_(Tag.source == current_user.id, Tag.destination == target_user.id)).first() if this_tag is None: flash('Not one of your targets', 'danger') else: if this_tag.time is None: this_tag.time = datetime.datetime.now() db.session.add(this_tag) db.session.commit() flash('Scan successful', 'success') # Get the team scores team_data = [] for team in [0, 1, 2]: users_on_team = User.query.filter(User.team == team).all() team_tags = Tag.query.filter( Tag.source.in_([x.id for x in users_on_team])).all() team_score = float(len([x for x in team_tags if x.time is not None ])) / len(team_tags) team_data.append((team_names[team], team_score)) chart_style = Style(background='transparent', plot_background='transparent', opacity='.6', opacity_hover='.9', transition='400ms ease-in') bar_chart = pygal.HorizontalStackedBar(range=(0, 100), style=chart_style, height=200, show_legend=False) bar_chart.title = "Scoreboard" bar_chart.x_title = "Scan completion (%)" bar_chart.x_labels = [x[0] for x in team_data] bar_chart.add('Scores', [100 * x[1] for x in team_data]) chart = bar_chart.render().decode('utf-8') user_team = team_names[current_user.team] # Get the user's tags user_tags = Tag.query.filter(Tag.source == current_user.id).order_by( desc(Tag.destination)).all() user_targets = User.query.filter( User.id.in_([x.destination for x in user_tags])).order_by(desc(User.id)).all() tag_data = zip(user_targets, user_tags) return render_template('game.html', chart=chart, user_team=user_team, tag_data=tag_data)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 官网:http://www.pygal.org/en/stable/documentation/types/bar.html import pygal # 创建条形图的类型 #bar = pygal.Bar() # 简单的条形图 #bar = pygal.StackedBar() # 叠加的条形图 #bar = pygal.HorizontalBar() # 水平条形图 bar = pygal.HorizontalStackedBar() # 水平叠加的图形图 bar.title = 'pygal_Bar' bar.x_title = 'x_title' bar.y_title = 'y_title' bar.x_labels = map(str, range(1, 7)) bar.add('Example1', [155, 167, 168, 170, 159, 181]) bar.add('Example2', [55, 67, 68, 70, 59, 81]) bar.add('Example3', [105, 17, 178, 100, 179, 81]) bar.render_to_file('pygal_Bar.svg')
import pygal bar_chart = pygal.HorizontalStackedBar() bar_chart.title = "Horizontal Stacked Bar" bar_chart.add('test', [0, 1, 2, 3, 4, 5, 6, 7, 8]) bar_chart.render_to_file('Stacked_Bar.svg')
def dashboard(request): pygal.style.DarkStyle.label_font_size = 20 pygal.style.DarkStyle.legend_font_size = 20 pygal.style.DarkStyle.major_label_font_size = 20 pygal.style.DarkStyle.value_label_font_size = 20 pygal.style.DarkStyle.tooltip_font_size = 20 # Winners line_chart = pygal.HorizontalBar(style=pygal.style.DarkStyle) # line_chart.title = 'Total Number of Wins' for player in Player.objects.all(): line_chart.add(player.screen_name, Game.objects.filter( Q(player_instigator=player, instigator_won=True) | Q(player_confederate=player, instigator_won=False) ).count()) winners_chart = line_chart.render_data_uri() # Winners as a percentage # Yes I couls store the resutl form before... but.. win = [] lose = [] players = [] table = [] for player in Player.objects.all(): players.append(player.screen_name) wins = (Game.objects.filter( Q(player_instigator=player, instigator_won=True) | Q(player_confederate=player, instigator_won=False) ).count()) loses = (Game.objects.filter( Q(player_instigator=player, instigator_won=False) | Q(player_confederate=player, instigator_won=True) ).count()) total = wins + loses win_percent = round(100*wins/total,1) lose_percent = round(100*loses/total,1) table.append((player.screen_name, wins, loses, win_percent, lose_percent, total)) leader_data = sort_table(table, (3,1)) # Ok now we have the leaderboard data in a nice table # Make into markdown leader_md = '| | Win Percentage | Total Wins | \n| - |:-:| -:|\n' for d in leader_data[:3]: leader_md = leader_md + '| [@' + d[0] + '](http://twitter.com/share?text=Ok%20@' + d[0] + '%20Your%20on%20the%20Leaderboard,%20lets%20duel%20with%20@RPSrobot%20as%20referee%20) |' + str(d[3]) + '|' + str(d[1]) + '| \n' #<a class="twitter popup" href="http://twitter.com/share?text=This%20is%20so%20easy">Tweet</a> # Make into chart win = [] lose = [] players = [] for d in reversed(leader_data): players.append(d[0]) win.append(d[3]) lose.append(d[4]) line_chart = pygal.HorizontalStackedBar(style=pygal.style.DarkStyle) line_chart.x_labels = players line_chart.add('Win', win) line_chart.add('Lose', lose) winners_percentage = line_chart.render_data_uri() # Choices pie_chart = pygal.Pie(style=pygal.style.DarkStyle) # pie_chart.title = 'Choices selected in %' not_n = Game.objects.filter(~Q(instigator_rpc ='N')).count() + Game.objects.filter(~Q(confederate_rpc='N')).count() for c in Game.RPS: if c[0] != 'N': pie_chart.add(c[1],round(100*Game.objects.filter(Q(instigator_rpc=c[0]) | Q(confederate_rpc=c[0]) ).count()/not_n, 2) ) choices_chart = pie_chart.render_data_uri() return render(request, 'dashboard.html', context = {'winners_chart': winners_chart, 'choices_chart': choices_chart, 'winners_percentage': winners_percentage, 'leader_md': leader_md})