def dot_graph(data): dot_chart = pg.Dot(x_label_rotation=30, dots_size=100) dot_chart.title = 'Amount of calcories in each Starbucks Beverage calcories' dot_chart.x_labels = [i for i in data] for i in data: dot_chart.add(i, data[i]) dot_chart.render_to_file('D:/chart.svg')
def make_chart(username, style='default', **args): if isinstance(style, list): style = style[0] style = pygal.style.styles[style] chart = pygal.Dot( x_label_rotation=90, style=style, ) chart.title = title_template % username try: user = m.User.query.filter(m.User.name == username).one() except NoResultFound: user = None base = datetime.today() weekrange = list(reversed(range(52))) chart.x_labels = [ "Week %02i %i" % (date.isocalendar()[1], date.isocalendar()[0]) for date in (base - timedelta(weeks=i) for i in weekrange) ] for day in [6, 0, 1, 2, 3, 4, 5]: print "Building series for %s." % calendar.day_name[day] offset = timedelta(days=(base.weekday() - day) % 7) weeks = (base - offset - timedelta(weeks=i) for i in weekrange) chart.add(calendar.day_name[day], [message_count(user, date) for date in weeks]) return chart
def plot_bubble_centralities_chart_V2(trusted_src_dict,other_src1_dict,other_src2_dict,src_labels): trusted_src = [] other_src1= [] other_src2= [] labels = [] for key in trusted_src_dict.keys(): labels.append(key) trusted_src.append(trusted_src_dict[key]) other_src1.append(other_src1_dict[key]) other_src2.append(other_src2_dict[key]) custom_style = Style( background = 'white', plot_background='white', value_label_font_size = 14, value_font_size = 14, major_label_font_size = 14 , label_font_size = 14) dot_chart = pygal.Dot(x_label_rotation=90,logarithmic=True,style = custom_style,width=800,height=700) dot_chart.title = '' dot_chart.x_labels = labels dot_chart.add(src_labels[0], trusted_src ) dot_chart.add(src_labels[1], other_src1) dot_chart.add(src_labels[2], other_src2) dot_chart.render_to_png('./sample_bubble.png')
def region(): """Make a graph by use pygal to region.svg""" wb = load_workbook(filename = 'region.xlsx') sheet_ranges = wb['Sheet1'] level = [] allr = [] ktm = [] mid = [] north = [] esan = [] south = [] for i in range(2, 12): cell_a = 'A'+str(i) cell_b = 'B'+str(i) cell_c = 'C'+str(i) cell_d = 'D'+str(i) cell_e = 'E'+str(i) cell_f = 'F'+str(i) cell_g = 'G'+str(i) level.append(sheet_ranges[cell_a].value) ktm.append(sheet_ranges[cell_c].value) mid.append(sheet_ranges[cell_d].value) north.append(sheet_ranges[cell_e].value) esan.append(sheet_ranges[cell_f].value) south.append(sheet_ranges[cell_g].value) line_chart = pygal.Dot(fill=True, interpolate='cubic', style=DarkStyle) line_chart.title = 'Static of Smoker sorted by Region & Education' line_chart.x_labels = map(str, level) line_chart.add('กรุงเทพฯ', ktm) line_chart.add('กลาง', mid) line_chart.add('เหนือ', north) line_chart.add('อิสาน', esan) line_chart.add('ใต้', south) line_chart.render_to_file('Graph_region.svg') age()
def graph(): _charts = [ pygal.Line(), pygal.Bar(), pygal.Histogram(), pygal.XY(), pygal.Pie(), pygal.Radar(), pygal.Box(), pygal.Dot(), pygal.Funnel(), pygal.SolidGauge(), pygal.Gauge(), pygal.Pyramid(), pygal.Treemap() ] charts = [] for chart in _charts: chart.title = '% Change Coolness of programming languages over time.' chart.x_labels = ['2011', '2012', '2013', '2014', '2015', '2016'] chart.add('Python', [15, 31, 89, 200, 356, 900]) chart.add('Java', [15, 45, 76, 80, 91, 95]) chart.add('C++', [5, 51, 54, 102, 150, 201]) chart.add('All others combined!', [5, 15, 21, 55, 92, 105]) charts.append(chart.render_data_uri()) return render_template('part2/graph.html', charts=charts, root_path=root_path)
def make_wordnet_plot(src_dict): custom_style = Style(background='white', plot_background='white', value_label_font_size=14, value_font_size=14, major_label_font_size=14, label_font_size=14, colors=('#E853A0', '#E8537A', '#E95355', '#E87653', '#E89B53')) dot_chart = pygal.Dot(x_label_rotation=90, logarithmic=True, style=custom_style) x_labels = [] y_labels_values = [] length = len(src_dict) for key in src_dict.keys(): x_labels.append(key) y_label = src_dict[key][0] ind = x_labels.index(key) y_values = [0] * length y_values[ind] = src_dict[key][1] y_labels_values.append([y_label, y_values]) #add to dot chart dot_chart.x_labels = x_labels for item in y_labels_values: lab = item[0] vals = item[1] #print(lab) dot_chart.add(lab, vals) dot_chart.render()
def prepare_dot_chart(): result, years, __ = languageStatistic() my_style = define_style() my_config = pygal.Config() my_config.x_label_rotation = 45 my_config.title_font_size = 30 my_config.label_font_size = 25 my_config.major_label_font_size = 20 my_config.truncate_label = 15 my_config.show_y_guides = True my_config.width = 1300 dot_chart = pygal.Dot(my_config, style=my_style) dot_chart.title = 'Timeline analysis' year_start, year_end = min(years), max(years) dot_chart.x_labels = map(str, range(year_start, year_end + 1)) for i, lang in enumerate(result['Language']): cut_lang = result.loc[:, result.columns != 'Language'] values_yearly = list(cut_lang.iloc[i]) dot_chart.add(lang, values_yearly) return dot_chart
def blue_style_chart(): dot = pygal.Dot(x_label_rotation=30, style=BlueStyle) dot.title = 'DOT CHART TEST' dot.x_labels = ['DOT TARGET {}'.format(x) for x in range(10)] for i in range(3): dot.add('Item {}'.format(i), get_random_data(size)) dot.add('Neg exists', [x - 100 for x in get_random_data(size)]) dot.render_to_file(get_file_name(inspect.stack()[0][3]))
def PlotItems(df): dot_chart = pygal.Dot(x_label_rotation=30) #line_chart.title = '每月支出' for i in range(0, 4): data = df.ix[i].values for j in range(2, 14): if math.isnan(data[j]): data[j] = 0 dot_chart.add(df.ix[i, 1], data[2:len(data)]) dot_chart.x_labels = map(str, range(1, 13)) dot_chart.render_to_file("部分支出情况.svg")
def svg_plot(): print('\n q1 Bubble chart in SVG') bubble_chart = pygal.Dot(title='Sample Bubble Chart') bubble_chart.x_labels = ['sample1', 'sample2', 'sample3'] bubble_chart.y_labels = [0, 10, 20, 30, 40, 50, 60] bubble_chart.add('10', [0, 0, 34]) bubble_chart.add('30', [0, 89, 0]) bubble_chart.add('50', [51, 0, 0]) bubble_chart.render_to_file('images/bubble_chart.svg') print( '\n q2 Draw a scatterplot of rank vs votes for every movie with at least 10,000 votes' ) imdb_df = pd.read_csv('data/imdb.csv', header=0, converters={ 'rating': float, 'num_votes': int, 'year': int }) votes_over_10000 = imdb_df.loc[imdb_df['num_votes'] >= 10000] votes_over_10000.reset_index() mean_votes = votes_over_10000['num_votes'].mean() r_and_nv = votes_over_10000[['num_votes', 'rating']] r_and_nv = list(map(tuple, r_and_nv.values)) scatter(r_and_nv[:150], title='IMDB #votes vs. Rating', label='', x_label='Number of votes', y_label='Rating', file_name='scatter_IMDB.svg') # r_and_nv = list(map(lambda x: (x[0]/mean_votes, x[1]), r_and_nv)) # scatter(r_and_nv[:150], title='IMDB #votes vs. Normalized Rating', label='', # x_label='Number of votes', y_label='Rating', file_name='scatter_post_norm.svg') print('\n q3 Draw a correlation matrix of any 30 stocks on the Sensex') stocks = pd.DataFrame() data_dir = 'data/prices/' pathlist = Path(data_dir).glob('*.csv') for p in pathlist: name = str(p).split('\\')[-1].split('.')[0] temp_df = pd.read_csv(p, index_col=0, header=0) closing_price = np.array(temp_df['closing']) stocks[name] = pd.Series(closing_price) print(stocks.head()) stocks = stocks.sample(30, axis=1) corr = stocks.corr() colormap = sns.diverging_palette(10, 150, as_cmap=True) corr_plot = sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, cmap=colormap) fig = corr_plot.get_figure() fig.savefig('images/corr.svg')
def exTrendAll(username): chart = pygal.Dot(show_legend=False) exAllData = getEx(username) chart.x_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'AVG'] if exAllData: yearList = set(x[0] for x in exAllData) for year in reversed(sorted(yearList)): expenses = [x[1] for x in exAllData if x[0] == year] if len(expenses) == 12: expenses.append(int(sum(expenses)/len(expenses))) chart.add('%s' % year, expenses) else: chart.add('line', []) return chart.render_data_uri()
def categoryAllGraphDot(username, category): chart = pygal.Dot(show_legend=False) data = getCategoryStatsAllYears(username, category) chart.x_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'AVG'] if data: for row in data: if row: year = set(x[0] for x in row if x[0] is not None) expenses = [x[1] for x in row] expenses.append(int(sum(expenses)/len(expenses))) chart.add('%s' % next(iter(year)), expenses) else: chart.add('line',[]) return chart.render_data_uri()
def _chart_commits_hour_week(self): """Generate dot chart with commits by hour of week.""" # format of lines in stdout: Fri, 15 Mar 2013 18:27:55 +0100 stdout = self._git_command_log(['--date=rfc', '--pretty=format:%ad']) commits = {day: {'{0:02d}'.format(hour): 0 for hour in range(0, 24)} for day in self.weekdays} for line in stdout: wday, _, _, _, hour, _ = line.split() commits[wday[:-1]][hour.split(':')[0]] += 1 dot_chart = pygal.Dot(style=self.style, js=self.javascript) dot_chart.title = self.title dot_chart.x_labels = ['{0:02d}'.format(hh) for hh in range(0, 24)] for day in self.weekdays: dot_chart.add(day, commits[day]) self._render(dot_chart) return True
def plot_emotion_dot_chart(): date_strings = [ 'October 26', 'October 27', 'October 28', 'October 29', 'October 30', 'October 31', 'November 1', 'November 2', 'November 3', 'November 4', 'November 5', 'November 6', 'November 7', 'November 8', 'November 9', 'November 10', 'November 11', 'November 12', 'November 13', 'November 14', 'November 15', 'November 16', 'November 17', 'November 18', 'November 19', 'November 20', 'November 21', 'November 22', 'November 23' ] input_files = [] for day in date_strings: date_string = '-'.join(day.split(' ')) input_file = '{}-emotions.json'.format(date_string) input_files.append(input_file) dot_chart = pygal.Dot(x_label_rotation=30) dot_chart.title = 'Daily Emotion' dot_chart.x_labels = date_strings emotions = [ 'anger', 'anticipation', 'disgust', 'fear', 'joy', 'sadness', 'surprise', 'trust', 'positive', 'negative' ] dictionary = dict() for em in emotions: dictionary[em] = [] for f in input_files: file = open(f, 'r') data = json.loads(file.readline()) file.close() for em in emotions: dictionary[em].append(sum(data[em].values())) # norm = mpl.colors.Normalize(vmin=-1.,vmax=1.) for key in dictionary.keys(): dot_chart.add(key, dictionary[key]) dot_chart.render_to_file('../Images/Emotion/All-Emotions.svg')
def stat_image(data, title, output, c1, num): time, key, value, order = [], [], [], [] count = 0 #print data for item in data: time.append(item[0].encode('utf-8')) key.append(item[1].encode('utf-8')) value.append(item[2]) count += 1 order.append(str(count)) if count >= num: break dot_chart = pygal.Dot(x_label_rotation=30, style=LightStyle, height=400) dot_chart.title = title dot_chart.x_labels = key dot_chart.add(c1, value) dot_chart.render_to_png( os.environ.get('DBNS_HOME') + "/report/image/" + output)
def print_visual_dots(title, print_list): """Prints the given list in dot style Keyword arguments: print_list -- the list which has to be printed """ countries = [] numbers = [] for item in print_list: countries.append(item[0]) numbers.append(int(item[1]) / 1000000) dot_chart = pygal.Dot(x_label_rotation=30) dot_chart.title = title dot_chart.x_labels = countries dot_chart.add('Countries', numbers) dot_chart.render_in_browser()
def generate(): firm = pd.read_csv('firm.csv') firm = firm.fillna(method='ffill') firm = firm.fillna(method='bfill') graph = pg.Line(width=800, height=400, explicit_size=True, dots_size=1) graph.add('price', firm['_price']) graph.render_in_browser() household = pd.read_csv('panel_household.csv') household = household.fillna(method='ffill') household = household.fillna(method='bfill') graph = pg.Dot(width=800, height=400, explicit_size=True, dots_size=1) for i in range(10): graph.add('Household: %i cookies' % i, household[household['id'] == i]['cookies']) graph.render_in_browser()
def make_dotplot(alldistprops, sortby, dotplotfile): print("----make_dotplot") alldistprops = alldistprops.T alldistprops = alldistprops.sort_values(sortby, axis=0, ascending="False") alldistprops = alldistprops.T dotplot = pygal.Dot(style=threeway_style, show_legend=False, legend_at_bottom=True, legend_at_bottom_columns=3, show_y_guides=True, show_x_guides=False, x_label_rotation=60, title="Vergleich dreier Gruppen\n(Anteil der Segmente pro Gruppe)", x_title="Distinktive Types", y_title="Textgruppen") distfeatures = alldistprops.columns dotplot.x_labels = distfeatures for i in range(0,3): grouplabel = alldistprops.index[i] distprops = list(alldistprops.loc[alldistprops.index[i],:]) dotplot.add(grouplabel, distprops) dotplot.render_to_file(dotplotfile)
def return_two_tier_chart(data, group_primary, group_secondary, aggregate_by, aggregate_type, chart_type, custom_config=None, custom_style=None): """Return a pygal Line chart from a pandas dataframe.""" if chart_type == 'line': chart = pygal.Line() elif chart_type == 'dot': chart = pygal.Dot() elif chart_type == 'grouped bar': chart = pygal.Bar() elif chart_type == 'stacked bar': chart = pygal.StackedBar() elif chart_type == 'stacked line': chart = pygal.StackedLine() elif chart_type == 'radar': chart = pygal.Radar() # Set custom style and config if exists if custom_config: chart.config = custom_config if custom_style: chart.style = custom_style # Transform dataframe into dictionary using helper function dictionary = return_data_tier2(data, group_primary, group_secondary, aggregate_by, aggregate_type) # Add data to pygal object [chart.add(key, values) for key, values in dictionary['data'].items()] chart.x_labels = dictionary['labels'] # Return chart object return chart
def details(request, user_name): '''Displays details about a profile''' usr = get_object_or_404(User, username=user_name) try: profile = usr.get_profile() bans = Ban.objects.filter(user=usr).order_by('-pubdate') except SiteProfileNotAvailable: raise Http404 #refresh moderation chart dot_chart = pygal.Dot(x_label_rotation=30) dot_chart.title = u'Messages postés par période' dot_chart.x_labels = [ u'Dimanche', u'Lundi', u'Mardi', u'Mercredi', u'Jeudi', u'Vendredi', u'Samedi' ] dot_chart.show_legend = False dates = date_to_chart(profile.get_posts()) for i in range(0, 24): dot_chart.add(str(i) + ' h', dates[(i + 1) % 24]) img_path = os.path.join(settings.MEDIA_ROOT, 'pygal') if not os.path.isdir(img_path): os.makedirs(img_path, mode=0777) fchart = os.path.join(img_path, 'mod-{}.svg'.format(str(usr.pk))) dot_chart.render_to_file(fchart) return render_template('member/profile.html', { 'usr': usr, 'profile': profile, 'bans': bans })
def get_all_faculty(): if request.method=="POST": profname=session['username'] courses=Course.query.filter(Course.profname==profname).all() selectcourse=request.form.get('select1') print(selectcourse) lis=[x for x in range(1,11)] responses=DisplayForm.query.filter(DisplayForm.courseid==selectcourse).all() print(responses) resp=[] repof=[] repo2f=[] if selectcourse: if responses is not None: count=0 graph1=pygal.Dot() graph1.title='% Course Rating' graph1.x_labels=lis for i in responses: print("i is") print(i) count=count+1 selected=i.ans selected2=i.subj resp=selected.split(',') resp2=selected2.split('&(a!3') repo=[] repo2=[] for j in resp: repo.append(ord(j)-48) for j in resp2: repo2.append(j) print(repo) print(repo2) print(resp) repof=repo repo2f=repo2 print(resp2) graph1.add(str("response"+str(count)),repo) graph_data1=graph1.render_data_uri() questions=Form.query.filter(Form.courseid==selectcourse).first() q='' q2='' repo=[] if questions is not None: q=questions.questions q2=questions.sub ques=[] ques2=[] if q: print(q) ques=q.split(',') print(ques) if q2: print(q2) ques2=q2.split(',') print(ques2) selectresponse2=request.form.get('select2') resp=[] repo=[] repo2=[] if selectresponse2: print(selectresponse2) selponse=DisplayForm.query.filter(DisplayForm.subj==selectresponse2).first() selectresponse=selponse.ans print(selectresponse) resp=selectresponse.split(',') repo2=selectresponse2.split('&(a!3') for i in resp: repo.append(ord(i)-48) print(repo) print(repo2) graph=pygal.Bar() graph.title='% Score' graph.x_labels=lis graph.add(str(selectcourse),repo) graph_data=graph.render_data_uri() return render_template("/professors/rating.html", courses=courses,responses=responses, questions=ques,questions2=ques2,selectresponse=repo, selectresponse2=repo2,selectcourse=selectcourse, graph_data=graph_data,graph_data1=graph_data1) if selectcourse and responses is not None: return render_template("/professors/rating.html", courses=courses,questions2=ques2,responses=responses, questions=ques,selectresponse=repo,selectresponse2=repo2 ,selectcourse=selectcourse,graph_data1=graph_data1) return render_template("/professors/rating.html", courses=courses,questions2=ques2,responses=responses, questions=ques,selectresponse=repo,selectresponse2=repo2 ,selectcourse=selectcourse)
import pygal '''这个是点图''' # x轴数据 x_data = ['2011', '2012', '2013', '2014', '2015', '2016', '2017'] # 构造数据 y_data = [58000, 60200, 63000, 71000, 84000, 90500, 107000] y_data2 = [52000, 54200, 51500, 58300, 56800, 59500, 62700] # 创建pygal.Dot对象(点图) dot = pygal.Dot() dot.dots_size = 5 # 添加两组数据 dot.add('本科', y_data) dot.add('专科', y_data2) # 设置X轴的刻度值 dot.x_labels = x_data # 重新设置Y轴的刻度值 dot.y_labels = ['本科', '专科'] # 设置Y轴刻度值的旋转角度 dot.y_label_rotation = 45 dot.title = '历年学校毕业生就业情况' # 设置X轴的标题 dot.x_title = '年份' # 设置将图例放在底部 dot.legend_at_bottom = True # 指定将数据图输出到SVG文件中 dot.render_to_file('fk_books.svg')
def details(request, user_name): """Displays details about a profile.""" usr = get_object_or_404(User, username=user_name) try: profile = usr.profile bans = Ban.objects.filter(user=usr).order_by("-pubdate") except SiteProfileNotAvailable: raise Http404 # refresh moderation chart dot_chart = pygal.Dot(x_label_rotation=30) dot_chart.title = u"Messages postés par période" dot_chart.x_labels = [ u"Dimanche", u"Lundi", u"Mardi", u"Mercredi", u"Jeudi", u"Vendredi", u"Samedi", ] dot_chart.show_legend = False dates = date_to_chart(profile.get_posts()) for i in range(0, 24): dot_chart.add(str(i) + " h", dates[(i + 1) % 24]) img_path = os.path.join(settings.MEDIA_ROOT, "pygal") if not os.path.isdir(img_path): os.makedirs(img_path, mode=0o777) fchart = os.path.join(img_path, "mod-{}.svg".format(str(usr.pk))) dot_chart.render_to_file(fchart) my_articles = Article.objects.filter( sha_public__isnull=False).order_by("-pubdate").filter( authors__in=[usr]).all()[:5] my_tutorials = \ Tutorial.objects.filter(sha_public__isnull=False) \ .filter(authors__in=[usr]) \ .order_by("-pubdate" ).all()[:5] my_tuto_versions = [] for my_tutorial in my_tutorials: mandata = my_tutorial.load_json_for_public() my_tutorial.load_dic(mandata) my_tuto_versions.append(mandata) my_article_versions = [] for my_article in my_articles: article_version = my_article.load_json_for_public() my_article.load_dic(article_version) my_article_versions.append(article_version) my_topics = \ Topic.objects\ .filter(author=usr)\ .exclude(Q(forum__group__isnull=False) & ~Q(forum__group__in=request.user.groups.all()))\ .prefetch_related("author")\ .order_by("-pubdate").all()[:5] form = OldTutoForm(profile) oldtutos = [] if profile.sdz_tutorial: olds = profile.sdz_tutorial.strip().split(":") else: olds = [] for old in olds: oldtutos.append(get_info_old_tuto(old)) return render_template( "member/profile.html", { "usr": usr, "profile": profile, "bans": bans, "articles": my_article_versions, "tutorials": my_tuto_versions, "topics": my_topics, "form": form, "old_tutos": oldtutos, })
def index(): # This would be dynamically retrieved first_name = 'Brendan' last_name = 'Sherman' full_name = first_name + ' ' + last_name customer = customer_from_name(full_name) loan_total = 0 bill_total = 0 withdrawal_total = 0 transfer_list = [] deposit_list = [] # Insert Error Handling Here # Get customer information global customer_id customer_id = customer['_id'] address = customer['address'] address1 = address['street_number'] + ' ' + address['street_name'] address2 = address['city'] + ', ' + address['state'] + ' ' + address['zip'] # Get accounts accounts = retrieve_accounts(customer_id) # Get pending transfers pending_transfers = [] for account in accounts: transfers = retrieve_transfers(account['_id'], 'payer') for transfer in transfers: pending_transfers.append(transfer) transfers = retrieve_transfers(account['_id'], 'payee') for transfer in transfers: transfer_list.append(transfer['amount']) num_pending = len(pending_transfers) # Get bills bills = get_bills_from_customer(customer_id) for bill in bills: bill_total+=bill['payment_amount'] # Get Loans all_loans = [] for account in accounts: loans = get_loans_from_account(account['_id']) for loan in loans: all_loans.append(loan) loan_total+=loan['amount'] # Get Withdrawals all_withdrawals = [] for account in accounts: withdrawals = get_withdrawals_from_account(account['_id']) for withdrawal in withdrawals: all_withdrawals.append(withdrawal) withdrawal_total+=withdrawal['amount'] # Get Deposits for account in accounts: deposits = get_deposits_from_account(account['_id']) for deposit in deposits: deposit_list.append(deposit['amount']) # Create account pie chart pie_chart = pygal.Pie(legend_font_size=54, title_font_size=72, style=LightGreenStyle, disable_xml_declaration=True) pie_chart.title = 'Account Balances' for account in accounts: pie_chart.add(account['nickname'], account['balance']) # Create spending bar graph bar_graph = pygal.HorizontalBar(legend_font_size=54, title_font_size=72, style=LightGreenStyle, disable_xml_declaration=True) bar_graph.title = 'Money to be Used for Services' bar_graph.add('Loans', loan_total) bar_graph.add('Bills', bill_total) bar_graph.add('Withdrawals', withdrawal_total) # Create revenue dot plot dot_plot = pygal.Dot(x_label_rotation=30, legend_font_size=54, title_font_size=72, style=LightGreenStyle, disable_xml_declaration=True) dot_plot.title = 'Revenue' dot_plot.add('deposits', deposit_list) dot_plot.add('transfers', transfer_list) return render_template('index.html', customer_id=customer_id, name=full_name, address1=address1, address2=address2, accounts = accounts, pending_transfers=transfers, num_pending=num_pending, bills=bills, pie_chart=pie_chart, all_withdrawals=all_withdrawals, bar_graph=bar_graph, dot_plot=dot_plot)
def year_compare_punchcard(): chart = pygal.Dot(style=Style) chart.x_labels = DAY_LABELS for year, datum in _year_compare_data(): chart.add(year, datum) return chart.render(is_unicode=True)
def charts(): """ Recipe ingredients statistics by cuisine """ dot_chart = pygal.Dot(x_label_rotation=30, print_values=False, show_legend=False, style=pygal.style.styles['default']( value_font_size=30, title_font_size=30, legend_font_size=30, dots_size=3000, background='transparent', tooltip_font_size=30, label_font_size=22)) dot_chart.title = 'Recipe Ingredients Statistics by Cuisine' dot_chart.y_title = 'Recipes by cuisine' dot_chart.x_labels = [ 'milk', 'egg', 'sugar', 'flour', 'salt', 'water', 'garlic', 'vanilla', 'butter' ] dot_chart.y_labels = [ 'French - 4', 'Mexican - 2', 'Greek - 2', 'English - 2', 'Asian - 4', 'Indian - 3', 'Irish - 2', 'Italian - 5' ] dot_chart.add('French', French_val) dot_chart.add('Mexican', Mexican_val) dot_chart.add('Greek', Greek_val) dot_chart.add('English', English_val) dot_chart.add('Asian', Asian_val) dot_chart.add('Indian', Indian_val) dot_chart.add('Irish', Irish_val) dot_chart.add('Italian', Italian_val) dot_chart = dot_chart.render_data_uri() """ Recipe allergens statistics (in %) """ solid_gauge_chart = pygal.SolidGauge(inner_radius=0.70, style=pygal.style.styles['default']( value_font_size=25, title_font_size=30, legend_font_size=30, background='transparent', tooltip_font_size=30)) solid_gauge_chart.title = 'Recipe Allergens Statistics (in %)' percent_formatter = lambda x: '{:.10g}%'.format(x) solid_gauge_chart.value_formatter = percent_formatter solid_gauge_chart.add('Egg', [{'value': 37.5, 'max_value': 100}]) solid_gauge_chart.add('Milk', [{'value': 8.33, 'max_value': 100}]) solid_gauge_chart.add('Nuts', [{'value': 4.16, 'max_value': 100}]) solid_gauge_chart.add('Garlic', [{'value': 41.66, 'max_value': 100}]) solid_gauge_chart.add('No allergens', [{'value': 25, 'max_value': 100}]) solid_gauge_chart = solid_gauge_chart.render_data_uri() """ Average calories by cuisine """ gauge_chart = pygal.Gauge(human_readable=True, style=pygal.style.styles['default']( value_font_size=30, title_font_size=30, legend_font_size=30, background='transparent', tooltip_font_size=30, label_font_size=25)) gauge_chart.title = 'Average calories by cuisine' gauge_chart.range = [0, 1000] gauge_chart.add('French', 393.5) gauge_chart.add('Mexican', 296) gauge_chart.add('Greek', 599) gauge_chart.add('English', 476) gauge_chart.add('Asian', 292) gauge_chart.add('Indian', 204.66) gauge_chart.add('Irish', 413.5) gauge_chart.add('All', 344.91) gauge_chart = gauge_chart.render_data_uri() return render_template('statistics.html', dot_chart=dot_chart, solid_gauge_chart=solid_gauge_chart, gauge_chart=gauge_chart)
def generate_report_header(journal_paths: List[str], export_format: str = "markdown") -> str: header_template = get_report_template(None, "header.md") header_info = {} header_info["title"] = "Chaos Engineering Report" header_info["today"] = datetime.now().strftime("%d %B %Y") header_info["export_format"] = export_format tags = [] contribution_labels = [] contributions_by_experiment = [] contributions_by_tag = [] experiment_titles = [] for journal_path in journal_paths: with io.open(journal_path) as fp: journal = json.load(fp) experiment = journal.get("experiment") experiment_tags = experiment.get("tags", []) tags.extend(experiment_tags) contribs = experiment.get("contributions") title = experiment["title"] experiment_titles.append(title) if not contribs: continue for contrib in contribs: contribution_labels.append(contrib) level = contribs[contrib] contributions_by_experiment.append((title, level, contrib)) for tag in experiment_tags: contributions_by_tag.append((tag, level, contrib)) number_of_contributions = len(set(contribution_labels)) header_info["contributions"] = number_of_contributions > 0 header_info["num_experiments"] = len(experiment_titles) header_info["tags"] = tags = set(tags) if number_of_contributions: unique_contributions = sorted(set(contribution_labels)) header_info["num_distinct_contributions"] = number_of_contributions ####################################################################### # Distribution chart ####################################################################### dist_chart = pygal.Bar(print_values=True, print_values_position='top', show_legend=False, show_y_labels=False, legend_at_bottom=True) dist_chart.title = 'Organization Contributions Distribution' dist_chart.x_labels = unique_contributions dist_chart.add("", [ contribution_labels.count(contrib) for contrib in unique_contributions ]) if export_format in ["html", "html5"]: header_info["contribution_distribution"] = dist_chart.render( disable_xml_declaration=True) else: header_info["contribution_distribution"] = b64encode( cairosvg.svg2png(bytestring=dist_chart.render(), dpi=72)).decode("utf-8") contribution_labels = list(unique_contributions) ####################################################################### # Dot chart per experiment ####################################################################### contributions = {} for title in experiment_titles: contributions[title] = [None] * number_of_contributions for (title, level, contrib) in contributions_by_experiment: idx = contribution_labels.index(contrib) amount = 0 if level == "high": amount = 0.75 elif level == "medium": amount = 0.50 elif level == "low": amount = 0.25 elif level == "none": amount = -0.1 else: continue contributions[title][idx] = amount chart = pygal.Dot(legend_at_bottom_columns=1, show_y_labels=False, legend_at_bottom=True, show_legend=True, x_label_rotation=30, style=LightColorizedStyle, interpolate='hermite') chart.title = 'Experiment Contributions to Organization Properties' chart.x_labels = contribution_labels for title in contributions: chart.add(title, contributions[title], fill=False, allow_interruptions=True) if export_format in ["html", "html5"]: header_info["contributions_per_exp"] = chart.render( disable_xml_declaration=True) else: header_info["contributions_per_exp"] = b64encode( cairosvg.svg2png(bytestring=chart.render(), dpi=72)).decode("utf-8") chart = pygal.Radar(legend_at_bottom_columns=1, show_y_labels=False, legend_at_bottom=True, show_legend=True, x_label_rotation=30, style=LightColorizedStyle, interpolate='hermite') chart.title = 'Experiment Contributions to Organization Properties' chart.x_labels = contribution_labels for title in contributions: chart.add(title, contributions[title], fill=False, allow_interruptions=True) if export_format in ["html", "html5"]: header_info["contributions_per_exp_radar"] = chart.render( disable_xml_declaration=True) else: header_info["contributions_per_exp_radar"] = b64encode( cairosvg.svg2png(bytestring=chart.render(), dpi=72)).decode("utf-8") ####################################################################### # Dot chart per tag ####################################################################### contributions = {} for tag in tags: contributions[tag] = [None] * number_of_contributions for (tag, level, contrib) in contributions_by_tag: idx = contribution_labels.index(contrib) amount = 0 if level == "high": amount = 0.75 elif level == "medium": amount = 0.50 elif level == "low": amount = 0.25 elif level == "none": amount = -0.1 else: continue contributions[tag][idx] = amount chart = pygal.Dot(show_legend=False, x_label_rotation=30, style=LightColorizedStyle, interpolate='hermite') chart.title = 'Organization Properties Coverage by Area' chart.x_labels = contribution_labels for tag in contributions: chart.add(tag, contributions[tag], fill=False, allow_interruptions=True) if export_format in ["html", "html5"]: header_info["contributions_per_tag"] = chart.render( disable_xml_declaration=True) else: header_info["contributions_per_tag"] = b64encode( cairosvg.svg2png(bytestring=chart.render(), dpi=72)).decode("utf-8") header = header_template.render(header_info) return header
eduvalue3 = 4 expvalue1 = 2 expvalue2 = 4 expvalue3 = 1 radar_chart = pygal.Radar() radar_chart.title = 'Personal Advanced Analytic' radar_chart.x_labels = [edu1,edu2,'Between Education Domain',exp1,exp2,'Between Experience Domain'] radar_chart.add('Candidate', [eduvalue1, eduvalue2, eduvalue3,expvalue1,expvalue2,expvalue3]) radar_chart.render_to_file('1.svg') #dot - Education edutop = [] dot_chart = pygal.Dot(x_label_rotation=30) dot_chart.title = 'Education Categorical' dot_chart.x_labels = [edutop] dot_chart.add('Candidate', [6395, 8212, 7520, 7218, 12464, 1660, 2123, 8607]) dot_chart.render_to_file('Edu.svg') #dot - Experience exptop = [] dot_chart = pygal.Dot(x_label_rotation=30) dot_chart.title = 'Experience Categorical' dot_chart.x_labels = [exptop] dot_chart.add('Candidate', [6395, 8212, 7520, 7218, 12464, 1660, 2123, 8607]) dot_chart.render_to_file('Edu.svg')
# -*- coding: utf-8 -*- import pygal dot_chart = pygal.Dot() dot_chart.title = 'Cost of Whole Milk in early 2014' dot_chart.add('US Dollars', [2.08, 3.14, 3.89, 3.91, 3.94, 3.98]) dot_chart.render_to_file('dot_chart.svg')
def get_photo_html(request): global b64, custom_style, other if request.method == 'GET': return render(request, "index.html") tp = request.POST.get("t") settings = json.loads(request.POST.get("settings")) data = json.loads(request.POST.get("data")) if tp not in DEFAULT_TYPE: return render(request, "index.html") if 'style' in settings.keys(): custom_style = Style(**settings['style']) else: custom_style = Style(font_family='Microsoft YaHei', label_font_size=20, major_label_font_size=20, value_font_size=26, value_label_font_size=20, tooltip_font_size=20, title_font_size=30, legend_font_size=20) default_other = {'fill': True, 'legend_at_bottom': True, 'print_values': True, 'show_legend': True} if 'others' in settings.keys(): other = {**default_other, **settings['others']} else: other = default_other try: if tp == 'bar': bar_chart = pygal.Bar(title=settings['title'], width=settings['width'], height=settings['height'], **other, style=custom_style) bar_chart.title = settings['title'] bar_chart.x_labels = data['labels'] for k, v in data['data'].items(): bar_chart.add(k, v) bar_chart.render_to_png("png/bar.png") b64 = get_base64("png/bar.png") elif tp == 'line': line_chart = pygal.Line(title=settings['title'], width=settings['width'], height=settings['height'] , **other, style=custom_style) line_chart.title = settings['title'] line_chart.x_labels = data['labels'] for k, v in data['data'].items(): line_chart.add(k, v) line_chart.render_to_png("png/line.png") b64 = get_base64("png/line.png") elif tp == 'pie': pie_chart = pygal.Pie(title=settings['title'], width=settings['width'], height=settings['height'] , **other, style=custom_style) pie_chart.title = settings['title'] for k, v in data['data'].items(): pie_chart.add(k, v) pie_chart.render_to_png("png/pie.png") b64 = get_base64("png/pie.png") elif tp == 'radar': show_legend = False if len(data["data"].items()) > 1: show_legend = True radar_chart = pygal.Radar(title=settings['title'], width=settings['width'], height=settings['height'], **other, style=custom_style) radar_chart.title = settings['title'] radar_chart.x_labels = data['labels'] for k, v in data['data'].items(): radar_chart.add(k, v) radar_chart.render_to_png("png/radar.png") b64 = get_base64("png/radar.png") elif tp == 'HBar': h_bar_chart = pygal.HorizontalBar(title=settings['title'], width=settings['width'], height=settings['height'], **other, style=custom_style) h_bar_chart.title = settings['title'] # h_bar_chart.x_labels = data['data'].keys() for k, v in data['data'].items(): h_bar_chart.add(k, v) h_bar_chart.render_to_png("png/h_bar.png") b64 = get_base64("png/h_bar.png") elif tp == 'dot': dot_chart = pygal.Dot(title=settings['title'], width=settings['width'], height=settings['height'] , **other, style=custom_style) dot_chart.title = settings['title'] dot_chart.x_labels = data['labels'] for k, v in data['data'].items(): dot_chart.add(k, v) dot_chart.render_to_png("png/dot.png") b64 = get_base64("png/dot.png") elif tp == 'WordCloud': style = settings["style"] wc = WordCloud( font_path='/Users/donggua/Library/Fonts/msyh.ttf', **style ) a = {} for word in data['data']: name = word["name"] a[name] = word["value"] wc.generate_from_frequencies(a) wc.to_file(r"png/WordCloud.png") b64 = get_base64("png/WordCloud.png") elif tp == 'graph': datas = data["data"] data = datas["ControllerData"]["Paths"] CompanyName = datas["CompanyName"] # print(name1) KeyN = datas["KeyNo"] dot = gz.Digraph(format="png") node = settings.get("node", {}) node["fontname"] = "Microsoft YaHei" edge = settings.get("edge", {}) graph = settings.get("graph", {}) dot.attr('node', **node) dot.attr('edge', **edge) dot.attr('graph', **graph) graph_data = set() for f in data: reverse_data = list(reversed(f)) for i, re in enumerate(reverse_data): name = re["Name"] Percent = re["Percent"] KeyNo = re["KeyNo"] try: name1 = reverse_data[i + 1]["Name"] KeyNo1 = reverse_data[i + 1]["KeyNo"] except Exception: name1 = CompanyName KeyNo1 = KeyN dot.node(KeyNo, name) dot.node(KeyNo1, name1) graph_data.add(KeyNo + '|' + KeyNo1 + '|' + Percent) for i in graph_data: data = i.split('|') dot.edge(data[0], data[1], data[2]) dot.render("png/relation") b64 = get_base64("png/relation.png") except Exception as e: logging.error(e) return HttpResponse(json.dumps(b64), content_type='application/json')