def test_64_colors(): n = 64 colors = [rotate('#ff0000', i * 360 / n) for i in range(n)] pie = Pie(style=Style(colors=colors)) for i in range(n): pie(1, title=str(i) if i % 5 == 1 else None) return pie.render_response()
def test_64_colors(): n = 64 colors = [rotate('#ff0000', i * 360 / n) for i in range(n)] pie = Pie(style=Style(colors=colors)) for i in range(n): pie.add(str(i), 1) return pie.render_response()
def test_pie_serie_radius(): pie = Pie() pie.js = ('http://a.zi:2343/2.0.x/pygal-tooltips.js', ) for i in range(10): pie.add(str(i), i, inner_radius=(10 - i) / 10) return pie.render_response()
def statistics(): """ Page display data visualization about statistics for the recipes """ # Count how many recipes have each meal time to send to the pie chart breakfast = mongo.db.recipes.find({'meal_time': 'breakfast'}).count() lunch = mongo.db.recipes.find({'meal_time': 'lunch'}).count() dinner = mongo.db.recipes.find({'meal_time': 'dinner'}).count() # Build pie chart pie_chart = Pie() pie_chart.title = 'Meal Times' pie_chart.add('Breakfast', breakfast) pie_chart.add('Lunch', lunch) pie_chart.add('Dinner', dinner) pie_chart = pie_chart.render_data_uri() # Count how many recipes have each training type to send to line chart endurance = mongo.db.recipes.find({'training_type': 'endurance'}).count() speed = mongo.db.recipes.find({'training_type': 'speed'}).count() strength = mongo.db.recipes.find({'training_type': 'strength'}).count() power = mongo.db.recipes.find({'training_type': 'power'}).count() # Build line chart line_chart = Bar() line_chart.title = 'Training Types' line_chart.add('Endurance', [{'value': endurance, 'label': 'Endurance'}]) line_chart.add('Strength', [{'value': strength, 'label': 'Strength'}]) line_chart.add('Power', [{'value': power, 'label': 'Power'}]) line_chart.add('Speed', [{'value': speed, 'label': 'Speed'}]) line_chart = line_chart.render_data_uri() return render_template('statists.html', title='Statistics', pie_chart=pie_chart, line_chart=line_chart)
def __init__(self): Pie.__init__(self, inner_radius=0.5, style=CUSTOM_STYLE, show_legend=False) self.title = "Distribution" for label in MoodItem.objects.order_by("order"): value = Mood.objects(user=current_user.id, mood=label).count() self.add(label.__str__(), [{"value": value, "color": label.color}]) print(Mood.objects(user=current_user.id, mood=label).to_json())
def create_pie_chart(self, data=None, span='all', no=None): """Creates a pie chart from the the data""" # Create the list of objects to be added to the chart chart_list = [] # If the span has been specified, then get the logs only for that time if not span == None and not span == 'all': # Iterate through the log data. for log in self.data: # Get and format the information we need from the log. activity = log[0] log_start = unformat_time(tuple_time(log[1])) log_end = unformat_time(tuple_time(log[2])) color = log[3] minimum = unformat_time(span[1]) maximum = unformat_time(span[2]) # Add the time and activity to the chart_list. log_time = time_in_span(log_start, log_end, minimum, maximum) # Check if the activity has already been added to chart_list. in_chart_list = False for entry in chart_list: # If the activity is in the chart_list, make a note and add. # its time to the existing list item. if entry[0] == activity: entry[1] += log_time in_chart_list = True # If the log is not in the chart_list and it is in the span, add # it to the chart_list. if not in_chart_list and log_time > 0: chart_list.append([activity, log_time, color]) else: # If span is not specified then the data are totals. # Set the chart_list equal to the total data. for total in data: chart_list.append((total[0], total[2], total[3])) # Add each entry is the chart_list to the chart self.sort(chart_list) # Data must be organized for day, month, etc. before using # If size has been specified if not self.size == (None, None): self.chart = Pie(style=self.style, print_values=False, fill=True, human_readable=True, include_x_axis=True, width=self.size[0], height=self.size[1]) # If size has not already been specified else: # Let the graph dynamically resize within webview self.chart = Pie(style=self.style, print_values=False, fill=True, human_readable=True, include_x_axis=True) if not chart_list == []: for entry in chart_list: self.chart.add(entry[0], entry[1])
def dashboard(): #Getting all projects projects = Project.select() #Creating a pie chart pie_chart = Pie() #adding title to pie chart pie_chart.title = 'Project Type' #instatiating two variables internal and external internal = 0 external = 0 for project in projects: if (project.type == 'Internal'): internal += 1 else: external += 1 pie_chart.add('Internal', internal) pie_chart.add('External', external) pie_chart.render() chart = pie_chart.render_data_uri() return render_template('index.html', projects_to_send=projects, chart=chart)
def create_bar_chart(self, data, span): """Creates a bar chart from the the data""" # Initialize the chart_list chart_list = [] for log in data: activity_time = 0 activity = log[0] log_start = unformat_time(tuple_time(log[1])) log_end = unformat_time(tuple_time(log[2])) color = log[3] minimum = span[1] maximum = span[2] minimum = unformat_time(minimum) maximum = unformat_time(maximum) activity_time += time_in_span(log_start, log_end, minimum, maximum) in_chart_list = False for entry in chart_list: if entry[0] == activity: entry[1] += activity_time in_chart_list = True if not in_chart_list and activity_time > 0: chart_list.append([activity, activity_time, color]) self.sort(chart_list) # Data must be organized for day, month, etc. before using # If size has been specified if not self.size == (None, None): self.chart = Bar(style=self.style, y_scale=60.0, print_values=False, include_x_axis=True, width=self.size[0], height=self.size[1]) # If size has not already been specified else: # Let the graph dynamically resize within webview self.chart = Bar(style=self.style, print_values=False, include_x_axis=True, y_scale=60.0) self.set_y_labels(chart_list) ## Add each entry is the chart_list to the chart if not chart_list == []: for entry in chart_list: time = str(timedelta(seconds=entry[1])) if time[1] == ':': time = '0' + time self.chart.add(entry[0], [{'value':entry[1], 'label':time}]) else: self.chart = Pie(style=self.style, width=self.size[0], height=self.size[1])
def test_half_pie(): pie = Pie(half_pie=True) for i in range(20): pie.add(str(i), i, inner_radius=.1) pie.legend_at_bottom = True pie.legend_at_bottom_columns = 4 return pie.render_response()
def _generate_pie_chart(self, datas): """ After generate the pie chart,save to file and return the chart path Keyword arguments: datas -- Dict object of parsed information for a pie chart """ if not datas: return "" pie_chart = Pie(fill=True, interpolate="cubic", style=LightStyle) for key, value in datas.items(): pie_chart.add(key, value) path = os.path.join(tempfile.gettempdir(), "pie{}.svg".format(str(int(time.time())))) pie_chart.render_to_file(path) logging.info("Pie chart was created successfully.") return path
def plot(): def _cmp(comp, node, field): comp.add(node.hostname, [d[-1] for d in node.data[field]]) return comp tree_clients, pie_clients = Treemap(), Pie() tree_traffic_rx, pie_traffic_rx = Treemap(), Pie() tree_traffic_tx, pie_traffic_tx = Treemap(), Pie() for node in _load(): save(node.name, node.clients(), 'clients') save(node.name, node.system(), 'system') save(node.name, node.traffic(), 'traffic') save(node.name, node.traffic_full(), 'traffic_full') save('_map', _cmp(tree_clients, node, 'clients_total'), 'clients') save('_pie', _cmp(pie_clients, node, 'clients_total'), 'clients') save('_map', _cmp(tree_traffic_rx, node, 'traffic_rx'), 'traffic_rx') save('_pie', _cmp(pie_traffic_rx, node, 'traffic_rx'), 'traffic_rx') save('_map', _cmp(tree_traffic_tx, node, 'traffic_tx'), 'traffic_tx') save('_pie', _cmp(pie_traffic_tx, node, 'traffic_tx'), 'traffic_tx')
def pie_route(): projects = Project.select() pie_chart = Pie() pie_chart.title = 'Browser usage in February 2012 (in %)' # instatiating two variables internal and external internal = 0 external = 0 for project in projects: if (project.type == 'internal'): internal += 1 else: external += 1 pie_chart.add('internal', internal) pie_chart.add('external', external) pie_chart.render() chart = pie_chart.render_data_uri() return render_template('index.html', projects_to_send=projects, chart=chart)
def lapspercar_svg(self, curr_url=None): if not config.config.HTTP_CONFIG.enable_svg_generation: return "" stats = self.lastStat pie_chart = Pie(pygalConfig) pie_chart.title = 'Car usage (% laps driven)' tl = stats['numLaps'] lapsPerTrack = sorted(stats['lapsPerCar'].items(), key=lambda x: x[1], reverse=True) valueToItem = {} for t, nl in lapsPerTrack: v = nl * 100 / tl while v in valueToItem: v -= 1e-9 valueToItem[v] = t pie_chart.add(t, v) pie_chart.value_formatter = lambda x, valueToItem=valueToItem: "%s: %.1f%%" % ( valueToItem.get(x, '?'), x) return pie_chart.render()
def lapspercombo_svg(self, curr_url=None): if not config.config.HTTP_CONFIG.enable_svg_generation: return "" stats = self.lastStat pie_chart = Pie(pygalConfig) pie_chart.title = 'Combo usage (% laps driven)' tl = stats['numLaps'] lapsPerCombo = sorted(stats['lapsPerCombo'].items(), key=lambda x: x[1]['lapCount'], reverse=True) valueToItem = {} for t, info in lapsPerCombo: nl = info['lapCount'] name = "+".join(info['cars']) + '@' + info['track'] v = nl * 100 / tl while v in valueToItem: v -= 1e-9 valueToItem[v] = name pie_chart.add(name, v) pie_chart.value_formatter = lambda x, valueToItem=valueToItem: "%s: %.1f%%" % ( valueToItem.get(x, '?'), x) return pie_chart.render()
def dashboard(): projects = Project.select() pie_chart = Pie() pie_chart.title = 'Project Type comparison' Internal = 0 External = 0 for project in projects: if (project.type == 'Internal'): Internal += 1 else: External += 1 pie_chart.add('External', External) pie_chart.add('Internal', Internal) # pie_chart.add('Chrome', 36.3) # pie_chart.add('Safari', 4.5) # pie_chart.add('Opera', 2.3) chart = pie_chart.render_data_uri() projects = Project.select() return render_template('index.html', projects_to_send=projects, chart=chart)
def test_multiseries_donut(): #this just demos that the multiseries pie does not respect the inner_radius file_name = '/tmp/test_graph-%s.svg' % uuid.uuid4() if os.path.exists(file_name): os.remove(file_name) chart = Pie(inner_radius=.3, pretty_print=True) chart.title = 'Browser usage by version in February 2012 (in %)' chart.add('IE', [5.7, 10.2, 2.6, 1]) chart.add('Firefox', [.6, 16.8, 7.4, 2.2, 1.2, 1, 1, 1.1, 4.3, 1]) chart.add('Chrome', [.3, .9, 17.1, 15.3, .6, .5, 1.6]) chart.add('Safari', [4.4, .1]) chart.add('Opera', [.1, 1.6, .1, .5]) chart.render_to_file(file_name) with open(file_name) as f: assert 'pygal' in f.read() os.remove(file_name)
def test_donut(): file_name = '/tmp/test_graph-%s.svg' % uuid.uuid4() if os.path.exists(file_name): os.remove(file_name) chart = Pie(inner_radius=.3, pretty_print=True) chart.title = 'Browser usage in February 2012 (in %)' chart.add('IE', 19.5) chart.add('Firefox', 36.6) chart.add('Chrome', 36.3) chart.add('Safari', 4.5) chart.add('Opera', 2.3) chart.render_to_file(file_name) with open(file_name) as f: assert 'pygal' in f.read() os.remove(file_name)
class Charter: def __init__(self, font, filepath, webview, webview_window, loading_spinner): self.font = font self.filepath = filepath self.webview = webview # Turn off the right click menu for the webview self.webview.props.settings.props.enable_default_context_menu = False self.webview_window = webview_window self.loading_spinner = loading_spinner self.loading_spinner.set_visible(False) self.data = [] self.type = None # Size is a tuple of (width, height) self.size = (450, 350) self.chart = None self.colorlist = ['#729fcf', '#ef2929', '#fce94f', '#8ae234', '#ad7fa8', '#fcaf3e', '#3465a4', '#cc0000', '#edd400', '#73d216', '#75507b', '#f57900', '#204a87', '#a40000', '#c4a000', '#4e9a06', '#5c3566', '#ce5c00', '#d3d7cf'] #self.sort_colorlist() # The custom pygal style used for the pie graph. self.style = Style(background='#F7F6F6', plot_background='#F7F6F6', foreground='#888a85', foreground_light='#888a85', foreground_dark='#555753', opacity='.6', opacity_hover='.9', transition='200ms ease-in', colors=(self.colorlist)) self.visible = True def add_entry(self, label, time, color): """Adds an entry to data and gives it a label, time, and color""" # If the color is not set if color == None: # Set the color to light grey color = len(self.colorlist)-1 # If color is specified else: # Make sure it is a valid color from the colorlist while color >= len(self.colorlist)-1: color -= len(self.colorlist)-1 # add the entry to the data self.data.append((label, time, color)) def compound_other_data(self, data): """Compounds smallest data entries into 'other' entry""" # This function is necessary to keep legend from growing larger than the # widget it is contained in. # Get the sum of all values (the [1] index in the entries) sum_of_values = 0 for entry in data: sum_of_values += entry[1] # Set the minimum amount to one percent of the total amount minimum_amount = 0.01 * sum_of_values # Create a list item 'other' and give it a value of 0 and the last color # in the CONST_COLOR_LIST. other = ['Other ', 0, len(CONST_COLOR_LIST)-1] entries_to_compound = [] entries_compunded = False for entry in data: if entry[1] <= minimum_amount: other[1] += entry[1] entries_to_compound.append(entry) entries_compunded = True # If there is more than one entry to compound into other if len(entries_to_compound) > 1: for entry in entries_to_compound: del data[data.index(entry)] # If the data still has too many entries, compound the smallest into the # 'Other' entry if len(data) > CONST_MAX_DATA_ENTRIES: self.sort_data_by_size(data) entries_to_compound = [] for entry in xrange((len(data) - CONST_MAX_DATA_ENTRIES)): other[1] += data[entry][1] entries_to_compound.append(data[entry]) entries_compunded = True for entry in entries_to_compound: del data[data.index(entry)] if entries_compunded: data.append(other) def create_chart(self, chart_type=None, span=None): """Creates a chart of the given type based the data""" if not chart_type == None: self.type = chart_type if self.type == 'pie': self.create_pie_chart(self.data, span) elif self.type == 'bar': self.create_bar_chart(self.data, span) def create_pie_chart(self, data=None, span='all', no=None): """Creates a pie chart from the the data""" # Create the list of objects to be added to the chart chart_list = [] # If the span has been specified, then get the logs only for that time if not span == None and not span == 'all': # Iterate through the log data. for log in self.data: # Get and format the information we need from the log. activity = log[0] log_start = unformat_time(tuple_time(log[1])) log_end = unformat_time(tuple_time(log[2])) color = log[3] minimum = unformat_time(span[1]) maximum = unformat_time(span[2]) # Add the time and activity to the chart_list. log_time = time_in_span(log_start, log_end, minimum, maximum) # Check if the activity has already been added to chart_list. in_chart_list = False for entry in chart_list: # If the activity is in the chart_list, make a note and add. # its time to the existing list item. if entry[0] == activity: entry[1] += log_time in_chart_list = True # If the log is not in the chart_list and it is in the span, add # it to the chart_list. if not in_chart_list and log_time > 0: chart_list.append([activity, log_time, color]) else: # If span is not specified then the data are totals. # Set the chart_list equal to the total data. for total in data: chart_list.append((total[0], total[2], total[3])) # Add each entry is the chart_list to the chart self.sort(chart_list) # Data must be organized for day, month, etc. before using # If size has been specified if not self.size == (None, None): self.chart = Pie(style=self.style, print_values=False, fill=True, human_readable=True, include_x_axis=True, width=self.size[0], height=self.size[1]) # If size has not already been specified else: # Let the graph dynamically resize within webview self.chart = Pie(style=self.style, print_values=False, fill=True, human_readable=True, include_x_axis=True) if not chart_list == []: for entry in chart_list: self.chart.add(entry[0], entry[1]) def create_bar_chart(self, data, span): """Creates a bar chart from the the data""" # Initialize the chart_list chart_list = [] for log in data: activity_time = 0 activity = log[0] log_start = unformat_time(tuple_time(log[1])) log_end = unformat_time(tuple_time(log[2])) color = log[3] minimum = span[1] maximum = span[2] minimum = unformat_time(minimum) maximum = unformat_time(maximum) activity_time += time_in_span(log_start, log_end, minimum, maximum) in_chart_list = False for entry in chart_list: if entry[0] == activity: entry[1] += activity_time in_chart_list = True if not in_chart_list and activity_time > 0: chart_list.append([activity, activity_time, color]) self.sort(chart_list) # Data must be organized for day, month, etc. before using # If size has been specified if not self.size == (None, None): self.chart = Bar(style=self.style, y_scale=60.0, print_values=False, include_x_axis=True, width=self.size[0], height=self.size[1]) # If size has not already been specified else: # Let the graph dynamically resize within webview self.chart = Bar(style=self.style, print_values=False, include_x_axis=True, y_scale=60.0) self.set_y_labels(chart_list) ## Add each entry is the chart_list to the chart if not chart_list == []: for entry in chart_list: time = str(timedelta(seconds=entry[1])) if time[1] == ':': time = '0' + time self.chart.add(entry[0], [{'value':entry[1], 'label':time}]) else: self.chart = Pie(style=self.style, width=self.size[0], height=self.size[1]) def set_y_labels(self, chart_list): """Sets the y labels on a bar chart""" # Set up the y axis maximum_time_in_seconds = 0 for entry in chart_list: if entry[1] > maximum_time_in_seconds: maximum_time_in_seconds = entry[1] max_number_of_minutes = int(ceil(maximum_time_in_seconds/60))+2 y_labels = [] if max_number_of_minutes > 2: if max_number_of_minutes < 30: for minute in xrange(max_number_of_minutes+1): y_labels.append(minute*60) elif max_number_of_minutes >= 30 and max_number_of_minutes < 60: for minute in xrange((max_number_of_minutes/5)+1): y_labels.append(minute*60*5) elif max_number_of_minutes >= 60 and max_number_of_minutes < 120: for minute in xrange((max_number_of_minutes/10)+2): y_labels.append(minute*60*10) elif max_number_of_minutes >= 120 and max_number_of_minutes < 240: for minute in xrange((max_number_of_minutes/15)+1): y_labels.append(minute*60*15) elif max_number_of_minutes >= 240 and max_number_of_minutes < 480: for minute in xrange((max_number_of_minutes/20)+1): y_labels.append(minute*60*20) elif max_number_of_minutes >= 480 and max_number_of_minutes < 960: for minute in xrange((max_number_of_minutes/30)+1): y_labels.append(minute*60*30) elif max_number_of_minutes >= 960: for minute in xrange((max_number_of_minutes/60)+1): y_labels.append(minute*3600) else: for second in xrange((maximum_time_in_seconds)+1): y_labels.append(second) self.chart.y_labels = y_labels def convert_y_axis_to_time(self, label): """Converts y axis labels from seconds to minutes""" y_value_in_time = '' y_value_in_time = str(timedelta(seconds=int(label))) if y_value_in_time[1] == ':': y_value_in_time = '0' + y_value_in_time if not self.filepath == None: convert_y_axis = ("sed -i 's/class=\\\"\\\">%s.0/class=\\\"\\\"" + ">%s/g' " + self.filepath) % (str(label), y_value_in_time) system(convert_y_axis) # Then convert the major y axises (The zeroeth and first amounts) to # a formatted time if the label is a major axis. convert_major_y_axis = ("sed -i 's/class=\\\"major\\\">%s.0/" + "class=\\\"major\\\">%s/g' " + self.filepath) % (str(label), y_value_in_time) system(convert_major_y_axis) def fix_tooltip(self): """Changes the SVG file's default mouseover tooltip to no longer contain value for time in seconds""" if not self.filepath == None: system(("sed -i 's/<desc class=\"value\">[0-9]*<\/desc>//g' " + self.filepath)) def clear(self): """Resets the data and chart""" self.data = [] self.chart = None def sort_data_by_size(self, data): """Used to sort the pie slices by time from largest to smallest.""" # Make a duplicate of the data so it does not get tampered with sorted_data = data # Sort from smallest to largest based on time. sorted_data.sort(key=itemgetter(1)) # Make sure that the Other entry is at the end of the list if it exists for entry in sorted_data: if entry[0] == 'Other ': sorted_data.insert(0,sorted_data.pop(sorted_data.index(entry))) # Then set data as the sorted data. data = sorted_data#[::-1] def sort_colorlist(self, data): """Used to make the order of the color_list match the order of the pie_list's activity colors""" # Create an empty list to put the sorted colors in sorted_colorlist = [] # Iterate through the chart data for entry in data: # Get the specified color from the chart data color = int(entry[2]) # Arrange the colorlist so that the given datum recieves that color if color < (len(CONST_COLOR_LIST)-1) or entry[0] == 'Other ': sorted_colorlist.append(CONST_COLOR_LIST[color]) else: sorted_colorlist.append(CONST_COLOR_LIST[(color-(len(CONST_COLOR_LIST)-1))]) # Set the colorlist to the sorted_colorlist self.colorlist = sorted_colorlist if not self.colorlist == []: self.style = Style(background='#F7F6F6', plot_background='#F7F6F6', foreground='#888a85', foreground_light='#888a85', foreground_dark='#555753', opacity='.6', opacity_hover='.9', transition='200ms ease-in', colors=(self.colorlist)) def sort(self, data): """Sort the data and colors""" if not data == []: self.compound_other_data(data) self.sort_data_by_size(data) self.sort_colorlist(data) def send_to_svg(self): """Send the prepared pie graph to an SVG file""" self.chart.render_to_file(self.filepath) # Set the font in the svg file to the font specified during __init__ self.fix_font() if hasattr(self.chart, 'y_labels'): self.fix_tooltip() for label in self.chart.y_labels: self.convert_y_axis_to_time(label) def fix_font(self): """Changes the SVG file's default font (monospace) to the font specified when the charter was initialized""" if not self.font == None: system(("sed -i 's/font-family:monospace/font-family:" + self.font + "/g' " + self.filepath)) def start_loading_animation(self): """Callback to start loading animation""" GLib.timeout_add(400, self.get_loading_animation) def get_loading_animation(self): """Checks to see wheteher or not we should continue loading animation""" if self.visible: chart_loading = not (str(self.webview.get_load_status()) == '<enum WEBKIT_LOAD_FAILED of type WebKitLoadStatus>' or str(self.webview.get_load_status()) == '<enum WEBKIT_LOAD_FINISHED of type WebKitLoadStatus>') if not chart_loading: self.loading_spinner.stop() self.loading_spinner.set_visible(False) self.webview_window.set_visible(True) return chart_loading else: return False def load_into_webview(self, initial=False): """Load the SVG file for the chart into the webview""" #self.sort() self.send_to_svg() if initial: self.webview.open(self.filepath) else: self.webview.reload() if self.visible: self.webview_window.set_visible(False) self.loading_spinner.set_visible(True) self.loading_spinner.start() self.start_loading_animation() def set_visible(self, visible=True): self.visible = visible self.webview_window.set_visible(visible) if not visible: self.loading_spinner.set_visible(False)
def test_half_pie(): """Test a half pie chart""" pie = Pie() pie.add('IE', 19.5) pie.add('Firefox', 36.6) pie.add('Chrome', 36.3) pie.add('Safari', 4.5) pie.add('Opera', 2.3) half = Pie(half_pie=True) half.add('IE', 19.5) half.add('Firefox', 36.6) half.add('Chrome', 36.3) half.add('Safari', 4.5) half.add('Opera', 2.3) assert pie.render() != half.render()
def test_half_pie(): pie = Pie(half_pie=True) for i in range(10): pie.add(str(i), i, inner_radius=.1) return pie.render_response()
def get_top_activity(target): if 'do' not in request.args.keys(): return render_template('top_activity.html') required_source = { 'start_date': request.args.get('start_date', '-1h'), 'end_date': request.args.get('end_date', '-0h') } required = {'start_date': 'datetime', 'end_date': 'datetime'} error, required_values = parse_parameters(required_source, required) if error: flash(f'Incorrect value: {error}') return render_template('top_activity.html') optional_source = { 'wait_class': request.args.get('wait_class', ''), 'event': request.args.get('event', ''), 'session_id': request.args.get('session_id', ''), 'user_name': request.args.get('user_name', ''), 'sql_id': request.args.get('sql_id', ''), 'object_name': request.args.get('object_name', '') } _optional = { 'wait_class': 'str', 'event': 'str', 'session_id': 'int', 'user_name': 'str', 'sql_id': 'str', 'object_name': 'str' } error, optional_values = parse_parameters(optional_source, _optional, True) if error: flash(f'Incorrect value: {error}') return render_template('top_activity.html') optional_values = {k: v for k, v in optional_values.items() if v} r = execute( target, "with h as (select sample_id, sample_time," " sql_id, o.object_name, event, event_id, user_id, session_id," " to_char(session_id) || ':' || to_char(session_serial#) sess" ", nvl(wait_class, 'CPU') wait_class" ", nvl(wait_class_id, -1) wait_class_id" ", wait_time, time_waited from v$active_session_history ash" " left join dba_objects o on o.object_id = ash.current_obj#" " where sample_time >= trunc(:start_date, 'mi') and sample_time < trunc(:end_date, 'mi')" " and sample_time > trunc(sysdate){}{}{}{}{}{})" " select 1 t, to_char(sample_time, 'hh24:mi') s, wait_class v1, wait_class_id v2, count(1) c" " from h group by to_char(sample_time, 'hh24:mi'), wait_class, wait_class_id union all" " select 2 t, sql_id s, wait_class v1, wait_class_id v2, count(1) c from h" " where sql_id is not null and sql_id in (select sql_id" " from (select sql_id, row_number() over (order by tc desc) rn" " from (select sql_id, count(1) tc from h" " where sql_id is not null group by sql_id)) where rn <= 10)" " group by sql_id, wait_class, wait_class_id union all" " select 6 t, to_char(h.session_id) || ':' || nvl(u.username, '') s," " wait_class v1, wait_class_id v2, count(1) c from h" " left join dba_users u on u.user_id = h.user_id" " where sess in (select sess" " from (select sess, row_number() over (order by tc desc) rn" " from (select sess, count(1) tc from h" " group by sess)) where rn <= 10)" " group by to_char(h.session_id) || ':' || nvl(u.username, ''), wait_class, wait_class_id union all" " select 3 t, object_name s, wait_class v1, wait_class_id v2, count(1) c from h" " where object_name is not null and object_name in (select object_name" " from (select object_name, row_number() over (order by tc desc) rn" " from (select object_name, count(1) tc from h" " where object_name is not null group by object_name))" " where rn <= 10) group by object_name, wait_class, wait_class_id union all" " select 4 t, null s, wait_class v1, wait_class_id v2, count(1) c" " from h group by wait_class, wait_class_id union all" " select 5 t, null s, event v1, event_id v2, count(1) c" " from h group by event, event_id union all" " select 7 t, to_char(sample_time, 'hh24:mi:ss') s, null v1, null v2, count(distinct session_id) c" " from h group by to_char(sample_time, 'hh24:mi:ss') union all" " select 8 t, null s, null v1, null v2, to_number(value) c" " from v$parameter where name = 'cpu_count' union all" " select 9 t, null s, null v1, null v2, to_number(value) c" " from v$parameter where name = 'sessions' order by 1, 4, 2".format( " and nvl(wait_class, 'CPU') like :wait_class" if optional_values.get('wait_class', '') else "", " and event like :event" if optional_values.get( 'event', '') else "", " and session_id = :session_id" if optional_values.get('session_id', '') else "", " and sql_id = :sql_id" if optional_values.get( 'sql_id', '') else "", " and object_name like :object_name" if optional_values.get('object_name', '') else "", " and user_id in (select user_id from dba_users " "where username like :user_name)" if optional_values.get( 'user_name', '') else ""), { **required_values, **optional_values }) colors = { 'Other': '#F06EAA', 'Application': '#C02800', 'Configuration': '#5C440B', 'Administrative': '#717354', 'Concurrency': '#8B1A00', 'Commit': '#E46800', 'Idle': '#FFFFFF', 'Network': '#9F9371', 'User I/O': '#004AE7', 'System I/O': '#0094E7', 'Scheduler': '#CCFFCC', 'Queueing': '#C2B79B', 'CPU': '#00CC00' } series = { k[1]: [] for k in sorted(set((item[3], item[2]) for item in r if item[0] == 1), key=lambda x: x[0]) } p = deepcopy(app.config['CHART_CONFIG']) p['style'].colors = tuple(colors[wait_class] for wait_class in series.keys()) p['height'] = 10 * 22 session_count = max(tuple(item[4] for item in r if item[0] == 7) or (0, )) session_limit = max(tuple(item[4] for item in r if item[0] == 9) or (0, )) cpu_count = max(tuple(item[4] for item in r if item[0] == 8) or (0, )) top_activity = StackedLine(**p, legend_at_bottom=True, legend_at_bottom_columns=len(series.keys()), title=f'sessions(max): {session_count}, ' f'sessions(limit): {session_limit}, ' f'cpu cores: {cpu_count};') top_activity.fill = True top_activity.x_labels = sorted(set(item[1] for item in r if item[0] == 1)) top_activity.x_labels_major_every = max( -(-len(top_activity.x_labels) // 20), 1) top_activity.truncate_label = 5 top_activity.show_minor_x_labels = False for label in top_activity.x_labels: for serie in series.keys(): v = tuple( item[4] for item in r if item[0] == 1 and item[1] == label and item[2] == serie) series[serie].append(v[0] if len(v) > 0 else 0) for serie in series.keys(): top_activity.add(serie, series[serie], show_dots=False) top_sql = HorizontalStackedBar(**p) top_sql.show_legend = False top_sql.width = 400 top_sql.show_x_labels = False top_sql.x_labels = sorted(set(item[1] for item in r if item[0] == 2), key=lambda x: sum( tuple(item[4] for item in r if item[0] == 2 and item[1] == x))) top_sql.height = len(top_sql.x_labels) * 22 series = { k[1]: [] for k in sorted(set((item[3], item[2]) for item in r if item[0] == 2), key=lambda x: x[0]) } for label in top_sql.x_labels: for serie in series.keys(): v = tuple( item[4] for item in r if item[0] == 2 and item[1] == label and item[2] == serie) series[serie].append(v[0] if len(v) > 0 else 0) for serie in series.keys(): # todo https://github.com/Kozea/pygal/issues/18 top_sql.add(serie, [ dict(value=item, color=colors[serie], xlink=dict(href=url_for('get_query', target=target, query=top_sql.x_labels[i], _external=True), target='_blank')) for i, item in enumerate(series[serie]) ]) top_objects = HorizontalStackedBar(**p) top_objects.show_legend = False top_objects.width = 400 top_objects.show_x_labels = False top_objects.x_labels = sorted(set(item[1] for item in r if item[0] == 3), key=lambda x: sum( tuple(item[4] for item in r if item[0] == 3 and item[1] == x))) series = { k[1]: [] for k in sorted(set((item[3], item[2]) for item in r if item[0] == 3), key=lambda x: x[0]) } top_objects.height = len(top_objects.x_labels) * 22 for label in top_objects.x_labels: for serie in series.keys(): v = tuple( item[4] for item in r if item[0] == 3 and item[1] == label and item[2] == serie) series[serie].append(v[0] if len(v) > 0 else 0) for serie in series.keys(): top_objects.add( serie, [dict(value=item, color=colors[serie]) for item in series[serie]]) pie_type = 5 if 'wait_class' in optional_values.keys( ) or 'event' in optional_values.keys() else 4 top_waits = Pie(**p) top_waits.show_legend = False top_waits.width = 140 top_waits.width = 140 top_waits.inner_radius = 0.5 labels = tuple( k[1] for k in sorted(set( (item[3], item[2]) for item in r if item[0] == pie_type), key=lambda x: x[0] if isinstance(x[0], int) else 0)) for label in labels: top_waits.add( label, tuple(item[4] for item in r if item[0] == pie_type and item[2] == label)[0]) top_sessions = HorizontalStackedBar(**p) top_sessions.show_legend = False top_sessions.width = 300 top_sessions.show_x_labels = False top_sessions.x_labels = sorted( set(item[1] for item in r if item[0] == 6), key=lambda x: sum( tuple(item[4] for item in r if item[0] == 6 and item[1] == x))) top_sessions.height = len(top_sessions.x_labels) * 22 series = { k[1]: [] for k in sorted(set((item[3], item[2]) for item in r if item[0] == 6), key=lambda x: x[0]) } for label in top_sessions.x_labels: for serie in series.keys(): v = tuple( item[4] for item in r if item[0] == 6 and item[1] == label and item[2] == serie) series[serie].append(v[0] if len(v) > 0 else 0) for serie in series.keys(): top_sessions.add(serie, [ dict(value=item, color=colors[serie], xlink=dict( href=url_for('get_session', target=target, sid=top_sessions.x_labels[i].split(':')[0], _external=True), target='_blank')) for i, item in enumerate(series[serie]) ]) return render_template( 'top_activity.html', top_activity=top_activity.render_data_uri(), top_sql=top_sql.render_data_uri() if 'sql_id' not in optional_values.keys() else None, top_sessions=top_sessions.render_data_uri() if 'session_id' not in optional_values.keys() else None, top_objects=top_objects.render_data_uri(), top_waits=top_waits.render_data_uri() if labels else None)
# pie_chart.add('p2', [120]) # pie_chart.add('p3', [779]) # pie_chart.add('other', [1000]) # # pie_chart.render_in_browser() from pygal import Pie # chart = pygal.Pie(inner_radius=.3, pretty_print=True) # chart.title = 'Browser usage in February 2012 (in %)' # chart.add('IE', 19.5) # chart.add('Firefox', 36.6) # chart.add('Chrome', 36.3) # chart.add('Safari', 4.5) # chart.add('Opera', 2.3) # chart.render_in_browser() pie = Pie() pie.add('IE', 19.5) pie.add('Firefox', 36.6) pie.add('Chrome', 36.3) pie.add('Safari', 4.5) pie.add('Opera', 2.3) half = Pie(inner_radius=.7, half_pie=True) half.add('IE', 19.5) half.add('Firefox', 36.6) half.add('Chrome', 36.3) half.add('Safari', 4.5) half.add('Opera', 2.3) assert pie.render_in_browser() != half.render_in_browser()
def node_apply_end(repo, node, duration=None, interactive=None, result=None, **kwargs): if environ.get('TERM_PROGRAM', None) != "iTerm.app" or not interactive: LOG.debug("skipping iTerm stats (wrong terminal)") return if not IMPORTS: LOG.error("failed to import dependencies of itermstats plugin") return css_file = NamedTemporaryFile(delete=False) css_file.write(".text-overlay { display: none; }") css_file.close() config = Config( height=150, style=STYLE, width=350, ) config.css.append(css_file.name) chart = Pie(config) chart.add('correct', result.correct) chart.add('fixed', result.fixed) chart.add('skipped', result.skipped) chart.add('failed', result.failed) png_data = cairosvg.svg2png(bytestring=chart.render()) png_data_b64 = b64encode(png_data) remove(css_file.name) print("\033]1337;File=inline=1:{}\007".format(png_data_b64))
def test_half_pie(): pie = Pie() pie.add('IE', 19.5) pie.add('Firefox', 36.6) pie.add('Chrome', 36.3) pie.add('Safari', 4.5) pie.add('Opera', 2.3) half = Pie(half_pie=True) half.add('IE', 19.5) half.add('Firefox', 36.6) half.add('Chrome', 36.3) half.add('Safari', 4.5) half.add('Opera', 2.3) assert pie.render() != half.render()
def test_half_pie(): pie = Pie() pie.add("IE", 19.5) pie.add("Firefox", 36.6) pie.add("Chrome", 36.3) pie.add("Safari", 4.5) pie.add("Opera", 2.3) half = Pie(half_pie=True) half.add("IE", 19.5) half.add("Firefox", 36.6) half.add("Chrome", 36.3) half.add("Safari", 4.5) half.add("Opera", 2.3) assert pie.render() != half.render()
def test_donut(): chart = Pie(inner_radius=.3, pretty_print=True) chart.title = 'Browser usage in February 2012 (in %)' chart.add('IE', 19.5) chart.add('Firefox', 36.6) chart.add('Chrome', 36.3) chart.add('Safari', 4.5) chart.add('Opera', 2.3) assert chart.render()
def test_donut(): """Test a donut pie chart""" chart = Pie(inner_radius=.3, pretty_print=True) chart.title = 'Browser usage in February 2012 (in %)' chart.add('IE', 19.5) chart.add('Firefox', 36.6) chart.add('Chrome', 36.3) chart.add('Safari', 4.5) chart.add('Opera', 2.3) assert chart.render()
def test_pie_table(): """Test rendering a table for a pie""" chart = Pie(inner_radius=.3, pretty_print=True) chart.title = 'Browser usage in February 2012 (in %)' chart.add('IE', 19.5) chart.add('Firefox', 36.6) chart.add('Chrome', 36.3) chart.add('Safari', 4.5) chart.add('Opera', 2.3) q = pq(chart.render_table()) assert len(q('table')) == 1
from pygal import Pie pie_chart = Pie() pie_chart.title = 'Browser usage in February 2012 (in %)' pie_chart.add('IE', 19.5) pie_chart.add('Firefox', 36.6) pie_chart.add('Chrome', 36.3) pie_chart.add('Safari', 4.5) pie_chart.add('Opera', 2.3) pie_chart.render()
def test_pie_serie_radius(): pie = Pie() for i in range(10): pie.add(str(i), i, inner_radius=(10 - i) / 10) return pie.render_response()
def _render_pie(self, values, labels, title, filename): pie_chart = Pie(config=self.pygal_config) pie_chart.title = title for label, val in zip(labels, values): pie_chart.add(label, val) pie_chart.render_to_file(filename)
def test_donut(): chart = Pie(inner_radius=0.3, pretty_print=True) chart.title = "Browser usage in February 2012 (in %)" chart.add("IE", 19.5) chart.add("Firefox", 36.6) chart.add("Chrome", 36.3) chart.add("Safari", 4.5) chart.add("Opera", 2.3) assert chart.render()
def test_multiseries_donut(): # this just demos that the multiseries pie does not respect # the inner_radius chart = Pie(inner_radius=0.3, pretty_print=True) chart.title = "Browser usage by version in February 2012 (in %)" chart.add("IE", [5.7, 10.2, 2.6, 1]) chart.add("Firefox", [0.6, 16.8, 7.4, 2.2, 1.2, 1, 1, 1.1, 4.3, 1]) chart.add("Chrome", [0.3, 0.9, 17.1, 15.3, 0.6, 0.5, 1.6]) chart.add("Safari", [4.4, 0.1]) chart.add("Opera", [0.1, 1.6, 0.1, 0.5]) assert chart.render()
def test_multiseries_donut(): """Test a donut pie chart with multiserie""" # this just demos that the multiseries pie does not respect # the inner_radius chart = Pie(inner_radius=.3, pretty_print=True) chart.title = 'Browser usage by version in February 2012 (in %)' chart.add('IE', [5.7, 10.2, 2.6, 1]) chart.add('Firefox', [.6, 16.8, 7.4, 2.2, 1.2, 1, 1, 1.1, 4.3, 1]) chart.add('Chrome', [.3, .9, 17.1, 15.3, .6, .5, 1.6]) chart.add('Safari', [4.4, .1]) chart.add('Opera', [.1, 1.6, .1, .5]) assert chart.render()
def test_multiseries_donut(): # this just demos that the multiseries pie does not respect # the inner_radius chart = Pie(inner_radius=.3, pretty_print=True) chart.title = 'Browser usage by version in February 2012 (in %)' chart.add('IE', [5.7, 10.2, 2.6, 1]) chart.add('Firefox', [.6, 16.8, 7.4, 2.2, 1.2, 1, 1, 1.1, 4.3, 1]) chart.add('Chrome', [.3, .9, 17.1, 15.3, .6, .5, 1.6]) chart.add('Safari', [4.4, .1]) chart.add('Opera', [.1, 1.6, .1, .5]) assert chart.render()
def test_64_colors(): colors = [rotate("#ff0000", i * 360 / 64) for i in range(64)] pie = Pie(style=Style(colors=colors)) for i in range(64): pie.add(str(i), 1) return pie.render_response()