def get_context_data(self, **kwargs): context_data = super(SessionChart, self).get_context_data(**kwargs) if not self.client: return context_data data = [('Date', 'Sessions Created')] date_dict = defaultdict(int) for row in models.RequestEvent.objects.values('tracking_key').annotate( new_date=Min('created')).filter( new_date__range=[self.start_date, self.end_date], client=self.client): date_dict[row['new_date'].strftime('%Y-%m-%d')] += 1 d = self.start_date while d <= self.end_date: data.append( (d.strftime('%Y-%m-%d'), date_dict[d.strftime('%Y-%m-%d')])) d += timedelta(days=1) chart = gchart.LineChart(SimpleDataSource(data=data), height=500, width=570, options={ 'title': 'Sessions Created', 'legend': 'none', }) context_data.update({'chart': chart}) return context_data
def monthly(request): queryset = Humidity.objects.filter(reading_time__month=month) data_source = ModelDataSource(queryset, fields=['reading_time', 'Humidity_Percent']) humidity_monthly_line_chart = gchart.LineChart(data_source, options={'title': "Monthly Readings"}) return render(request, 'humidity/monthly.html', {'humidity_monthly_line_chart': humidity_monthly_line_chart})
def get_chart(data, type): data_source = [] data_source.append(['Date', type]) if (len(data) == 0): data_source.append(['No Data', 0]) for k, v in data.items(): # date_="" # date_=datetime.datetime.strptime(data.index.values[i].astype(str),'%Y-%m-%dT00:00:00.000000000') # date_=datetime.datetime.strftime(date_,'%d %b %Y') data_source.append([k, v]) options1 = { 'title': type, 'series': [{ 'color': '#000080' }], } # <script type="text/javascript" src="https://www.google.com/jsapi"></script> # <script type="text/javascript"> # google.load("visualization", "1", {packages:["corechart"]}); # </script> {{ products_chart.as_html }} chart_name = gchart.LineChart(SimpleDataSource(data=data_source), options=options1, html_id=type, width="100%") return chart_name
def monthly(request): queryset = Temperature.objects.filter(reading_time__month=month) data_source = ModelDataSource(queryset, fields=['reading_time', 'Temp_F']) temp_monthly_line_chart = gchart.LineChart(data_source, options={'title': "Monthly Redings"}) return render(request, 'tempsensor/monthly.html', {'temp_monthly_line_chart': temp_monthly_line_chart})
def get_context_data(self): create_demo_accounts() Account.objects.create(week="10", count=2130, area=1940, farmer="Cook") queryset = Account.objects.all() data_source = ModelDataSource(queryset, fields=['week', 'count']) line_chart = gchart.LineChart(data_source) context = {"chart": line_chart} return context
def home(request): chart = flot.LineChart(SimpleDataSource(data=data), html_id="line_chart") g_chart = gchart.LineChart(SimpleDataSource(data=data)) cursor = get_mongo_cursor("graphos_mongo", "zips", max_docs=100) m_data = MongoDBDataSource(cursor=cursor, fields=['_id', 'pop']) m_chart = flot.LineChart(m_data) context = {'chart': chart, 'g_chart': g_chart, 'm_chart': m_chart} return render(request, 'demo/home.html', context)
def get_context_data(self): create_demo_accounts() Account.objects.create(year="2010", sales=2130, expenses=1940, ceo="Cook") queryset = Account.objects.all() data_source = ModelDataSource(queryset, fields=['year', 'sales']) line_chart = gchart.LineChart(data_source) context = {"chart": line_chart} return context
def temp_daily_line(self): queryset = Temperature.objects.filter(reading_time__date=now) data_source = ModelDataSource(queryset, fields=['reading_time', 'Temp_F']) temp_daily_line_chart = gchart.LineChart(data_source, options={ 'title': "Daily Readings", 'vAxis': { 'minValue': 60, 'maxValue': 80 } }) return temp_daily_line_chart
def get(request): context = dict() showResult = False if len(request.GET) == 3: ngram_query = request.GET['ngram_query'] start = request.GET['start'] end = request.GET['end'] showResult = True result, data = processResult(ngram_query, start, end) g_chart = gchart.LineChart(SimpleDataSource(data=data), options={'title': 'Ngram Viewer'}) context = {'ngram_query': ngram_query, 'start': start, 'end': end, 'result': result} context['g_chart'] = g_chart context['showResult'] = showResult return render(request, 'index.html', context)
def humidity_monthly_line(self): queryset = Humidity.objects.filter(reading_time__month=month) data_source = ModelDataSource( queryset, fields=['reading_time', 'Humidity_Percent']) humidity_monthly_line_chart = gchart.LineChart(data_source, options={ "title": "Monthly Reading", 'vAxis': { 'minValue': 70, 'maxValue': 100 } }) return humidity_monthly_line_chart
def time_series_demo(request): create_demo_mongo() db = get_db('charts') query = get_query('year_ago', None, 'employee=/example/employee/500ff1b8e147f74f7000000c/') coll_name = "mapreduce_daily__sumof__time_record__hours" cursor = db[coll_name].find(query) data_source_2 = DemoMongoDBDataSource(cursor, fields=["_id", "value"]) chart_2 = flot.LineChart(data_source_2) accounts_cursor = get_db("accounts").docs.find() data_source_3 = MongoDBDataSource(accounts_cursor, fields=['Year', 'Sales', 'Expenses']) chart_3 = gchart.LineChart(data_source_3) data_source_4 = MongoDBDataSource(accounts_cursor, fields=['Year', 'Sales']) chart_4 = CustomFlot2(data_source_4) period = 'weekly' start = 'year_ago' end = None series = [{ 'resource': 'time_record', 'field': 'hours', 'filter': 'employee=/example/employee/500ff1b8e147f74f7000000c/', 'mapreduce_function': 'sumof' }, { 'resource': 'other_time_record', 'field': 'hours', 'filter': 'employee=/example/employee/500ff1b8e147f74f7000000c/', 'mapreduce_function': 'sumof' }] datasets = build_timeseries_chart(period=period, series=series, start=start, end=end) context = { 'datasets': json.dumps(datasets), 'chart_2': chart_2, "chart_3": chart_3, "chart_4": chart_4, } return render(request, 'demo/mongodb_source.html', context)
def temp_monthly_line(self): queryset = Temperature.objects.filter(reading_time__month=month) data_source = ModelDataSource(queryset, fields=['reading_time', 'Temp_F']) temp_monthly_line_chart = gchart.LineChart(data_source, options={ "title": "Monthly Reading", 'vAxis': { 'minValue': 60, 'maxValue': 80, 'viewWindowMode': 'maximized' } }) return temp_monthly_line_chart
def gchart_demo(request): create_demo_accounts() queryset = Account.objects.all() data_source = ModelDataSource(queryset, fields=['year', 'sales']) line_chart = gchart.LineChart(data_source, options={'title': "Sales Growth"}) column_chart = gchart.ColumnChart(SimpleDataSource(data=data), options={'title': "Sales vs Expense"}) bar_chart = gchart.BarChart(data_source, options={'title': "Expense Growth"}) candlestick_chart = gchart.CandlestickChart( SimpleDataSource(data=candlestick_data)) pie_chart = gchart.PieChart(data_source) custom_chart = CustomGchart(data_source) context = { "line_chart": line_chart, "column_chart": column_chart, 'bar_chart': bar_chart, 'candlestick_chart': candlestick_chart, 'pie_chart': pie_chart, "custom_chart": custom_chart } return render(request, 'demo/gchart.html', context)
def charts(request): form_class = ChartForm() lockerId = request.POST.get('locker_id') lockerType = request.POST.get('prime_or_standard') if lockerType.lower() == "prime": locker_type = "Prime" locker = Orders.objects.filter(Q(locker_id=lockerId), Q(order_type=1)).distinct() else: locker_type = "Standard" locker = Orders.objects.filter(Q(locker_id=lockerId), Q(order_type=2)).distinct() data_source = ModelDataSource(locker, fields=['order_date', 'locker_used']) chart = gchart.LineChart(data_source, html_id='gchart_div', options={'title': 'Locker Booking Trends'}) context = { 'chart': chart, 'len': len(locker), 'locker_id': lockerId, 'type': locker_type } return render(request, 'charts.html', context)
def get_context_data(self, **kwargs): context_data = super(UserChart, self).get_context_data(**kwargs) if not self.client: return context_data data = [ ('Date', 'Users Created') ] date_dict = defaultdict(int) for row in models.RequestEvent.objects.values( 'tracking_user_id' ).annotate(new_date=Min('created')).filter( new_date__range=[self.start_date, self.end_date], client=self.client ): date_dict[row['new_date'].strftime('%Y-%m-%d')] += 1 d = self.start_date while d <= self.end_date: data.append( (d.strftime('%Y-%m-%d'), date_dict[d.strftime('%Y-%m-%d')]) ) d += timedelta(days=1) chart = gchart.LineChart(SimpleDataSource(data=data)) context_data.update( { 'chart': chart, } ) return context_data
def home(request): template = 'aqp/home.html' form1 = Form1(request.GET or None) form2 = Form2(request.GET or None) #template = 'template.html' filterdata = Data.objects.all() '''for i in products: print((Data.RPD_deaths)[1])''' featured_filter1 = 2001 featured_filter2 = 2015 if request.GET.get('featured'): featured_filter1 = request.GET.get('From') featured_filter2 = request.GET.get('To') #print("dsds",Data.RPD_deaths) filterdata = Data.objects.filter( Year__range=[featured_filter1, featured_filter2]) else: filterdata = Data.objects.all() #print(products) data = [[ 'Year', 'Four_wheelers', 'Two_wheelers', 'Auto_rickshaw', 'Buses', 'Taxis', 'e.Good_vehicles', 'Total_vehicles' ]] for e in filterdata: data.append([ str(e.Year), e.Four_wheelers, e.Two_wheelers, e.Auto_rickshaw, e.Buses, e.Taxis, e.Good_vehicles, e.Total_vehicles ]) # DataSource object data_source = SimpleDataSource(data=data) chart = gchart.LineChart(data_source) data_deaths = [['Year', "RPD_deaths", "Total_deaths"]] for e in filterdata: data_deaths.append([str(e.Year), e.RPD_deaths, e.Total_deaths]) # DataSource object data_source2 = SimpleDataSource(data=data_deaths) chart2 = highcharts.DonutChart( data_source2, height=450, width=1200, options={'title': "Deaths caused by Air Pollution"}) #chart3 = gchart.AreaChart(data_source2,height=400, width=1100,options={'title':"Deaths caused by Air Pollution"}) fw, tw, ar, bs, tx, gv = "None", "None", "None", "None", "None", "None" fws, tws, ars, bss, txs, gvs = "None", "None", "None", "None", "None", "None" if featured_filter1 <= featured_filter2: ob1 = filterdata[0] ob2 = filterdata[len(filterdata) - 1] #print(ob1,ob2) fw = ob2.Four_wheelers - ob1.Four_wheelers tw = ob2.Two_wheelers - ob1.Two_wheelers ar = ob2.Auto_rickshaw - ob1.Auto_rickshaw bs = ob2.Buses - ob1.Buses tx = ob2.Taxis - ob1.Taxis gv = ob2.Good_vehicles - ob1.Good_vehicles fws, tws, ars, bss, txs, gvs = 0, 0, 0, 0, 0, 0 if fws < 0: fws = 1 if tw < 0: tws = 1 if ar < 0: ars = 1 if bs < 0: bss = 1 if tx < 0: txs = 1 if gv < 0: gvs = 1 fw = "{:,}".format(fw) tw = "{:,}".format(tw) ar = "{:,}".format(ar) bs = "{:,}".format(bs) tx = "{:,}".format(tx) gv = "{:,}".format(gv) return render( request, "aqp/home.html", { "form1": form1, "form2": form2, "filterdata": filterdata, "chart": chart, "chart2": chart2, "data": data, "fws": fws, "tws": tws, "ars": ars, "bss": bss, "txs": txs, "gvs": gvs, "fw": fw, "gv": gv, "tw": tw, "ar": ar, "bs": bs, "tx": tx })
def index(request): # Used later to keep track of the maximum JSS lastResets = [] no_seum_delta = timedelta.max # First select our counter try: myCounter = Counter.objects.get(user__id=request.user.id) myLastReset = Reset.objects.select_related('who').filter( counter=myCounter).order_by('-timestamp').first() if myLastReset is None: # This person never had the seum myCounter.lastReset = Reset() myCounter.lastReset.delta = no_seum_delta myCounter.lastReset.formatted_delta = format_timedelta( myCounter.lastReset.delta, locale=get_language(), threshold=1) myCounter.lastReset.noSeum = True else: myCounter.lastReset = myLastReset myCounter.lastReset.noSeum = False if myCounter.lastReset.who is None or myCounter.lastReset.who.id == myCounter.id: myCounter.lastReset.selfSeum = True else: myCounter.lastReset.selfSeum = False likesMe = list( Like.objects.select_related('liker').filter( reset=myCounter.lastReset)) myCounter.likeCount = len(likesMe) if myCounter.likeCount > 0: myCounter.likersString = ", ".join( [like.liker.trigramme for like in likesMe]) myCounter.lastReset.formatted_delta = arrow.Arrow.fromdatetime( myCounter.lastReset.timestamp).humanize(locale=get_language()) except Counter.DoesNotExist: return HttpResponseRedirect(reverse('login')) # Building data for counters display counters = Counter.objects.prefetch_related( 'resets__likes', Prefetch('resets', queryset=Reset.objects.prefetch_related( 'who', Prefetch('likes', queryset=Like.objects.select_related( 'liker'))).order_by('-timestamp'), to_attr='lastReset')) for counter in counters: # Only the last reset is displayed lastReset = list(counter.lastReset) if len(lastReset) == 0: # This person never had the seum counter.lastReset = Reset() counter.lastReset.delta = no_seum_delta counter.lastReset.formatted_delta = format_timedelta( counter.lastReset.delta, locale=get_language(), threshold=1) counter.lastReset.noSeum = True counter.lastReset.likes_count = -1 counter.CSSclass = "warning" else: # This person already had the seum counter.lastReset = lastReset[0] # To display the last seum we have to know if it is self-inflicted if counter.lastReset.who is None or counter.lastReset.who == counter: counter.lastReset.selfSeum = True else: counter.lastReset.selfSeum = False # Now we compute the duration since the reset counter.lastReset.noSeum = False counter.lastReset.delta = datetime.now( ) - counter.lastReset.timestamp.replace(tzinfo=None) # Defining CSS attributes for the counter counter.CSSclass = 'primary' if counter == myCounter else 'default' # Computing the total number of likes for this counter likesMe = list(counter.lastReset.likes.all()) counter.lastReset.likes_count = len(likesMe) counter.alreadyLiked = myCounter.id in [ likeMe.liker.id for likeMe in likesMe ] if counter.lastReset.likes_count > 0: counter.likersString = ", ".join( [like.liker.trigramme for like in likesMe]) counter.lastReset.formatted_delta = arrow.Arrow.fromdatetime( counter.lastReset.timestamp).humanize(locale=get_language()) counter.likeCount = counter.lastReset.likes_count counter.isHidden = 'hidden' if myCounter.sort_by_score: # Now we sort the counters according to a reddit-like ranking formula # We take into account the number of likes of a reset and recentness # The log on the score will give increased value to the first likes # The counters with no seum have a like count of -1 by convention sorting_key = lambda t: -(math.log(t.lastReset.likes_count + 2) / (1 + (t.lastReset.delta.total_seconds()) / (24 * 3600))) counters = sorted(counters, key=sorting_key) else: counters = sorted(counters, key=lambda t: +t.lastReset.delta.total_seconds()) # ### GRAPHS ### resets_raw = list( Reset.objects.select_related( 'who', 'counter').annotate(likes_count=Count('likes'))) likes_raw = list( Like.objects.select_related('liker', 'reset__counter').all()) hashtags_raw = list(Hashtag.objects.select_related('keyword').all()) # Prepare pandas.DataFrames to efficiently process the data # About the counters resets_cols = [ 'date', 'counter', 'counter_trigram', 'who', 'who_trigram', 'reason', 'likes_count' ] resets_data = [[ r.timestamp, r.counter.id, r.counter.trigramme, r.who, r.who, r.reason, r.likes_count ] for r in resets_raw] for r in resets_data: r[3] = 0 if r[3] is None else r[3].id r[4] = '' if r[4] is None else r[4].trigramme resets_df = pd.DataFrame(resets_data, columns=resets_cols) resets_df['timestamp'] = resets_df.date.map(lambda d: d.timestamp()) resets_df['self_seum'] = (resets_df.who.eq(np.zeros(resets_df.shape[0])) | resets_df.who.eq(resets_df.counter)).map(float) resets_df['formatted_delta'] = resets_df.date.map( lambda d: arrow.Arrow.fromdatetime(d).humanize(locale=get_language())) # About the likes likes_cols = ['liker', 'liker_trigram', 'counter', 'counter_trigram'] likes_data = [[ l.liker.id, l.liker.trigramme, l.reset.counter.id, l.reset.counter.trigramme ] for l in likes_raw] likes_df = pd.DataFrame(likes_data, columns=likes_cols) # About the hashtags hashtags_cols = ['keyword'] hashtags_data = [[h.keyword.text] for h in hashtags_raw] hashtags_df = pd.DataFrame(hashtags_data, columns=hashtags_cols) # Timeline graph timeline_resets = resets_df[resets_df.date > ( datetime.now() - timedelta(days=1))].copy().reset_index() if timeline_resets.shape[0] == 0: noTimeline = True line_chart = None else: noTimeline = False # Construct legend for timeline dots legend_ = np.zeros(timeline_resets.shape[0], dtype=np.object) for i in range(timeline_resets.shape[0]): row = timeline_resets.iloc[i] if row['self_seum'] == 1: legend_[i] = _('%(counter)s: %(reason)s') % { 'counter': row['counter_trigram'], 'reason': row['reason'] } else: legend_[i] = _('%(who)s to %(counter)s: %(reason)s') % { 'who': row['who_trigram'], 'counter': row['counter_trigram'], 'reason': row['reason'] } timeline_resets['legend'] = legend_ # Generate graph resets_ = [['', _('Seum')]] for i in range(timeline_resets.shape[0]): r = timeline_resets.iloc[i] resets_.append([{ 'v': r.timestamp, 'f': r.formatted_delta }, { 'v': 0, 'f': r.legend }]) # resets_.append({ # 'timestamp': {'v': r.date.timestamp(), 'f': r.formatted_delta}, # 'Seum': {'v': 0, 'f': r.legend}, # }) line_data = SimpleDataSource(resets_) line_chart = gchart.LineChart( line_data, options={ 'lineWidth': 0, 'pointSize': 10, 'title': '', 'vAxis': { 'ticks': [] }, 'hAxis': { 'ticks': [{ 'v': (datetime.now() - timedelta(days=1)).timestamp(), 'f': _('24h ago') }, { 'v': datetime.now().timestamp(), 'f': _('Now') }] }, 'legend': 'none', 'height': 90 }) # Graph of greatest seumers seum_counts_df = resets_df[['counter_trigram', 'self_seum']].copy() seum_counts_df['seum_count'] = np.ones(seum_counts_df.shape[0], dtype=np.float32) seum_counts_df = seum_counts_df.groupby(['counter_trigram' ]).sum().reset_index() # TODO: Add the ratio self_seum / seum_count if (seum_counts_df.shape[0] == 0): noBestSeum = True best_chart = None else: noBestSeum = False seum_counts_data = seum_counts_df.sort_values(by='seum_count', ascending=False)[[ 'counter_trigram', 'seum_count' ]].values.tolist() seum_counts_data.insert(0, [_('Trigram'), _('Number of seums')]) best_data = SimpleDataSource(seum_counts_data[:bestSeumeursNumber]) best_chart = gchart.ColumnChart(best_data, options={ 'title': '', 'legend': 'none', 'vAxis': { 'title': _('Number of seums') }, 'hAxis': { 'title': _('Trigram') }, }) # Graph of seum activity resets_act = resets_df[resets_df.date > (timezone.now() - timedelta(days=365))][['date' ]].copy() resets_act['year'] = resets_df.date.map(lambda d: d.year) resets_act['month'] = resets_df.date.map(lambda d: d.month) resets_act = resets_act.drop(['date'], axis=1) resets_act['month_counts'] = np.ones(resets_act.shape[0], dtype=int) resets_act = resets_act.groupby(['year', 'month']).sum().reset_index() if resets_act.shape[0] == 0: noSeumActivity = True activity_chart = None else: noSeumActivity = False seumActivity = [[ arrow.Arrow(a[0], a[1], 1).format("MMM YYYY", locale=get_language()).capitalize(), a[2] ] for a in resets_act.values.tolist()] seumActivity.insert(0, [_('Month'), _('Number of seums')]) activity_data = SimpleDataSource(seumActivity) activity_chart = gchart.ColumnChart(activity_data, options={ 'title': '', 'legend': 'none', 'vAxis': { 'title': _('Number of seums') }, 'hAxis': { 'title': _('Month') }, }) # Graph of best likers best_likers_df = likes_df.drop(['liker', 'counter', 'counter_trigram'], axis=1) best_likers_df['count'] = np.ones(best_likers_df.shape[0], dtype=int) best_likers_df = best_likers_df.groupby(['liker_trigram' ]).sum().reset_index() if best_likers_df.shape[0] == 0: noBestLikers = True likers_chart = None else: noBestLikers = False likersCounts = best_likers_df.sort_values( by='count', ascending=False).values.tolist() likersCounts.insert(0, [_('Trigram'), _('Number of given likes')]) likers_data = SimpleDataSource(likersCounts[:bestSeumeursNumber]) likers_chart = gchart.ColumnChart(likers_data, options={ 'title': '', 'legend': 'none', 'vAxis': { 'title': _('Number of given likes') }, 'hAxis': { 'title': _('Trigram') }, }) # Graph of popular hashtags hashtags_df['count'] = np.ones(hashtags_df.shape[0], dtype=int) hashtags_df = hashtags_df.groupby(['keyword']).sum().reset_index() hashtags_df['keyword'] = hashtags_df.keyword.map(lambda x: '#' + x) if hashtags_df.shape[0] == 0: noBestHashtags = True hashtags_chart = None else: noBestHashtags = False hashtags_data = hashtags_df.sort_values( by='count', ascending=False).values.tolist() hashtags_data.insert( 0, [_('Hashtag'), _('Number of seums containing the hashtag')]) hashtags_data = SimpleDataSource(hashtags_data[:bestSeumeursNumber]) hashtags_chart = gchart.ColumnChart( hashtags_data, options={ 'title': '', 'legend': 'none', 'vAxis': { 'title': _('Number of seums containing the hashtag') }, 'hAxis': { 'title': _('Hashtag') }, }) # Graph of best likee best_likees_df = likes_df.drop(['counter', 'liker', 'liker_trigram'], axis=1) best_likees_df['count'] = np.ones(best_likees_df.shape[0], dtype=int) best_likees_df = best_likees_df.groupby(['counter_trigram' ]).sum().reset_index() if best_likees_df.shape[0] == 0: noBestLikees = True likees_chart = None else: noBestLikees = False likeesCounts = best_likees_df.sort_values( by='count', ascending=False).values.tolist() likeesCounts.insert(0, [_('Trigram'), _('Number of received likes')]) likees_data = SimpleDataSource(likeesCounts[:bestSeumeursNumber]) likees_chart = gchart.ColumnChart(likees_data, options={ 'title': '', 'legend': 'none', 'vAxis': { 'title': _('Number of received likes') }, 'hAxis': { 'title': _('Trigram') }, }) # At last we render the page return render( request, 'homeTemplate.html', { 'counters': counters, 'line_chart': line_chart, 'best_chart': best_chart, 'likers_chart': likers_chart, 'likees_chart': likees_chart, 'hashtags_chart': hashtags_chart, 'activity_chart': activity_chart, 'noTimeline': noTimeline, 'noBestSeum': noBestSeum, 'noBestLikers': noBestLikers, 'noBestLikees': noBestLikees, 'noBestHashtags': noBestHashtags, 'noSeumActivity': noSeumActivity, 'myCounter': myCounter, })
def home(request): chart = flot.LineChart(SimpleDataSource(data=data), html_id="line_chart") g_chart = gchart.LineChart(SimpleDataSource(data=data)) context = {'chart': chart, 'g_chart': g_chart} return render(request, 'demo/home.html', context)