def characters(xmlplay): ''' Loads a Shakespeare xml file (Bosak) and makes calculations on the characters Creates a small index.html file with a google chart ''' book = smallcharacteranalysis(xmlplay) from graphy.backends import google_chart_api from graphy import line_chart #pass # Lexical diversity BarChart chart = google_chart_api.BarChart() chart.AddBars(book['hapaxes'], color='a06F00',label='words said just once') chart.AddBars(book['vocab'], color='506F00',label='repeated words') chart.AddBars(book['length_list'], color='006F00',label='repetitions of the repeated words') chart.vertical = False chart.stacked = True #chart.auto_legend() chart.bottom.min = 0 chart.left.labels = book['charlist'] chart.left.max = len(book['charlist'])+1 chart.left.min = 0 chart.left.label_positions = [range(len(book['charlist']))] #chart.bottom.labels = char_list #Pie Chart total words pie = google_chart_api.PieChart(book['length_list'],book['charlist']) #line chart ? and ! exxageration = google_chart_api.BarChart() exxageration.AddBars(book['exclammarks'], color='a06F00',label='Exclamation Marks('!')') exxageration.AddBars(book['questionmarks'], color='506F00',label='Question Marks ('?')') exxageration.vertical = False exxageration.left.labels = book['charlist'] exxageration.bottom.min = 0 exxageration.left.labels = book['charlist'] exxageration.left.max = len(book['charlist'])+1 exxageration.left.min = 0 exxageration.left.label_positions = [range(len(book['charlist']))] import os.path file = 'index.html' infile = open(file,'w') infile.write('<h2>Lexical Variety</h2>') infile.write(chart.display.Img(600, 400)) infile.write('<h2>All words spoken, totals per character</h2>') infile.write(pie.display.Img(600, 300)) infile.write('<h2>Exageration and questioning</h2>') infile.write(exxageration.display.Img(600, 300))
def set_processed_counts(self, shards_processed): """Updates a chart url to display processed count for each shard. Args: shards_processed: list of integers with number of processed entities in each shard """ chart = google_chart_api.BarChart(shards_processed) shard_count = len(shards_processed) if shards_processed: # Only 16 labels on the whole chart. stride_length = max(1, shard_count / 16) chart.bottom.labels = [] for x in xrange(shard_count): if (x % stride_length == 0 or x == shard_count - 1): chart.bottom.labels.append(x) else: chart.bottom.labels.append("") chart.left.labels = ["0", str(max(shards_processed))] chart.left.min = 0 self.chart_width = min(700, max(300, shard_count * 20)) self.chart_url = chart.display.Url(self.chart_width, 200)
def set_processed_counts(self, shards_processed, shards_status): """Updates a chart url to display processed count for each shard. Args: shards_processed: list of integers with number of processed entities in each shard """ chart = google_chart_api.BarChart() def filter_status(status_to_filter): return [ count if status == status_to_filter else 0 for count, status in zip(shards_processed, shards_status) ] if shards_status: # Each index will have only one non-zero count, so stack them to color- # code the bars by status # These status values are computed in _update_state_from_shard_states, # in mapreduce/handlers.py. chart.stacked = True chart.AddBars(filter_status("unknown"), color="404040") chart.AddBars(filter_status("success"), color="00ac42") chart.AddBars(filter_status("running"), color="3636a9") chart.AddBars(filter_status("aborted"), color="e29e24") chart.AddBars(filter_status("failed"), color="f6350f") else: chart.AddBars(shards_processed) shard_count = len(shards_processed) if shard_count > 95: # Auto-spacing does not work for large numbers of shards. pixels_per_shard = 700.0 / shard_count bar_thickness = int(pixels_per_shard * .9) chart.style = bar_chart.BarChartStyle( bar_thickness=bar_thickness, bar_gap=0.1, use_fractional_gap_spacing=True) if shards_processed and shard_count <= 95: # Adding labels puts us in danger of exceeding the URL length, only # do it when we have a small amount of data to plot. # Only 16 labels on the whole chart. stride_length = max(1, shard_count / 16) chart.bottom.labels = [] for x in xrange(shard_count): if (x % stride_length == 0 or x == shard_count - 1): chart.bottom.labels.append(x) else: chart.bottom.labels.append("") chart.left.labels = ["0", str(max(shards_processed))] chart.left.min = 0 self.chart_width = min(700, max(300, shard_count * 20)) self.chart_url = chart.display.Url(self.chart_width, 200)
def makechart(mag): chart = google_chart_api.BarChart(mag) chart.left.min = 0 chart.left.max = ceil(max(mag)) chart.display.style.bar_thickness = 10 chart.display.style = bar_chart.BarStyle() chart.display.style.grou_gap = 10 chart.bottom.min = 0 chart.bottom.max = len(mag) chart.bottom.labels = [z for z in range(len(mag))] chart.top.labels = mag
def set_processed_counts(self, shards_processed): """Updates a chart url to display processed count for each shard. Args: shards_processed: list of integers with number of processed entities in each shard """ chart = google_chart_api.BarChart(shards_processed) if self.mapreduce_spec and shards_processed: chart.bottom.labels = [ str(x) for x in xrange(self.mapreduce_spec.mapper.shard_count)] chart.left.labels = ['0', str(max(shards_processed))] chart.left.min = 0 self.chart_url = chart.display.Url(300, 200)
def PerRunDurationBarGraph(run_data, scale=None): """Output a Google Chart API URL showing per-run durations.""" chart = google_chart_api.BarChart() chart.vertical = False chart.bottom.label_gridlines = True chart.bottom.label_positions = chart.bottom.labels max_run_avg = -1 runs = {} for (ns, run_averages) in run_data: chart.left.labels.append(ns) for run_num, run_avg in enumerate(run_averages): if run_num not in runs: runs[run_num] = [] runs[run_num].append(run_avg) if run_avg > max_run_avg: max_run_avg = run_avg if max_run_avg < 0: print "No decent data to graph: %s" % run_data return None if not scale: scale = int(math.ceil(max_run_avg / 5) * 5) if len(runs) == 1: bar_count = len(runs[0]) chart.AddBars(runs[0]) else: bar_count = 0 for run_num in sorted(runs): bar_count += len(runs[run_num]) chart.AddBars(runs[run_num], label='Run %s' % (run_num + 1), color=DarkenHexColorCode('4684ee', run_num * 3)) tick = _GoodTicks(scale, num_ticks=15.0) labels = range(0, scale, tick) + [scale] chart.bottom.min = 0 chart.display.enhanced_encoding = True bottom_axis = chart.AddAxis('x', common.Axis()) bottom_axis.labels = ['Duration in ms.'] bottom_axis.label_positions = [int((max_run_avg / 2.0) * .9)] chart.bottom.labels = labels chart.bottom.max = labels[-1] return chart.display.Url(CHART_WIDTH, _BarGraphHeight(bar_count))
def MinimumDurationBarGraph(fastest_data, scale=None): """Output a Google Chart API URL showing minimum-run durations.""" chart = google_chart_api.BarChart() chart.vertical = False chart.bottom.label_gridlines = True chart.bottom.label_positions = chart.bottom.labels chart.AddBars([x[1] for x in fastest_data]) chart.left.labels = [x[0].name for x in fastest_data] slowest_time = fastest_data[-1][1] if not scale: scale = int(math.ceil(slowest_time / 5) * 5) tick = _GoodTicks(scale, num_ticks=15.0) labels = range(0, scale, tick) + [scale] chart.bottom.min = 0 chart.bottom.max = scale chart.display.enhanced_encoding = True bottom_axis = chart.AddAxis('x', common.Axis()) bottom_axis.labels = ['Duration in ms.'] bottom_axis.label_positions = [int((scale / 2.0) * .9)] chart.bottom.labels = labels return chart.display.Url(CHART_WIDTH, _BarGraphHeight(len(chart.left.labels)))
def GetChart(self, *args, **kwargs): return google_chart_api.BarChart(*args, **kwargs)
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from graphy.backends import google_chart_api from graphy import bar_chart left_channel = [] right_channel = [] for i in xrange(0, 360, 3): left_channel.append(100.0 * math.sin(math.radians(i))) right_channel.append(100.0 * math.sin(math.radians(i + 30))) chart = google_chart_api.BarChart() chart.AddBars(left_channel, color='0000ff') chart.AddBars(right_channel, color='ff8040') chart.display.enhanced_encoding = True print '<html><head><title>Audio Signal</title></head><body>' print '<h1>Separate</h1>' chart.stacked = False chart.style = bar_chart.BarChartStyle(None, 0, 1) print chart.display.Img(640, 120) print '<h1>Joined</h1>' chart.stacked = True chart.style = bar_chart.BarChartStyle(None, 1) print chart.display.Img(640, 120)
def MakePageOne(tags_dict, pr_data, sr_data): tags_dict["TITLE_SOUNDLEVEL"] = _("Sound level") tags_dict["TITLE_PONCTUAL_RECEIVER"] = _("Punctual receivers") tags_dict["TITLE_SURFACE_RECEIVER"] = _("Surface receivers") tags_dict["TITLE_ACOUSTIC_PARAMETERS"] = _("Acoustic parameters") tags_dict["TITLE_REVERBERATION_TIME"] = _("Reverberation time") ############################################################## #Mise en page des niveaux sonores ## # Récepteurs ponctuels rplbl_lst = [] spl_byfreq = [] spl_html_array = u"" if len(pr_data) != 0: freq_lst = [ col[0] for col in pr_data[pr_data.keys()[0]]["sound_level"][1:] ] spl_byfreq = [[] for i in range(len(freq_lst))] for ponctualreceiver_name, rp_data in SortedDictByKeys(pr_data): rplbl_lst.append(ponctualreceiver_name) for idfreq, value in enumerate( [line[-1] for line in rp_data["sound_level"][1:]]): spl_byfreq[idfreq].append(value) spl_html_array += "<tr><th>%s</th>" % (_("SPL")) for rplbl in rplbl_lst: spl_html_array += "<th>%s</th>" % rplbl spl_html_array += "</tr>\n" for freqlbl, prs_spl in zip(freq_lst, spl_byfreq): newhtmlline = "<th>%s</th>\n" % (freqlbl) for rp_spl_val in prs_spl: newhtmlline += "<td>%.2f</td>" % (rp_spl_val) spl_html_array += "<tr class=\"even\">" + newhtmlline + "</tr>" tags_dict["ARRAY_PR_SOUNDLEVEL"] = spl_html_array #### #Création du graphique if len(spl_byfreq) > 0: spl_chart = google_chart_api.BarChart() spl_ticksBuilder = besttick.AxesLabelsCreator() spl_chart.AddBars(spl_byfreq[-1]) spl_ticksBuilder.feed(spl_byfreq[-1]) spl_chart.bottom.labels = map(GoogleEncode, rplbl_lst) spl_ticksBuilder.setmargin() spl_chart.left.min = spl_ticksBuilder.min spl_chart.left.max = spl_ticksBuilder.max spl_chart.left.labels = spl_ticksBuilder.GetTicksLabels("%.2f dB") spl_chart.left.label_positions = spl_ticksBuilder.GetTicksPosition() spl_chart.left.label_gridlines = True spl_chart.display.extra_params['chf'] = "bg,s,65432100" tags_dict["CHART_SPL"] = spl_chart.display.Img(settings.width, settings.height) ## # Récepteurs surfacique #Création du graphique tags_dict["CHART_SR"] = "" for rs_name, rs_tuple in SortedDictByKeys(sr_data): sr_chart = google_chart_api.BarChart() sr_ticksBuilder = besttick.AxesLabelsCreator() sr_chart.AddBars(rs_tuple[1]) sr_ticksBuilder.feed(rs_tuple[1]) sr_chart.bottom.labels = rs_tuple[0] sr_ticksBuilder.setmargin() sr_chart.left.min = sr_ticksBuilder.min sr_chart.left.max = sr_ticksBuilder.max area_ticks = sr_ticksBuilder.GetTicksPosition() sumArea = float(sum(rs_tuple[1])) percentage_ticks = [area / sumArea * 100. for area in area_ticks] left_labels = [ "%g m2 (%.f %%)" % (area, percentage) for area, percentage in zip(area_ticks, percentage_ticks) ] sr_chart.left.labels = left_labels sr_chart.left.label_positions = area_ticks sr_chart.left.label_gridlines = True sr_chart.display.extra_params['chf'] = "bg,s,65432100" sr_chart.display.extra_params['chtt'] = GoogleEncode(rs_name) tags_dict["CHART_SR"] += "<br />" + sr_chart.display.Img( settings.width, settings.height) ############################################################## #Mise en page des paramètres acoustiques rt_html_array = u"" if len(pr_data) != 0: freq_lst = [ col[0] for col in pr_data[pr_data.keys()[0]]["sound_level"][1:] ] rplbl_lst = [] tr_byfreq = [[] for i in range(len(freq_lst))] for ponctualreceiver_name, rp_data in SortedDictByKeys(pr_data): rplbl_lst.append(ponctualreceiver_name) for idfreq, value in enumerate(rp_data["rt30"][1:-1]): tr_byfreq[idfreq].append(value) #print "name: %s idfreq:%i value:%f" % (ponctualreceiver_name,idfreq,value) rt_html_array += "<tr><th>%s</th>" % (_("RT30")) for rplbl in rplbl_lst: rt_html_array += "<th>%s</th>" % (rplbl) rt_html_array += "</tr>\n" for freqlbl, prs_tr in zip(freq_lst, tr_byfreq): newhtmlline = "<th>%s</th>\n" % (freqlbl) for rp_tr_val in prs_tr: newhtmlline += "<td>%.2f</td>" % (rp_tr_val) rt_html_array += "<tr class=\"even\">" + newhtmlline + "</tr>" tags_dict["ARRAY_RT30"] = rt_html_array #### #Création du graphique chart = google_chart_api.BarChart() display_mode = "byfreq" if len( pr_data ) > 5: #si il y a plus de 5 récepteurs ponctuels on limite à la valeur globale display_mode = "global_only" ticksBuilder = besttick.AxesLabelsCreator() if display_mode == "byfreq": for ponctualreceiver_name, rp_data in SortedDictByKeys(pr_data): bar_data = rp_data["rt30"][1:] chart.AddBars( bar_data, label=GoogleEncode(ponctualreceiver_name)) #, color='ccccff' ticksBuilder.feed(bar_data) if len(pr_data) != 0: chart.bottom.labels = [ col[0] for col in pr_data[pr_data.keys()[0]]["sound_level"][1:] ] else: rplist = [] rplvllist = [] for ponctualreceiver_name, rp_data in SortedDictByKeys(pr_data): rplvllist.append(rp_data["rt30"][-1]) rplist.append(GoogleEncode(ponctualreceiver_name)) chart.AddBars(rplvllist) ticksBuilder.feed(rplvllist) chart.bottom.labels = rplist if ticksBuilder.min != None: ticksBuilder.setmargin() chart.left.min = ticksBuilder.min chart.left.max = ticksBuilder.max chart.left.labels = ticksBuilder.GetTicksLabels("%.2f s") chart.left.label_positions = ticksBuilder.GetTicksPosition() chart.left.label_gridlines = True chart.display.extra_params['chf'] = "bg,s,65432100" tags_dict["CHART_RT30"] = chart.display.Img(settings.width, settings.height) return tags_dict
'NY': 54475, 'CT': 5544, 'RI': 1545, 'NJ': 8722, 'PA': 46058 } northwest = ('WA', 'OR', 'ID', 'MT', 'WY') northeast = ('ME', 'VT', 'NH', 'MA', 'NY', 'CT', 'RI', 'NJ', 'PA') states = northwest + northeast areas = [area[s] for s in states] print '<html><body>' print '<h1>Areas of States in the Northwest and Northeast US</h1>' print '<h3>(in square miles)</h3>' chart = google_chart_api.BarChart(areas) chart.bottom.labels = states region_axis = common.Axis() region_axis.min = 0 region_axis.max = 100 region_axis.labels = ['Northwest', 'Northeast'] region_axis.label_positions = [20, 60] chart.AddAxis(common.AxisPosition.BOTTOM, region_axis) ylabels = range(0, 150001, 50000) chart.left.min = min(ylabels) chart.left.max = max(ylabels) chart.left.labels = ['%sK' % (x / 1000) for x in ylabels] chart.left.label_positions = ylabels print chart.display.Img(500, 220) print '</body></html>'
def setUp(self): self.chart = google_chart_api.BarChart()
# See the License for the specific language governing permissions and # limitations under the License. from graphy.backends import google_chart_api elevation = { 'Death Valley': -210, # Showing off negative barchart values! 'Mountain View': 32, 'Livermore': 400, 'Riverside': 819, 'Auburn': 1536, 'South Lake Tahoe': 6264, } cities = elevation.keys() elevations = [elevation[city] for city in cities] print '<html>' print '<h1>Elevation</h1>' chart = google_chart_api.BarChart(elevations) chart.left.labels = cities chart.vertical = False xlabels = range(-1000, 7001, 1000) chart.bottom.min = min(xlabels) chart.bottom.max = max(xlabels) chart.bottom.label_positions = xlabels chart.bottom.labels = ['%sK' % (x / 1000) for x in xlabels] chart.bottom.grid_spacing = 1000 print chart.display.Img(400, 220) print '</html>'