def analysis(request): if request.method == "GET": version = random.randint(0, 1000) search_dict = request.GET.dict() filter_dict = {} for key, value in search_dict.items(): # Bench if key == "movement1" and value == "bench1": for key, value in search_dict.items(): if value != '' and value != "None" and key != "movement1": filter_dict[key] = value if len(filter_dict) > 0: print(filter_dict) filtered_movements = BenchMovement.objects.\ filter(user_id=request.user.id).filter(**filter_dict) max_weight = [] for workout in filtered_movements: max_weight.append(workout.movement_weight) line_chart = pygal.Line(style=NeonStyle) line_chart.title = 'Lift Progression' line_chart.x_labels = map(str, range(1, len(max_weight))) line_chart.add('Bench', max_weight) line_chart.render_to_file(IMAGE_PATH + 'tracker/static/tmp/chart.svg') # Deadlift if key == "movement1" and value == "deadlift1": for key, value in search_dict.items(): if value != '' and value != "None" and key != "movement1": filter_dict[key] = value if len(filter_dict) > 0: print(filter_dict) filtered_movements = DeadliftMovement.objects.\ filter(user_id=request.user.id).filter(**filter_dict) max_weight = [] for workout in filtered_movements: max_weight.append(workout.movement_weight) line_chart = pygal.Line(style=NeonStyle) line_chart.title = 'Lift Progression' line_chart.x_labels = map(str, range(1, len(max_weight))) line_chart.add('Deadlift', max_weight) line_chart.render_to_file(IMAGE_PATH + 'tracker/static/tmp/chart.svg') # Squat if key == "movement1" and value == "squat1": for key, value in search_dict.items(): if value != '' and value != "None" and key != "movement1": filter_dict[key] = value if len(filter_dict) > 0: print(filter_dict) filtered_movements = SquatMovement.objects.\ filter(user_id=request.user.id).filter(**filter_dict) max_weight = [] for workout in filtered_movements: max_weight.append(workout.movement_weight) line_chart = pygal.Line(style=NeonStyle) line_chart.title = 'Lift Progression' line_chart.x_labels = map(str, range(1, len(max_weight))) line_chart.add('Squat', max_weight) line_chart.render_to_file(IMAGE_PATH + 'tracker/static/tmp/chart.svg') # Upper if key == "movement1" and value == "upper1": for key, value in search_dict.items(): if value != '' and value != "None" and key != "movement1": filter_dict[key] = value if len(filter_dict) > 0: print(filter_dict) filtered_movements = SquatMovement.objects.\ filter(user_id=request.user.id).filter(**filter_dict) max_weight = [] for workout in filtered_movements: max_weight.append(workout.movement_weight) line_chart = pygal.Line(style=NeonStyle) line_chart.title = 'Lift Progression' line_chart.x_labels = map(str, range(1, len(max_weight))) line_chart.add('Squat', max_weight) line_chart.render_to_file(IMAGE_PATH + 'tracker/static/tmp/chart.svg') upperform = UpperForm() lowerform = LowerForm() return render(request, 'tracker/analysis.html', { 'upper_form': upperform, 'lower_form': lowerform, 'version': version })
def render(self, name=''): values = [ self.generation.current_generation(self.day * self.iterations + self.time_step - 1), self._compute_tcl_power() + np.sum([l.load() for l in self.loads]), np.average([tcl.SoC for tcl in self.tcls]) * 100, self.temperatures[self.day * self.iterations + self.time_step - 1], np.average([l.load() for l in self.loads]), self.sale_price, self.battery.SoC * 100, self.energy_sold, self.energy_bought, self.grid.buy_prices[self.day * self.iterations + self.time_step - 1], self.grid.sell_prices[self.day * self.iterations + self.time_step - 1], self.control, self._compute_tcl_power() ] for index, key in enumerate(RENDER_VALUES_dict.keys()): RENDER_VALUES_dict[key].append(values[index]) if self.time_step == self.iterations: self.html_file = open("app/templates/figure.html", 'w') self.html_file.write("{% extends \"base.html\" %}" + "\n" + "{% block content %}" + "\n") self.html_file.write("<h1>Day: {}</h1>".format(self.day)) ax = pg.Line(height=300, include_x_axis=True, label_font_size=2, truncate_legend=-1, title_font_size=20, x_title="Time steps", y_title="Energy" + " (kWh)", legend_at_bottom=True, x_label_rotation=0) ax.title = "Energy generated and consumed" ax.x_labels = range(self.iterations) ax.add(RENDER_VALUES_list[0], RENDER_VALUES_dict[RENDER_VALUES_list[0]]) ax.add(RENDER_VALUES_list[1], RENDER_VALUES_dict[RENDER_VALUES_list[1]]) self.add_content(ax, 1) ax = pg.Line(height=300, include_x_axis=True, label_font_size=1, truncate_legend=-1, title_font_size=20, x_title="Time steps", y_title="TCLs SOC", legend_at_bottom=False, x_label_rotation=0) ax.title = "Average TCLs state of charge % and outdoor temperatures" ax.x_labels = range(self.iterations) ax.add(RENDER_VALUES_list[2], RENDER_VALUES_dict[RENDER_VALUES_list[2]]) ax.add(RENDER_VALUES_list[3], RENDER_VALUES_dict[RENDER_VALUES_list[3]], secondary=True) self.add_content(ax, 2) ax = pg.Line(height=300, include_x_axis=True, label_font_size=1, truncate_legend=-1, title_font_size=20, x_title="Time steps", spacing=1, legend_at_bottom=False, x_label_rotation=0, style=custom_style) ax.title = "Retail prices and average consumption from price responsive loads" ax.x_labels = range(self.iterations) ax.add(RENDER_VALUES_list[5], RENDER_VALUES_dict[RENDER_VALUES_list[5]]) ax.add(RENDER_VALUES_list[4], RENDER_VALUES_dict[RENDER_VALUES_list[4]], secondary=True) self.add_content(ax, 3) ax = pg.Line(height=300, include_x_axis=True, label_font_size=1, truncate_legend=-1, title_font_size=20, x_title="Time steps", show_legend=False, x_label_rotation=0, range=(0, 100)) ax.title = "State of charge of the energy storage system %" ax.x_labels = range(self.iterations) ax.add(RENDER_VALUES_list[6], RENDER_VALUES_dict[RENDER_VALUES_list[6]]) self.add_content(ax, 4) ax = pg.Bar(height=300, include_x_axis=True, label_font_size=2, truncate_legend=-1, title_font_size=20, x_title="Time steps", legend_at_bottom=True, x_label_rotation=0) ax.title = "Energy sold to and purchased from the main grid (kWh)" ax.x_labels = range(self.iterations) ax.add(RENDER_VALUES_list[8], RENDER_VALUES_dict[RENDER_VALUES_list[8]]) ax.add(RENDER_VALUES_list[7], RENDER_VALUES_dict[RENDER_VALUES_list[7]]) self.add_content(ax, 5) ax = pg.Line(height=300, include_x_axis=True, label_font_size=2, truncate_legend=-1, title_font_size=20, x_title="Time steps", legend_at_bottom=True, x_label_rotation=0) ax.title = "Electricity prices in the balancing market (cents/kW)" ax.x_labels = range(self.iterations) ax.add(RENDER_VALUES_list[9], RENDER_VALUES_dict[RENDER_VALUES_list[9]]) ax.add(RENDER_VALUES_list[10], RENDER_VALUES_dict[RENDER_VALUES_list[10]]) self.add_content(ax, 6) ax = pg.Bar(height=300, include_x_axis=True, label_font_size=2, truncate_legend=-1, title_font_size=20, x_title="Time steps", legend_at_bottom=True, x_label_rotation=0) ax.title = "Energy allocated to and consumed by TCLs (kWh)" ax.x_labels = range(self.iterations) ax.add(RENDER_VALUES_list[12], RENDER_VALUES_dict[RENDER_VALUES_list[12]]) ax.add(RENDER_VALUES_list[11], RENDER_VALUES_dict[RENDER_VALUES_list[11]]) self.add_content(ax, 7) self.html_file.write( "\n <form action=\"\" method=\"post\" novalidate> \n" + "{{ form.hidden_tag() }} \n " + "<p>{{ form.next_day() }}</p>\n ") if self.day != self.day0: self.html_file.write("<p>{{ form.previous_day() }}</p>\n ") self.html_file.write(" </form>") self.html_file.write("{% endblock %}") self.html_file.close() reset_dict() ## TO DO: write a render method using pygal pass
def piechart(): conn = psycopg2.connect( "dbname='salesdemo' user='******' host='localhost' password='******'" ) cur1 = conn.cursor() cur1.execute("""SELECT type, count (type) FROM public.inventories group by inventories.type """) records = cur1.fetchall() # print(type(records)) for each in records: print(each) ratios = [("Gentlement", 5), ("Ladies", 9)] pie_chart = pygal.Pie() pie_chart.title = 'Browser usage in February 2012 (in %)' pie_chart.add('Products', records[0][1]) pie_chart.add('Others', records[1][1]) pie_chart.add('Services', records[2][1]) # pie_chart.add('Chrome', 36.3) # pie_chart.add('Safari', 4.5) # pie_chart.add('Opera', 2.3) pie_data = pie_chart.render_data_uri() cur = conn.cursor() cur.execute( """SELECT to_char(to_timestamp(date_part('month',sales.ceated_at)::text,'MM'),'Month') as month, round(sum(inventories.selling_price*sales.quantity)) from public.inventories join sales on sales.inv_id = inventories.id group by extract (month from sales.ceated_at) order by extract (month from sales.ceated_at) asc """) rows = cur.fetchall() # print(type(rows)) months = [] totalsales = [] for each in rows: months.append(each[0]) totalsales.append(each[1]) print(months) print(totalsales) graph = pygal.Line() graph.title = '% Change Coolness of programming languages over time.' graph.x_labels = months graph.add('Total Sales', totalsales) # graph.add('Java', [15, 45, 76, 80, 91, 95]) # graph.add('C++', [5, 51, 54, 102, 150, 201]) # graph.add('All others combined!', [5, 15, 21, 55, 92, 105]) graph_data = graph.render_data_uri() return render_template('xyz.html', pie_data=pie_data, graph_data=graph_data)
import pygal import math filename='btc_close_2017_urllib.json' with open(filename) as f: btc_data=json.load(f) #创建5个列表,分别存储日期和收盘价 dates=[] months=[] weeks=[] weekdays=[] close=[] #每天的信息 for btc_dict in btc_data: dates.append(btc_dict['date']) months.append(int(btc_dict['month'])) weeks.append(int(btc_dict['week'])) weekdays.append(btc_dict['weekday']) close.append(int(float(btc_dict['close']))) #绘制图像 line_chart=pygal.Line(x_label_rotation=20,show_minor_x_labels=False) line_chart.title="收盘价(¥)" line_chart.x_labels=dates N=20 #X坐标每隔20天显示一次 line_chart.x_labels_major=dates[::N] close_log=[math.log10(_) for _ in close] line_chart.add("log收盘价",close_log) line_chart.render_to_file("收盘价折线图(¥).svg")
def queryStockData(symbol, chart_type, time_series, start_date, end_date): """ Given a set of inputs performs a stock query """ # API Query paramters series = "TIME_SERIES_" + Constants.TIMESERIES[time_series].upper() data = { "function": series, "symbol": symbol, "outputsize": "full", "interval": "60min", "apikey": Constants.API_KEY } print(data) # Sending our request to the API using the information we put in the data collection. apiCall = requests.get(Constants.API_URL, params=data) # Stores the json-enconded content in the retrieved data. response = apiCall.json() if (response.__contains__('Note')): # We hit a throttling limit; just return an error and wait. return "throttled" # If statements to change key depending on the Time Serires selected. if series == "TIME_SERIES_INTRADAY": timeSeries = "Time Series (60min)" elif series == "TIME_SERIES_DAILY": timeSeries = "Time Series (Daily)" elif series == "TIME_SERIES_WEEKLY": timeSeries = "Weekly Time Series" elif series == "TIME_SERIES_MONTHLY": timeSeries = "Monthly Time Series" dates = [] opens = [] highs = [] lows = [] closes = [] # Parsing the dates from the user input startDate = convert_date(start_date) endDate = convert_date(end_date) items = list(response[timeSeries].items()) i = len(items) - 1 while i >= 0: date, stockData = items[i] # Parsing the date from the api record. entryDate = convert_date(date) # Populating lists with data, within the given date range, from API if (entryDate >= startDate and entryDate <= endDate): model = StockModel(stockData) opens.append(model.open) highs.append(model.high) lows.append(model.low) closes.append(model.close) dates.append(date) i = i - 1 # If true, prints line chart. Else prints the bar chart. if (chart_type == "1"): chart = pygal.Bar(x_label_rotation=45) else: chart = pygal.Line(x_label_rotation=45) chart.x_labels = dates chart.title = "Stock Date for " + symbol + ": " + start_date + " to " + end_date chart.add("Open", opens) chart.add("High", highs) chart.add("Low", lows) chart.add("Close", closes) return chart.render_data_uri()
plt.xlabel('', fontsize=14) fig.autofmt_xdate() plt.ylabel('Temp (F)', fontsize=14) plt.tick_params(axis='both', labelsize=14) plt.savefig('images/plot_death_valley.png', bbox_inches='tight') plt.show() # plt.scatter() fig = plt.figure(figsize=(10, 6)) plt.scatter(dates, highs, c='red', edgecolors='none', s=10) plt.scatter(dates, lows, c='blue', edgecolors='none', s=10) plt.fill_between(dates, highs, lows, facecolor='blue', alpha=.1) plt.title('Death Valley 2014- highs and lows', fontsize=24) plt.xlabel('', fontsize=14) fig.autofmt_xdate() plt.ylabel('Temp (F)', fontsize=14) plt.tick_params(axis='both', labelsize=14) plt.savefig('images/scatter_death_valley.png', bbox_inches='tight') plt.show() # pygal.Line() hist = pygal.Line() hist.title = 'Death Valley 2014' hist.x_labels = dates hist.y_labels = highs hist.y_labels = lows hist.add('Highs', highs) hist.add('Lows', lows) hist.render_to_file('images/pygal_line_death_valley.svg')
import json import pygal with open('data.json') as test_data: #receive data data = json.load(test_data) city = {} remove_case = ["Total (All India)", "Total (States)", "Total (Uts)"] for year, posit in zip(range(2001, 2013), range(12)): for i in data: """edit year to find 2001-2012 and check requestment""" if i["State"] not in remove_case and i["Age_group"] != "0-100+" and i["Year"] == year: """check in have it dict already or not""" if i["State"] in city: city[i["State"]][posit] += i["Total"] else: city[i["State"]] = [i["Total"], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] print("***Complete***") #finish """show data process""" list_city = sorted(list(city)) line_chart = pygal.Line(height=800, width=1000) line_chart.title = "2001-2012" line_chart.x_labels = map(str, range(2001, 2013)) for i in list_city: line_chart.add(i, city[i]) print(i, ":", city[i]) line_chart.render_to_file('2001-2012.svg')
#Get Evaluation Metrics -- MSE, MAE, R2 Score, and Explained Variance Score print("Model evaluation metrics: ") print("Test MSE:", mean_squared_error(y_true=y_test, y_pred=preds)) print("Test MAE: ", mean_absolute_error(y_true=y_test, y_pred=preds)) print("Test R2 Score: ", r2_score(y_pred=preds, y_true=y_test)) print("Explained Variance Score: ", explained_variance_score(y_pred=preds, y_true=y_test)) print("+++++++++++++++++++++++++++++++++++++++") #Convert Preds and Actual Values on Test Set to Flat List for Plotting preds_flat = preds.flatten().tolist() y_test_flat = y_test.flatten().tolist() #Plot Predictions vs Actual line_chart = pygal.Line(width=500, height=300, explicit_size=True, x_labels_major_every=150, show_minor_x_labels=False, x_label_rotation=45) line_chart.title = 'Test Predictions vs Actual' line_chart.x_labels = df['Date'][::-1].iloc[int(0.8 * len(df)):].tolist() line_chart.add('Preds', preds_flat) line_chart.add('Actual', y_test_flat) line_chart.render_in_browser() # Save Model: model.save('EUR_USD_1_Day_Forecast_2.h5') print("Model saved to disk: EUR_USD_1_Day_Forecast_2.h5")
import pygal chart = pygal.Line(title=u'Some different points') chart.x_labels = ('one', 'two', 'three') chart.add('line', [.0002, .0005, .00035]) chart.add('other line', [1000, 2000, 7000], secondary=True) print(chart.render(is_unicode=True))
import pygal chart = pygal.Line(fill=True, zero=.0004) chart.add('line', [.0002, .0005, .00035]) print(chart.render(is_unicode=True))
def plot(start_show, end_show, interval): try: conn = http.client.HTTPConnection("") payload = "temperature=23&token=" headers = { 'content-type': "application/x-www-form-urlencoded", 'x-access-token': "", 'cache-control': "no-cache", 'postman-token': "" } if interval == "24": conn.request("GET", "/api/temperature?unit=hours&count=24", payload, headers) smhi_date, smhi_temp = get_smhi('last-days') smhi_date.pop(0) smhi_temp.pop(0) elif interval == 'today': now = datetime.now() now = pytz.timezone('UTC').localize(now) now = now.astimezone(pytz.timezone('Europe/Stockholm')) nbr_hrs = str(now.hour) conn.request("GET", "/api/temperature?unit=hours&count=" + nbr_hrs, payload, headers) smhi_date, smhi_temp = get_smhi('last-days') start_time = datetime.now().strftime("%Y-%m-%d 00:00:00") k = 0 while smhi_date[k] <= str(start_time): smhi_date.pop(0) smhi_temp.pop(0) else: end_dtg = datetime.strptime(end_show, "%Y-%m-%d %H:%M:%S") start_dtg = datetime.strptime(start_show, "%Y-%m-%d %H:%M:%S") delta = end_dtg - start_dtg nbr_days = str(delta.days) end_time = end_dtg.strftime('%Y-%m-%dT%H:%M:%S.%fZ') conn.request( "GET", "/api/temperature?unit=days&enddate=" + end_time + "&count=" + nbr_days, payload, headers) smhi_date, smhi_temp = get_smhi('last-months') k = 0 while smhi_date[k] < str(start_dtg): smhi_date.pop(0) smhi_temp.pop(0) smhi_temp = map(float, smhi_temp) res = conn.getresponse() data = json.loads(res.read().decode('utf-8')) temp = [] timestamp = [] for x in data['temperatures']: temp.append(float(x['temperature'])) dtg = datetime.strptime(x['time'], "%Y-%m-%dT%H:%M:%S.%fZ") dtg = pytz.timezone('UTC').localize(dtg) dtg = dtg.astimezone( pytz.timezone('Europe/Stockholm')).replace(tzinfo=None) dtg = dtg.strftime('%Y-%m-%d %H:%M:%S') timestamp.append(dtg) start = datetime.strptime(data['temperatures'][0]['time'], "%Y-%m-%dT%H:%M:%S.%fZ") start = pytz.timezone('UTC').localize(start) start = start.astimezone( pytz.timezone('Europe/Stockholm')).replace(tzinfo=None) start = start.strftime('%Y-%m-%d %H:%M:%S') end = datetime.strptime( data['temperatures'][len(data['temperatures']) - 1]['time'], "%Y-%m-%dT%H:%M:%S.%fZ") end = pytz.timezone('UTC').localize(end) end = end.astimezone( pytz.timezone('Europe/Stockholm')).replace(tzinfo=None) end = end.strftime('%Y-%m-%d %H:%M:%S') title = 'Temperature in degrees Celsius between ' + start + ' and ' + end line_chart = pygal.Line(x_label_rotation=30) line_chart.title = title if len(temp) < 30: line_chart.x_labels = map(str, list(timestamp)) line_chart.add('Inside', list(temp)) if interval != 'interval': line_chart.add('Outside', list(smhi_temp), secondary=True, x_title='Time') return Response(response=line_chart.render(), content_type='image/svg+xml') finally: conn.close()
import pygal chart = pygal.Line(truncate_label=-1) chart.x_labels = [ 'This is the first point !', 'This is the second point !', 'This is the third point !', 'This is the fourth point !'] chart.add('line', [0, .0002, .0005, .00035]) print(chart.render(is_unicode=True))
# -*- coding: utf-8 -*- import pygal param_line_chart = pygal.Line(interpolate='cubic', label_font_size=20, x_label_rotation=50) param_line_chart.title = 'Parameter Line Chart' param_line_chart.x_labels = map(str, [ "Data Object 1", "Data Object 2", "Data Object 3", "Data Object 4", "Data Object 5", "Data Object 6" ]) param_line_chart.add('Data-Set 1', [8, 16, 24, 32, 48, 56]) param_line_chart.add('Data-Set 2', [2, 4, 6, 8, 10, 12]) param_line_chart.add('Data-Set 3', [1, 3, 5, 7, 9, 12]) param_line_chart.render_to_file('lineparam.svg')
custom_style = pygal.style.Style(label_font_size=18, major_label_font_size=18, title_font_size=24) our_css_file = os.path.join(os.path.dirname(__file__), 'pygal.css') line_chart = pygal.Line( css=('file://style.css', 'file://graph.css', 'file://' + our_css_file), background='transparent', plot_background='transparent', colors=('#000000', '#888888'), opacity='1.0', show_dots=False, x_label_rotation=1, x_labels_major_every=HOP_LIMIT // (HOP_STEP * 10), # legend_at_bottom=True, # legend_at_bottom_columns=4, # legend_box_size=24, # legend_font_size=18, show_legend=False, margin=54, range=(0, 300), show_minor_x_labels=False, style=custom_style) line_chart.title = sys.argv[2] line_chart.x_title = 'Turnaround time (ms)' line_chart.y_title = 'Requests count with turnaround time' line_chart.x_labels = [ttime for ttime in range(0, HOP_LIMIT, HOP_STEP)] for i, tsv_file in enumerate(sys.argv[3:]): hop_counts = read_tsv(tsv_file)
def line(): with open('us_exchange_extracted.json', 'r') as data_file: us_exchange_data = json.load(data_file) with open('bitcoin_prices.json', 'r') as data_file: bitcoin_data = json.load(data_file) with open('ethereum_prices.json', 'r') as data_file: ethereum_data = json.load(data_file) custom_style = Style(colors=('#6699ff', '#1cbc7c'), background='#000000', plot_background='#1a1a1a', foreground='#ffffff', foreground_subtle='#ffffff', foreground_strong='#ffffff', legend_font_size=10, font_family='googlefont:Raleway', major_label_font_size=7, label_font_size=8) chart = pygal.Line(width=600, height=300, style=custom_style, dots_size=0.8, label_font_size=6, x_title='Time', y_title='Price', x_labels_major_every=300, y_labels_major_every=None, x_label_rotation=20, show_minor_x_labels=False) chart.title = 'Exchange rates of US Dollar' coin_chart = pygal.Line(width=600, height=300, style=custom_style, dots_size=0.8, label_font_size=10, x_title='Time', y_title='Price', x_labels_major_every=200, y_labels_major_every=None, x_label_rotation=20, show_minor_x_labels=False) coin_chart.title = 'Prices of coins' francs_list = [] for x in us_exchange_data: temp = {'value': x['FRANCS/US$'], 'label': x['YEAR']} francs_list.append(temp) chart.add('Francs/USD', francs_list) singapore_list = [] for x in us_exchange_data: temp = {'value': x['SINGAPORE/US$'], 'label': x['YEAR']} singapore_list.append(temp) chart.add('Singapore/USD', singapore_list) kroner_list = [] for x in us_exchange_data: temp = {'value': x['KRONER/US$'], 'label': x['YEAR']} kroner_list.append(temp) chart.add('Kroner/USD', kroner_list) ethereum_list = [] for x in ethereum_data: temp = {'value': x['Open'], 'label': x['Date']} ethereum_list.append(temp) ethereum_list.reverse() coin_chart.add('Ethereum', (ethereum_list)) coin_chart.x_labels = [x['label'] for x in ethereum_list] bitcoin_list = [] for x in bitcoin_data: temp = {'value': x['Open'], 'label': x['Date']} bitcoin_list.append(temp) bitcoin_list.reverse() coin_chart.add('Bitcoin', (bitcoin_list)) chart.x_labels = [x['YEAR'] for x in us_exchange_data] coin_chart.render_to_file('static/images/coin_line_chart.svg') chart.render_to_file('static/images/line_chart.svg') img_url = 'static/images/line_chart.svg?cache=' + str(time.time()) coin_url = 'static/images/coin_line_chart.svg?cache=' + str(time.time()) return render_template('line_chart.html', image_url=img_url, coin_chart=coin_url)
def data_visualisation(): conn = psycopg2.connect( " dbname='inventory_management_system' user='******' host='localhost' port='5432' password='******' " ) cur = conn.cursor() cur.execute(""" SELECT type, count(type) FROM public.inventories group by type; """) product_service = cur.fetchall() print(product_service) pie_chart = pygal.Pie() '''my_pie_data = [ ('Nairobi', 63), ('Mombasa', 20), ('Kilifi', 17), ('Machakos', 30), ('Kiambu', 7)]''' pie_chart.title = 'Ratio of product and service' for each in product_service: pie_chart.add(each[0], each[1]) pie_data = pie_chart.render_data_uri() #end of pie chart #start of line graph cur.execute(""" SELECT EXTRACT(MONTH FROM s.created_at) as sales_month, sum(quantity*selling_price) as total_sales from sales as s join inventories as i on s.invid = i.id group by sales_month order by sales_month asc; """) monthly_sales = cur.fetchall() print(monthly_sales) data = [{ 'month': 'January', 'total': 22 }, { 'month': 'February', 'total': 27 }, { 'month': 'March', 'total': 23 }, { 'month': 'April', 'total': 20 }, { 'month': 'May', 'total': 12 }, { 'month': 'June', 'total': 32 }, { 'month': 'July', 'total': 42 }, { 'month': 'August', 'total': 72 }, { 'month': 'September', 'total': 52 }, { 'month': 'October', 'total': 42 }, { 'month': 'November', 'total': 92 }, { 'month': 'December', 'total': 102 }] a = [] b = [] for each in monthly_sales: a.append(each[0]) b.append(each[1]) line_chart = pygal.Line() line_chart.title = 'Total Sales in the year 2019' line_chart.x_labels = a line_chart.add('Total Sales', b) line_data = line_chart.render_data_uri() return render_template('chart.html', pie=pie_data, line=line_data)
import pygal chart = pygal.Line(inverse_y_axis=True) chart.add('line', [.0002, .0005, .00035]) print(chart.render(is_unicode=True))
else: highStr = "" highStr = highStr.join(temhigh) highs.append(int(highStr)) # 以上三行将高温NavigableString转成int类型并存入高温列表 temp.append(temperate) final.append(temp) i = i + 1 # 将最终的获取的天气写入csv文件 with open('weather.csv', 'a', errors='ignore', newline='') as f: f_csv = csv.writer(f) f_csv.writerows([cityname]) f_csv.writerows(final) # 绘图 bar = pygal.Line() # 创建折线图 bar.add('最低气温', lows) bar.add('最高气温', highs) bar.x_labels = daytimes bar.x_labels_major = daytimes[::30] # bar.show_minor_x_labels = False # 不显示X轴最小刻度 bar.x_label_rotation = 45 bar.title = cityname+'未来七天气温走向图' bar.x_title = '日期' bar.y_title = '气温(摄氏度)' bar.legend_at_bottom = True bar.show_x_guides = False
# coding=utf-8
foreground_dark='rgba(0, 0, 0, 0.3)', colors=('rgb(163, 190, 140)', 'rgb(123, 163, 168)', 'rgb(130, 192, 175)', 'rgb(159, 224, 246)', 'rgb(0, 146, 199)', 'rgb(91, 144, 191)', 'rgb(40, 81, 113)', 'rgb(190, 173, 146)', 'rgb(243, 90, 74)', 'rgb(91, 73, 71)', 'rgb(218, 145, 122)', 'rgb(242, 156, 156)') ) line = pygal.Line( width=800, height=400, interpolate='hermite', style=custom_style) line.title = u'每月种子下载平均量统计' line.x_labels = [u'1月', u'2月', u'3月', u'4月', u'5月', u'6月', u'7月', u'8月', u'9月', u'10月', u'11月', u'12月'] line.add(u'2012年', h.monthes(2012, None)) line.add(u'2013年', h.monthes(2013, None)) line.add(u'2014年', h.monthes(2014, None)) line.render_to_file(hsvgpath + 'month_ave.svg') line = pygal.Line( width=800, height=400, interpolate='hermite', style=custom_style) line.title = u'每月种子下载累积量统计' line.x_labels = [u'起始', u'1月', u'2月', u'3月', u'4月', u'5月', u'6月', u'7月', u'8月', u'9月', u'10月', u'11月', u'12月'] line.add(u'2012年', h.accum(h.monthes(2012))) line.add(u'2013年', h.accum(h.monthes(2013)))
def words_usage(self, event, word, unit='days', amount=7): sql = ''' SELECT date, coalesce(count, 0) AS count FROM generate_series( NOW() - interval %s, NOW(), %s ) AS date LEFT OUTER JOIN ( SELECT date_trunc(%s, timestamp) AS dt, count(*) AS count FROM messages WHERE timestamp >= (NOW() - interval %s) AND timestamp < (NOW()) AND guild_id=%s AND (SELECT count(*) FROM regexp_matches(content, %s)) >= 1 GROUP BY dt ) results ON (date_trunc(%s, date) = results.dt); ''' msg = event.msg.reply(':alarm_clock: One moment pls...') start = time.time() tuples = list(Message.raw( sql, '{} {}'.format(amount, unit), '1 {}'.format(unit), unit, '{} {}'.format(amount, unit), event.guild.id, '\s?{}\s?'.format(word), unit ).tuples()) sql_duration = time.time() - start start = time.time() chart = pygal.Line(style=pygal.style.NeonStyle) chart.title = 'Usage of {} Over {} {}'.format( word, amount, unit, ) if unit == 'days': chart.x_labels = [i[0].strftime('%a %d') for i in tuples] elif unit == 'minutes': chart.x_labels = [i[0].strftime('%X') for i in tuples] else: chart.x_labels = [i[0].strftime('%x %X') for i in tuples] chart.x_labels = [i[0] for i in tuples] chart.add(word, [i[1] for i in tuples]) pngdata = cairosvg.svg2png( bytestring=chart.render(), dpi=72) chart_duration = time.time() - start event.msg.reply( '_SQL: {}ms_ - _Chart: {}ms_'.format( int(sql_duration * 1000), int(chart_duration * 1000), ), attachments=[('chart.png', pngdata)]) msg.delete()
# Dimensions IN_SIZE = 1000 HIDDEN_SIZE = 100 OUT_SIZE = 10 NO_OF_EXAMPLES = 64 LEARNING_RATE = 1e-4 # Input and Output Data ( Here we choose some random input and output to train with) X = Variable(torch.randn(NO_OF_EXAMPLES, IN_SIZE).type(dtype)) Y = Variable(torch.randn(NO_OF_EXAMPLES, OUT_SIZE).type(dtype), requires_grad=False) # For Graphs loss_vals = [] line_graph = pygal.Line() line_graph.title = 'Loss' model = torch.nn.Sequential(torch.nn.Linear(IN_SIZE, HIDDEN_SIZE), torch.nn.ReLU(), torch.nn.Linear(HIDDEN_SIZE, OUT_SIZE)) loss_func = torch.nn.MSELoss(size_average=False) for episode in range(500): # Calculate Y_predict Y_pred = model(X) loss = loss_func(Y_pred, Y) loss_vals.append(loss.data[0]) print("Episode : {} \t Loss = {}".format(episode, loss))
#Import modules
def make_graph(graph_style): msg = "" graph_data = "" rv = ran.randint(3, 60) try: if graph_style == "Line": graph = pygal.Line(fill=True, interpolate='cubic', style=DarkColorizedStyle) graph.title = "Timeline year soda sales in mil" graph.x_labels = ["2000", "2001", "2003", "2004", "2005"] graph.add("Pepsi", [rv, rv + 20, rv - 5, rv + 3, rv + 12]) graph.add("Coca Cola", [rv + 5, rv + 18, rv - 5, rv + 20, rv + 25]) graph.add("Sprite", [rv, rv + 6, rv - 9, rv + 5, rv + 12]) graph.add("Orange", [rv + 4, rv + 30, rv - 10, rv, rv + 8]) graph_data = graph.render_data_uri() msg = "Line" elif graph_style == "Bar": graph = pygal.Bar(fill=True, interpolate='cubic', style=DarkColorizedStyle) graph.title = "Timeline year soda sales in mil" graph.x_labels = ["2000", "2001", "2003", "2004", "2005"] graph.add("Pepsi", [rv, rv + 20, rv - 5, rv + 3, rv + 12]) graph.add("Coca Cola", [rv + 5, rv + 18, rv - 5, rv + 20, rv + 25]) graph.add("Sprite", [rv, rv + 6, rv - 9, rv + 5, rv + 12]) graph.add("Orange", [rv + 4, rv + 30, rv - 10, rv, rv + 8]) graph_data = graph.render_data_uri() msg = "Bar" elif graph_style == "Treemap": treemap = pygal.Treemap(fill=True, interpolate='cubic', style=DarkColorizedStyle) treemap.title = 'Binary TreeMap' treemap.add('A', [2, 1, 12, 4, 2, 1, 1, 3, 12, 3, 4, None, 9]) treemap.add('B', [4, 2, 5, 10, 3, 4, 2, 7, 4, -10, None, 8, 3, 1]) treemap.add('C', [3, 8, 3, 3, 5, 3, 3, 5, 4, 12]) treemap.add('D', [23, 18]) treemap.add('E', [1, 2, 1, 2, 3, 3, 1, 2, 3, 4, 3, 1, 2, 1, 1, 1, 1, 1]) treemap.add('F', [31]) treemap.add('G', [5, 9.3, 8.1, 12, 4, 3, 2]) treemap.add('H', [12, 3, 3]) graph_data = treemap.render_data_uri() msg = " Treemap" elif graph_style == "Gauge": gauge_chart = pygal.Gauge(human_readable=True, fill=True, interpolate='cubic', style=DarkColorizedStyle) gauge_chart.title = 'DeltaBlue V8 benchmark results' gauge_chart.range = [0, 10000] gauge_chart.add('Chrome', 8212) gauge_chart.add('Firefox', 8099) gauge_chart.add('Opera', 2933) gauge_chart.add('IE', 41) graph_data = gauge_chart.render_data_uri() msg = "Gauge" elif graph_style == "SolidGauge": gauge = pygal.SolidGauge(inner_radius=0.70, fill=True, interpolate='cubic', style=DarkColorizedStyle) percent_formatter = lambda x: '{:.10g}%'.format(x) dollar_formatter = lambda x: '{:.10g}$'.format(x) gauge.value_formatter = percent_formatter gauge.add('Series 1', [{ 'value': 225000, 'max_value': 1275000 }], formatter=dollar_formatter) gauge.add('Series 2', [{'value': 110, 'max_value': 100}]) gauge.add('Series 3', [{'value': 50}]) gauge.add('Series 4', [{ 'value': 51, 'max_value': 100 }, { 'value': 12, 'max_value': 100 }]) gauge.add('Series 5', [{'value': 79, 'max_value': 100}]) gauge.add('Series 6', 99) gauge.add('Series 7', [{'value': 100, 'max_value': 100}]) graph_data = gauge.render_data_uri() msg = "SolidGauge" elif graph_style == "XY": xy_chart = pygal.XY(fill=True, interpolate='cubic', style=DarkColorizedStyle) xy_chart.title = 'XY Cosinus' xy_chart.add('x = cos(y)', [(cos(x / 10.), x / 10.) for x in range(-50, 50, 5)]) xy_chart.add('y = cos(x)', [(x / 10., cos(x / 10.)) for x in range(-50, 50, 5)]) xy_chart.add('x = 1', [(1, -5), (1, 5)]) xy_chart.add('x = -1', [(-1, -5), (-1, 5)]) xy_chart.add('y = 1', [(-5, 1), (5, 1)]) xy_chart.add('y = -1', [(-5, -1), (5, -1)]) graph_data = xy_chart.render_data_uri() msg = "XY" elif graph_style == "Multi-series pie": pie_chart = pygal.Pie(fill=True, interpolate='cubic', style=DarkColorizedStyle) pie_chart.title = 'Browser usage by version in February 2012 (in %)' pie_chart.add('IE', [5.7, 10.2, 2.6, 1]) pie_chart.add('Firefox', [.6, 16.8, 7.4, 2.2, 1.2, 1, 1, 1.1, 4.3, 1]) pie_chart.add('Chrome', [.3, .9, 17.1, 15.3, .6, .5, 1.6]) pie_chart.add('Safari', [4.4, .1]) pie_chart.add('Opera', [.1, 1.6, .1, .5]) graph_data = pie_chart.render_data_uri() msg = "Multi-series pie" except Exception as e: msg = e t = (msg, graph_data) return t
def piechart(): conn = psycopg2.connect("dbname='sales_demo' user='******' host='localhost' password='******' ") ratios = [('Gentlemen', 5), ('Ladies',9)] # ratios[0][0] # ratios1 = [{},{}] pie_chart = pygal.Pie() pie_chart.title = 'Browser usage in February 2012 (in %)' pie_chart.add(ratios[0][0], ratios[0][1]) pie_chart.add(ratios[1][0], ratios[1][1]) # pie_chart.add('Chrome', 36.3) # pie_chart.add('Safari', 4.5) # pie_chart.add('Opera', 2.3) pie_data = pie_chart.render_data_uri() data = [ {'month': 'January', 'total': 22}, {'month': 'February', 'total': 27}, {'month': 'March', 'total': 23}, {'month': 'April', 'total': 20}, {'month': 'May', 'total': 12}, {'month': 'June', 'total': 32}, {'month': 'July', 'total': 42}, {'month': 'August', 'total': 72}, {'month': 'September', 'total': 52}, {'month': 'October', 'total': 42}, {'month': 'November', 'total': 92}, {'month': 'December', 'total': 102} ] cur = conn.cursor() # cur.execute("""SELECT (sum(i.selling_price * s.quatity)) as subtotal, EXTRACT(MONTH FROM s.created_at) 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(type(rows)) months = [] total_sales = [] for each in rows: months.append(each[1]) total_sales.append(each[0]) # # print(months) # print(total_sales) graph = pygal.Line() graph.title = '% Change Coolness of programming languages over time.' graph.x_labels = months graph.add('Total Sales', total_sales) # graph.add('Java', [15, 45, 76, 80, 91, 95]) # graph.add('C++', [5, 51, 54, 102, 150, 201]) # graph.add('All others combined!', [5, 15, 21, 55, 92, 105]) graph_data = graph.render_data_uri() # return render_template("graphing.html", graph_data=graph_data) return render_template('index.html', pie_data=pie_data, graph_data=graph_data)
def home(): # print ("__xlabels__",var_x_labels) #####################################Active session chart ##### custom_style = Style(colors=('#351508', '#404040', '#9BC850')) title = 'STB Uptime' bar_chart = pygal.Bar(width=400, height=400, explicit_size=True, title=title, x_label_rotation=90, style=custom_style) var_x_labels = [] var_data = [] for idx1 in list(range(0, len(data_time_spent))): var_end_time = datetime.utcfromtimestamp( int(data_time_spent.Date_Time[idx1])).strftime('%Y-%m-%d %H:%M:%S') var_x_labels.append(var_end_time) var_data.append(data_time_spent.Time_spent[idx1]) # print(data_time_spent.Time[idx1]) bar_chart.x_labels = var_x_labels var_time_spent = var_data bar_chart.add('Active session time', var_time_spent) bar_chart.render_to_file('static/images/bar_chart.svg') #####################################Active session line chart ##### line_chart = pygal.Line() line_chart.title = 'Time series' # line_chart.x_labels = map( # date.isoformat, # rrule(DAILY, dtstart=date(2010, 8, 1), until=date.today()) # ) # line_chart.y_labels = map(str,range(1,25)) var_date_series = [] var_start_time_series = [] var_end_time_series = [] var_time_series_plot = [] for idx1 in list(range(0, len(data_time_spent))): tmp_start_time = data_time_spent.Date_Time[ idx1] - data_time_spent.Time_spent[idx1] var_date_series.append( datetime.utcfromtimestamp( int(tmp_start_time)).strftime('%Y-%m-%d')) var_start_time_series.append( datetime.utcfromtimestamp( int(tmp_start_time)).strftime('%H:%M:%S')) var_end_time_series.append( datetime.utcfromtimestamp(int( data_time_spent.Date_Time[idx1])).strftime('%H:%M:%S')) line_chart.x_labels = var_date_series line_chart.x_labels = map(str, range(2002, 2013)) print("##########var date series####", var_date_series) print("##########var start time series####", var_start_time_series) print("##########var end time series####", var_end_time_series) line_chart.add("start Time", [12, 34, 10, 5, 7]) line_chart.add("End Time", [22, 12, 13, 16, 5]) line_chart.render_to_file('static/images/line_chart.svg') ################################### Avg time spent chart ####### title2 = 'Avg time spent on each screen' custom_style = Style(colors=('#059467', '#9BC850', '#E80080')) avg_bar_chart = pygal.Bar(width=1200, height=800, explicit_size=True, title=title2, x_label_rotation=70, style=custom_style) var_x_labels = [] var_data = [] # print ("__xlabels__",var_x_labels) # print ("avg time spent===",avg_time_spent) for idx1 in list(range(0, len(avg_time_spent))): var_x_labels.append(avg_time_spent.Screen_id[idx1]) var_data.append(avg_time_spent.Avg_Time[idx1]) # print(avg_time_spent.Avg_Time[idx1]) avg_bar_chart.x_labels = var_x_labels # bar_chart.y_labels = var_y_labels # var_time_spent = [data_time_spent[x] for x in data_time_spent] # print ("_Time spent_",var_time_spent) # print ("_Time spent_0___",var_time_spent[0]) # print ("_Time spent_1___",var_time_spent[1]) var_time_spent = var_data avg_bar_chart.add('Avg time sec', var_data) avg_bar_chart.render_to_file('static/images/screen_avg_chart.svg') ################################### title2 = 'Least used screens' custom_style = Style(colors=('#1878f7', '#404040', '#E80080')) avg_bar_chart = pygal.Bar(width=1200, height=600, explicit_size=True, title=title2, x_label_rotation=90, style=custom_style) var_x_labels = [] var_data = [] # print ("__xlabels__",var_x_labels) for idx1 in list(range(0, len(data_tf_idf))): var_x_labels.append(data_tf_idf.GUI[idx1]) var_data.append(data_tf_idf.Priority[idx1]) # print(avg_time_spent.Avg_Time[idx1]) avg_bar_chart.x_labels = var_x_labels # bar_chart.y_labels = var_y_labels # var_time_spent = [data_tf_idf[x] for x in data_tf_idf] # print ("_Time spent_",var_time_spent) # print ("_Time spent_0___",var_time_spent[0]) # print ("_Time spent_1___",var_time_spent[1]) var_time_spent = var_data avg_bar_chart.add('Least used screen', var_time_spent) avg_bar_chart.render_to_file('static/images/tf_idf_chart.svg') #====================Donut chart of the screens used================== pie_chart = pygal.Pie(width=1200, height=600, explicit_size=True, inner_radius=.2) pie_chart.title = 'Time spent on each screen (in %)' var_x_labels = [] var_data = [] total_values = 0 for idx1 in list(range(0, len(avg_time_spent))): total_values = total_values + avg_time_spent.Avg_Time[idx1] # print ("Total value===",total_values) for idx1 in list(range(0, len(avg_time_spent))): prcnt = round((avg_time_spent.Avg_Time[idx1] / total_values) * 100, 2) # print ("% = ",prcnt) pie_chart.add(avg_time_spent.Screen_id[idx1], prcnt) pie_chart.render_to_file('static/images/donut.svg') #==================================Gauge chart========== gauge = pygal.SolidGauge(inner_radius=0.70) percent_formatter = lambda x: '{:.10g}%'.format(x) gauge.value_formatter = percent_formatter #====Screen Pattern Table Info===================================== for idx in list(range(0, len(avg_time_spent))): # print (idx,"=>",avg_time_spent.Screen_id[idx]) for idx2 in list(range(0, len(var_full_data))): if (avg_time_spent.Screen_id[idx] == var_full_data.ScreenName[idx2] ): # print (idx2,"count=",var_full_data.ScreenName[idx2]) if (idx2 + 1 >= len(var_full_data)): continue else: var_screen_id_dict[avg_time_spent.Screen_id[idx]].append( var_full_data.ScreenName[idx2 + 1]) # print("screneid =",avg_time_spent.Screen_id[idx],"next id=",var_full_data.ScreenName[idx2+1]) # print("The next screen list stored==========") # print (var_screen_id_dict) #====scatter plot===================================== # xy_chart = pygal.XY(width=1200,height=600,explicit_size=True,stroke=False) # xy_chart.title = 'Scatter plot of the screen ID and time spent' # xy_chart.add('2', [(.1, .15), (.12, .23), (.4, .3), (.6, .4), (.21, .21), (.5, .3), (.6, .8), (.7, .8)]) # xy_chart.add('3', [(.05, .01), (.13, .02), (1.5, 1.7), (1.52, 1.6), (1.8, 1.63), (1.5, 1.82), (1.7, 1.23), (2.1, 2.23), (2.3, 1.98)]) # xy_chart.render_to_file('static/images/scatter.svg') #====================================== my_html = create_html_page() return my_html
# -*- coding: utf-8 -*- import pygal param_line_chart = pygal.Line(fill=True, label_font_size=20) param_line_chart.title = 'Parameter Line Chart' param_line_chart.x_labels = map(str, [ "Data Object 1", "Data Object 2", "Data Object 3", "Data Object 4", "Data Object 5", "Data Object 6" ]) param_line_chart.add('Data-Set 1', [8, 16, 24, 32, 48, 56]) param_line_chart.add('Data-Set 2', [2, 4, 6, 8, 10, 12]) param_line_chart.add('Data-Set 3', [1, 3, 5, 7, 9, 12]) param_line_chart.render_to_file('lineparam.svg')
def scatter(): with open('bitcoin_prices.json', 'r') as data_file: bitcoin_data = json.load(data_file) with open('ethereum_prices.json', 'r') as data_file: ethereum_data = json.load(data_file) with open('litecoin_prices.json', 'r') as data_file: litecoin_data = json.load(data_file) with open('monero_prices.json', 'r') as data_file: monero_data = json.load(data_file) with open('dash_prices.json', 'r') as data_file: dash_data = json.load(data_file) with open('iota_prices.json', 'r') as data_file: iota_data = json.load(data_file) with open('nem_prices.json', 'r') as data_file: nem_data = json.load(data_file) with open('omisego_prices.json', 'r') as data_file: omisego_data = json.load(data_file) with open('qtum_prices.json', 'r') as data_file: qtum_data = json.load(data_file) with open('stratis_prices.json', 'r') as data_file: stratis_data = json.load(data_file) with open('waves_prices.json', 'r') as data_file: waves_data = json.load(data_file) custom_style = Style(colors=('#E853A0', '#E8537A', '#E95355', '#E87653', '#E89B53'), background='#000000', plot_background='#1a1a1a', foreground='#ffffff', foreground_subtle='#ffffff', foreground_strong='#ffffff', legend_font_size=10, font_family='googlefont:Raleway', major_label_font_size=7, label_font_size=8) chart = pygal.Line(width=600, height=300, style=custom_style, dots_size=0.2, label_font_size=6, x_title='Time', y_title='Price', y_labels_major_every=None, x_label_rotation=20, show_minor_x_labels=False, stroke=False) chart.title = 'Comparison of lesser known coins' bitcoin_list = [] for x in bitcoin_data: temp = {'value': x['Open'] / 100, 'label': x['Date']} bitcoin_list.append(temp) bitcoin_list.reverse() chart.add('Bitcoin/100', bitcoin_list) nem_list = [x['Open'] for x in nem_data] # nem_list = [] # for x in nem_data: # temp = { # 'value': x['Open'], # 'label': x['Date'] # } nem_list.reverse() chart.add('Nem', nem_list) stratis_list = [x['Open'] for x in stratis_data] # stratis_list = [] # for x in stratis_data: # temp = { # 'value': x['Open'], # 'label': x['Date'] # } stratis_list.reverse() chart.add('Stratis', stratis_list) waves_list = [x['Open'] for x in waves_data] # waves_list = [] # for x in waves_data: # temp = { # 'value': x['Open'], # 'label': x['Date'] # } waves_list.reverse() chart.add('Waves', waves_list) iota_list = [x['Open'] for x in iota_data] # iota_list = [] # for x in iota_data: # temp = { # 'value': x['Open'], # 'label': x['Date'] # } iota_list.reverse() chart.add('Iota', iota_list) label_list = [] for x in nem_data: temp = {'value': x['Open'], 'label': x['Date']} label_list.append(temp) label_list.reverse() chart.x_labels = [x['label'] for x in label_list] chart.render_to_file('static/images/scatter_chart.svg') img_url = 'static/images/scatter_chart.svg?cache=' + str(time.time()) return render_template('template.html', image_url=img_url)
import pygal chart = pygal.Line() chart.add('line', [.0002, .0005, .00035], show_dots=False) chart.add('line', [.0004, .0009, .001]) print(chart.render(is_unicode=True))
def data_visualization(): ''' Add components to your pie chart 1. add title 2. Partition your pie chart ''' cur.execute(""" SELECT type, count(type) FROM public.inventories GROUP BY type; """) product_service = cur.fetchall() # print(product_service) # Initialize your pie chart pie_chart = pygal.Pie() # my_pie_data = [ # ('Nairobi', 63), # ('Mombasa', 20), # ('Kilifi', 17), # ('Machakos', 30), # ('Kiambu', 7) # ] pie_chart.title = 'Ratio of product and service' for each in product_service: pie_chart.add(each[0], each[1]) # pie_chart.add('Nairobi', 63) # pie_chart.add('Mombasa', 20) # pie_chart.add('Kilifi', 17) # pie_chart.add('Machakos', 30) # pie_chart.add('Kiambu', 7) pie_data = pie_chart.render_data_uri() # end of piechart # start of line graph # represennts sales made in every month cur.execute(""" SELECT EXTRACT(MONTH FROM s.created_at) as sales_month, sum(quantity * selling_price) as total_sales from sales as s join inventories as i on s.inv_id = i.id GROUP BY sales_month ORDER BY sales_month """) monthly_sales=cur.fetchall() # print(monthly_sales) data = [ {'month': 'January', 'total': 22}, {'month': 'February', 'total': 27}, {'month': 'March', 'total': 23}, {'month': 'April', 'total': 20}, {'month': 'May', 'total': 12}, {'month': 'June', 'total': 32}, {'month': 'July', 'total': 42}, {'month': 'August', 'total': 72}, {'month': 'September', 'total': 52}, {'month': 'October', 'total': 42}, {'month': 'November', 'total': 92}, {'month': 'December', 'total': 102} ] x = [] sales = [] for each in monthly_sales: x.append(each[0]) sales.append(each[1]) # print(x) # print(sales) line_graph = pygal.Line() line_graph.title = 'Total sales made in every month in the year 2019' line_graph.x_labels = map(str, x) # line_graph.add('Firefox', [None, None, 0, 16.6, 25, 31, 36.4, 45.5, 46.3, 42.8, 37.1, 42.8]) # line_graph.add('Chrome', [None, None, None, None, None, None, 0, 3.9, 10.8, 23.8, 35.3, 23.8]) # line_graph.add('IE', [85.8, 84.6, 84.7, 74.5, 66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1, 26.6]) # line_graph.add('Others', [14.2, 15.4, 15.3, 8.9, 9, 10.4, 8.9, 5.8, 6.7, 6.8, 7.5, 26.6]) line_graph.add('Total Sales', sales) line_data = line_graph.render_data_uri() ''' x = "tech" y = x y = x = 'tech' ''' return render_template('charts.html', pie=pie_data, line=line_data)