def chart_default_options(_, title, code, doc, sidebar_items): """ Some default options explained ------------------------------- Even though the ``chart_options`` are not specified, Chartit automatically tries to guess the axis titles, chart titles etc. Points to note: - Notice how the axes are named, chart is named etc. by default. """ # start_code ds = DataPool( series=[{ 'options': { 'source': MonthlyWeatherByCity.objects.all() }, 'terms': [ 'month', 'houston_temp', 'boston_temp' ]}, { 'options': { 'source': MonthlyWeatherSeattle.objects.all() }, 'terms': [ {'month_seattle': 'month'}, 'seattle_temp' ]} ] ) cht = Chart( datasource=ds, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'month': [ 'boston_temp', 'houston_temp' ], 'month_seattle': ['seattle_temp'] } }] ) # end_code return render_to_response('chart_code.html', { 'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items})
def create_err_stat_pie(top_n): def err_map(item): return ERR_DICT.get(item, 'UNKNOWN') # Step 2: Create the Chart object ds = DataPool( series=[ { 'options': { 'source': FailedStat.objects.exclude(err_code__in=[ UNKNOWN, SUCCESS, STILL_RUNNING ]).values('err_code').annotate(err_count=Count('err_code')).order_by('-err_count')[:top_n], }, 'terms': [ 'err_code', 'err_count', ] }, ], ) cht = Chart( datasource=ds, series_options=[ { 'options': { 'type': 'pie', }, 'terms': { 'err_code': ['err_count'] } }, ], chart_options={ 'chart': { 'height': 600, }, 'title': { 'text': u'Agent安装错误码统计图 - %s' % datetime.datetime.now().strftime('%Y-%m-%d')}, 'xAxis': { 'title': { 'text': u'错误码' } }, 'yAxis': [ { 'title': { 'text': u'错误次数(次)' }, }, ], }, x_sortf_mapf_mts=(None, err_map, True) ) return cht
def avg_count(_, title, code, doc, sidebar_items): """ A Basic Line Chart using Avg() and Count() ------------------------------------------ This chart plots the average book rating in each genre together with the number of books in each genre. """ # start_code ds = DataPool( series=[{ 'options': { 'source': Book.objects.values('genre').annotate( Avg('rating'), Count('genre') ) }, 'terms': [ 'genre__name', 'rating__avg', 'genre__count' ] }] ) cht = Chart( datasource=ds, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'genre__name': [ 'rating__avg', 'genre__count' ] } }], chart_options={ 'title': { 'text': 'Book rating and count per Genre' }, 'xAxis': { 'title': { 'text': 'Genre' } } } ) # end_code return render_to_response('chart_code.html', { 'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items})
def scatter_plot(_, title, code, doc, sidebar_items): """ Scatter Plot ------------- The ``DailyWeather`` database has data by ``month``, ``day``, ``city`` and ``temperature``. In this example we plot a scatter plot of temperature of the city of Boston w.r.t month. Points to note: - Notice that the data is filtered naturally using ``filter`` method in django. """ # start_code ds = DataPool( series=[{ 'options': { 'source': DailyWeather.objects.filter(city="Boston") }, 'terms': [ 'month', 'temperature' ] }] ) cht = Chart( datasource=ds, series_options=[{ 'options': { 'type': 'scatter' }, 'terms': { 'month': ['temperature'] } }], chart_options={ 'title': { 'text': 'Boston weather scatter plot' }, 'xAxis': { 'title': { 'text': 'Month' } } } ) # end_code return render_to_response('chart_code.html', { 'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items})
def getExpense(request): def my_custom_sql(self): cursor = connection.cursor() cursor.execute( """SELECT SUM(cost) from Main_expense WHERE "option"='Expense' GROUP BY date_created""" ) result = cursor.fetchall() return result # Step 1: Create a DataPool with the data we want to retrieve. weatherdata = \ DataPool( series= [{'options': { 'source': Expense.objects.all().filter(option__exact='Expense')}, 'terms': [ {'expense': Sum('cost')}, {'date_expense': 'date_created'}, ]}, {'options': { 'source':Expense.objects.all().filter(option__exact='Income')}, 'terms': [ {'income': Sum('cost')}, {'date_income': 'date_created'}, ]} ]) # Step 2: Create the Chart object cht = Chart(datasource=weatherdata, series_options=[{ 'options': { 'type': 'column', 'stacking': False }, 'terms': { 'date_expense': [ 'expense', ], 'date_income': ['income'] } }], chart_options={ 'title': { 'text': 'Income Vs Expenditure' }, 'xAxis': { 'title': { 'text': 'Date Created' } } }) # Step 3: Send the chart object to the template. return render(request, 'Main/chart.html', {'cht': cht})
def avg_count(_, title, code, doc, sidebar_items): """ A Basic Line Chart using AVG and COUNT -------------------------------------- This chart plots the average book rating in each genre together with the number of books in each genre. NOTE that we use the SQL functions for average and count! """ # start_code ds = DataPool(series=[{ 'options': { 'source': Book.objects.raw("SELECT " " demoproject_book.id, " " demoproject_genre.name as genre_name, " " avg(rating) as rating_avg, " " count(genre_id) as genre_count " "FROM demoproject_book " "JOIN demoproject_genre ON " " genre_id == demoproject_genre.id " "GROUP BY genre_id ") }, 'terms': ['genre_name', 'rating_avg', 'genre_count'] }]) cht = Chart(datasource=ds, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'genre_name': ['rating_avg', 'genre_count'] } }], chart_options={ 'title': { 'text': 'Book rating and count per Genre' }, 'xAxis': { 'title': { 'text': 'Genre' } } }) # end_code return render_to_response( 'chart_code.html', { 'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items })
def basicline_with_datefield(_, title, code, doc, sidebar_items): """ A Basic Line Chart with DateField --------------------------------- This chart plots sales quantities per day from the first book store. Points to note: - ``sale_date`` is a DateField """ # start_code ds = DataPool(series=[{ 'options': { 'source': SalesHistory.objects.filter( bookstore=BookStore.objects.first())[:10] }, 'terms': [ 'sale_date', 'sale_qty', ] }]) cht = Chart(datasource=ds, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'sale_date': [ 'sale_qty', ] } }], chart_options={ 'title': { 'text': 'Sales QTY per day' }, 'xAxis': { 'title': { 'text': 'Sale date' } } }) # end_code return render_to_response( 'chart_code.html', { 'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items })
def model_property(request, title, code, doc, sidebar_items): """ A basic Chart using model property ---------------------------------- NOTE that ``region()`` is a model property defined as :: class City(models.Model): def region(self): return 'USA:%s' % self.city """ # start_code ds = DataPool(series=[{ 'options': { 'source': SalesHistory.objects.only('bookstore__city', 'sale_qty')[:10], }, 'terms': ['bookstore__city__region', 'sale_qty'] }]) cht = Chart(datasource=ds, series_options=[ { 'options': { 'type': 'column', 'stacking': False, 'stack': 0, }, 'terms': { 'bookstore__city__region': ['sale_qty'] } }, ], chart_options={ 'title': { 'text': 'Sales reports' }, 'xAxis': { 'title': { 'text': 'City' } } }) # end_code return render_to_response( 'chart_code.html', { 'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items })
def correlation_chart_view(request): """ User logged to sensor can see its data represented by charts """ terms = [] if request.method == 'POST': form = ChooseCorrelationForm(request.POST) if form.is_valid(): # get data from dropdown axis_x = form.data['axis-x'] terms.append(axis_x) # get data from checkboxes axis = request.POST.get("axis-checkbox", None) if axis in ["temperature"]: terms.append('temperature') if axis in ["humidity"]: terms.append('humidity') if axis in ["pm25"]: terms.append('pm25') if axis in ["pm10"]: terms.append('pm10') if axis in ["pressure"]: terms.append('pressure') if axis in ["wind_speed"]: terms.append('wind_speed') else: terms = ['temperature', 'pm25', 'pm10'] else: form = ChooseCorrelationForm() terms = ['temperature', 'pm25', 'pm10'] # some default values weather_data = DataPool(series=[{ 'options': { 'source': Entry.objects.all() }, 'terms': terms }]) correlation_chart = Chart( datasource=weather_data, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { terms[0]: terms[1:] } }], # category for axis x and multiple values for axis y chart_options={'title': { 'text': 'Weather Data' }}) return render(request, 'correlation_chart.html', { 'correlation_chart': correlation_chart, 'form': form })
def mainticker_chart(): delta = datetime.timedelta(hours=2) primero = datetime.datetime.utcnow() - delta presource = MainTickerValue.objects.filter(time__gt=primero, currency='USD') #MainTickerValue.objects.extra({'tiempo':"date(pub_date)"}).values('tiempo').annotate(count=Count('id')) #deltamin = datetime.timedelta(minutes=1) # def date_handler(obj): # return obj.isoformat() if hasattr(obj, 'isoformat') else obj # def date_handler(obj): # if hasattr(obj, 'isoformat'): # return obj.isoformat() # else: # raise TypeError("Unserializable object {} of type {}".format(obj,type(obj))) #print json.dumps(data, default=date_handler) #Step 1: Create a DataPool with the data we want to retrieve. mainticker_data = \ DataPool( series= [{'options': { 'source': presource}, 'terms': [ ('time', lambda d: time.mktime(d.timetuple())), 'value']} ]) #Step 2: Create the Chart object cht = Chart( datasource = mainticker_data, series_options = [{'options':{ 'type': 'line', 'stacking': False}, 'terms':{ 'time': [ 'value'] }}], chart_options = {'title': { 'text': 'Mainticker'}, 'xAxis': { 'title': { 'text': 'Time'}}}, x_sortf_mapf_mts=(None, lambda i: datetime.datetime.fromtimestamp(i).strftime("%H:%M"), False)) # return the chart object return cht
def earning(request): member = Member.objects.get(user_id=request.user.id) family_id = member.fam_id all_family_members = Member.objects.filter(fam_id=family_id) Earnings = Earning.objects.filter(Member_id__in=all_family_members) earning = DataPool( # what data is being retrieved and where it is being retrieved from series=[ { 'options': { 'source': Earnings }, 'terms': [{ 'wage': 'wage', 'year': 'year' }] }, ]) cht = Chart( datasource=earning, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'year': ['wage'] } }], chart_options={ 'title': { 'text': 'Family Income over the Past 10 Years' }, 'xAxis': { 'title': { 'text': 'Year' } }, 'yAxis': { 'title': { 'text': 'Wage' } }, 'legend': { 'enabled': True }, 'credits': { 'enabled': True } }, ) return render(request, 'earning.html', { 'chart_list': [cht], 'member': member })
def column_chart(request, title, code, doc, sidebar_items): """ Column Chart ------------------ Just a simple column chart of temperatures of Boston and Houston stacked on top of each other. Points to note: - Any of the `Highcharts series options <http://www.highcharts.com/ref/#series>`_ are valid options for the Chart ``series_options`` - ``options`` dict. In this case we set the ``stacking`` parameter to ``True`` to stack the columns on the top of each other. Note: This demo is to demonstrate the use of the API and not to teach you data analysis and data presentation skills. Not all charts plotted in this demo may make sense in real life applications. But they can still be useful in demonstrating the API. """ #start_code ds = DataPool( series= [{'options': { 'source': MonthlyWeatherByCity.objects.all()}, 'terms': [ 'month', 'houston_temp', 'boston_temp']} ]) cht = Chart( datasource = ds, series_options = [{'options':{ 'type': 'column', 'stacking': True}, 'terms':{ 'month': [ 'boston_temp', 'houston_temp'] }}], chart_options = {'title': { 'text': 'Weather Data of Boston and Houston'}, 'xAxis': { 'title': { 'text': 'Month number'}}}) #end_code return render_to_response('chart_code.html', {'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items})
def datetimefield_from_related_model(_, title, code, doc, sidebar_items): """ A Basic Line Chart with DateTimeField from related model -------------------------------------------------------- This chart plots sales quantities from the first book store based on when the book was published. """ # start_code ds = DataPool( series=[{ 'options': { 'source': SalesHistory.objects.filter( bookstore=BookStore.objects.first() )[:10] }, 'terms': [ 'book__published_at', 'sale_qty', ] }] ) cht = Chart( datasource=ds, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'book__published_at': [ 'sale_qty', ] } }], chart_options={ 'title': { 'text': 'Sales QTY vs. Book publish date' }, 'xAxis': { 'title': { 'text': 'Publish date' } } } ) # end_code return render_to_response('chart_code.html', { 'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items})
def get_context_data(self, **kwargs): ctx = super(PlanDetailView, self).get_context_data(**kwargs) chart_type = self.request.GET.get('chart_type', 'column') exercises = self.get_object().planexercise_set.all() if exercises.count() == 0: return ctx from django.db.models import Sum, F data_series = [] for plan_exercise in exercises: start_key = 'start_{}'.format(plan_exercise.pk) count_key = '{}'.format(plan_exercise.name) data_series.append({ 'options': { 'source': ExerciseRecord.objects.filter(exercise=plan_exercise) }, 'terms': [ {start_key: 'natural_date'}, {count_key: 'count'}, ] }) data_pool = DataPool(series=data_series) chart_terms = {} for series in data_series: # Super brittle! key = series['terms'][0].keys()[0] val = series['terms'][1].keys()[0] chart_terms.update({ key: [val]}) chart = Chart( datasource = data_pool, series_options = [ { 'options': { 'type': chart_type, 'stacking': True }, 'terms': chart_terms, } ], chart_options = { 'title': {'text': 'Patient progress over time'}, 'xAxis': {'title': {'text': 'Date'}, 'type': 'datetime'}, } ) ctx.update({'chart': chart}) return ctx
def index(request): MonthlyWeatherByCity.objects.all().delete() for x in range(20): MonthlyWeatherByCity.objects.create( month=x, boston_temp=random.randint(10, 30), houston_temp=random.randint(10, 30), new_york_temp=random.randint(10, 30), san_franciso_temp=random.randint(10, 30) ) # Step 1: Create a DataPool with the data we want to retrieve. weatherdata = \ DataPool( series= [{'options': { 'source': MonthlyWeatherByCity.objects.all()}, 'terms': [ 'month', 'san_franciso_temp', 'new_york_temp', 'houston_temp', 'boston_temp']} ]) # Step 2: Create the Chart object cht = Chart( datasource=weatherdata, series_options= [{'options': { 'type': 'column', 'stacking': False}, 'terms': { 'month': [ 'boston_temp', 'houston_temp', ] }}, {'options': { 'type': 'line', 'stacking': False}, 'terms': { 'month': [ 'new_york_temp', 'san_franciso_temp'] }}], chart_options= {'title': { 'text': u'支持中文吗'}, 'xAxis': { 'title': { 'text': 'Month number'}}}, x_sortf_mapf_mts=(None, err_trans, False) ) # Step 3: Send the chart object to the template. return render_to_response('index.html', {'weatherchart': cht, 'STATIC_URL': settings.STATIC_URL})
def weatherByCity(request): ds = DataPool(series=[{ 'options': { 'source': MonthlyWeatherByCity.objects.all() }, 'terms': ['month', 'boston_temp', 'houston_temp'] }]) def monthname(month_num): names = { 1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: "Dec" } return names[month_num] cht = Chart(datasource=ds, series_options=[{ 'options': { 'type': 'line' }, 'terms': { 'month': ['boston_temp'] } }, { 'options': { 'type': 'pie', 'center': [150, 100], 'size': '50%' }, 'terms': { 'month': ['houston_temp'] } }], chart_options={ 'title': { 'text': 'Weather Data of Boston (line) and Houston (pie)' } }, x_sortf_mapf_mts=[(None, monthname, False), (None, monthname, False)]) return render_to_response('weatherByCity.html', {'weatherByCity': cht})
def basicline(request, title, code, doc, sidebar_items): """ A Basic Line Chart ------------------ This is just a simple line chart with data from 2 different columns. Points to note: - ``terms`` is a list of all fields (both for x-axis and y-axis) to retrieve from the model. - Remember that for a Chart, the x and y terms in the ``series_options`` are written as ``x: [y, ...]`` pairs. - Any valid items in the `Highcharts options object <http://api.highcharts.com/highcharts>`_ are valid ``chart_options``. """ # start_code ds = DataPool(series=[{ 'options': { 'source': MonthlyWeatherByCity.objects.all() }, 'terms': ['month', 'houston_temp', 'boston_temp'] }]) cht = Chart(datasource=ds, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'month': ['boston_temp', 'houston_temp'] } }], chart_options={ 'title': { 'text': 'Weather Data of Boston and Houston' }, 'xAxis': { 'title': { 'text': 'Month number' } } }) # end_code return render_to_response( 'chart_code.html', { 'chart_list': cht, 'code': code, 'title': title, 'doc': doc, 'sidebar_items': sidebar_items })
def index(request): recent_probes = Probe.objects.all().filter(timestamp__gte=timezone.now() - timedelta(days=1)) ds = DataPool(series=[{ 'options': { 'source': recent_probes }, 'terms': [ 'timestamp', 'temperature', ] }]) cht = Chart( datasource=ds, series_options=[{ 'options': { 'type': 'line', 'stacking': False, }, 'terms': { 'timestamp': [ 'temperature', ] } }], chart_options={ 'title': { 'text': 'Temperature chart' }, 'xAxis': { 'title': { 'text': 'Time' } }, # -*- coding: utf-8 -*- 'yAxis': { 'title': { 'text': 'Temperature (°C)' } } }, x_sortf_mapf_mts=(None, tz_oriented_date, False)) # -*- coding: utf-8 -*- last_probe = Probe.objects.order_by('-timestamp')[0] last_measured = "{}°C".format(last_probe.temperature) last_date = tz_oriented_date(last_probe.timestamp) return render(request, 'temperatures/index.html', { 'last_measured': last_measured, 'last_date': last_date, 'chart': cht })
def _create_statdata(chart_type, stats, terms=None, term_names=None): if chart_type == 'bar': statdata = DataPool( series=[{'options': { 'source': stats.filter(feature=term)}, 'legend_by': 'feature', 'terms': [{'time_%s' %term :'time'}, {term_names[term] : 'value', 'name': 'feature'}] } for term in terms] ) elif chart_type == 'pie': statdata = DataPool( series=[{'options': { 'source': stats }, 'legend_by': 'feature', 'terms': ['feature', 'value'], }] ) else: statdata = None return statdata
def generate_chart(checks, start_date, end_date, group, agg_name, aggregate, title, axis): """ This function generates a report for the amount/total checks paid during a time period. :param checks: The check objects to filter by :param start_date: The start date range :param end_date: The end date range :param group: The field to group by (a date) :param agg_name: The column name :param aggregate: The aggregate, either Sum/Count :param title: The title of the chart :param axis: The axis of the chart :return: The chart """ ds = DataPool( series=[{ 'options': { 'source': checks .filter(**{'{}__range'.format(group): (start_date, end_date)}) .values(group) .annotate(**{agg_name: aggregate}) .exclude(**{'{}__isnull'.format(group): True}) .order_by(group), }, 'terms': [group, agg_name] }] ) # Generate and return the chart return Chart( datasource=ds, series_options=[{ 'options': { 'type': 'column', 'stacking': False }, 'terms': { group: [agg_name] } }], chart_options={ 'title': { 'text': title }, 'xAxis': { 'title': { 'text': axis } } } )
def debt(request): member = Member.objects.get(user_id=request.user.id) family_id = member.fam_id all_family_members = Member.objects.filter(fam_id=family_id) Debts = Debt.objects.filter(Member_id__in=all_family_members) debt = DataPool( # what data is being retrieved and where it is being retrieved from series=[ { 'options': { 'source': Debts }, 'terms': [{ 'type': 'type', 'net_amount': 'net_amount' }] }, ]) cht = Chart( datasource=debt, series_options=[{ 'options': { 'type': 'column', 'stacking': False }, 'terms': { 'type': ['net_amount'] } }], chart_options={ 'title': { 'text': 'Amount of Debts vs Type of Loan in the Past 5 Years' }, 'xAxis': { 'title': { 'text': 'Type' } }, 'yAxis': { 'title': { 'text': 'Net Amount' } }, 'legend': { 'enabled': True }, 'credits': { 'enabled': True } }, ) return render(request, 'debt.html', {'chart_list': [cht]})
def spending(request): member = Member.objects.get(user_id=request.user.id) family_id = member.fam_id all_family_members = Member.objects.filter(fam_id=family_id) Spendings = Spending.objects.filter(Member_id__in=all_family_members) spending = DataPool( # what data is being retrieved and where it is being retrieved from series=[ { 'options': { 'source': Spendings }, 'terms': [{ 'type': 'type', 'neg_amount': 'neg_amount' }] }, ]) cht = Chart( datasource=spending, series_options=[{ 'options': { 'type': 'column', 'stacking': False }, 'terms': { 'type': ['neg_amount'] } }], chart_options={ 'title': { 'text': 'Spending Habits' }, 'xAxis': { 'title': { 'text': 'Type' } }, 'yAxis': { 'title': { 'text': 'Amount' } }, 'legend': { 'enabled': True }, 'credits': { 'enabled': True } }, ) return render(request, 'spending.html', {'chart_list': [cht]})
def chart_bathroom(**kwargs): model = Bathroom period = kwargs['period'] date_range = datetime.date.today() - datetime.timedelta(period) if period == 1: chart_text = '24 hours' elif period == 7: chart_text = 'week' elif period == 30: chart_text = 'month' else: chart_text = str(period) + ' days' #Step 1: Create a DataPool with the data we want to retrieve. modelData = \ DataPool( series= [{'options': { 'source': model.objects.filter(datetime__gte=date_range)}, 'terms': [ 'datetime', 'temp_value', 'hum_value']} ]) #Step 2: Create the Chart object cht = Chart(datasource=modelData, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'datetime': ['temp_value', 'hum_value'] } }], chart_options={ 'title': { 'text': 'Climate in my bathroom in the last ' + chart_text }, 'xAxis': { 'title': { 'text': 'Date/Time' } } }) #Step 3: Send the chart object to the template. return cht
def investment(request): member = Member.objects.get(user_id=request.user.id) family_id = member.fam_id all_family_members = Member.objects.filter(fam_id=family_id) Investments = Investment.objects.filter(Member_id__in=all_family_members) investment = DataPool( # what data is being retrieved and where it is being retrieved from series=[ { 'options': { 'source': Investments }, 'terms': [{ 'type': 'type', 'net_amount': 'net_amount' }] }, ]) cht = Chart( datasource=investment, series_options=[{ 'options': { 'type': 'pie', 'stacking': False }, 'terms': { 'type': ['net_amount'] } }], chart_options={ 'title': { 'text': 'Percentage Distribution of Investments' }, 'xAxis': { 'title': { 'text': 'Type' } }, 'yAxis': { 'title': { 'text': 'Net Amount' } }, 'legend': { 'enabled': True }, 'credits': { 'enabled': True } }, ) return render(request, 'investment.html', {'chart_list': [cht]})
def Rainfall_per_month_chart_view(request): month_name = 'January' if request.method == 'POST': # If the form has been submitted... form = ViewmMonthsForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data month_name = form.cleaned_data['Month'] heading_text = 'County Rainfall During the month of {} '.format( month_name) #Step 1: Create a DataPool with the data we want to retrieve. weatherdata = \ DataPool( series= [{'options': { 'source': RainDataStore.objects.filter(Month=month_name)}, 'terms': [ 'County', 'Rainfall_Amount', ]} ]) #Step 2: Create the Chart object cht = Chart(datasource=weatherdata, series_options=[{ 'options': { 'type': 'column', 'stacking': False }, 'terms': { 'County': [ 'Rainfall_Amount', ] } }], chart_options={ 'title': { 'text': heading_text }, 'xAxis': { 'title': { 'text': 'Month of year' } } }) #Step 3: Send the chart object to the template. return render_to_response('Visualized_rain_data.html', {'weatherchart': cht})
def get_fee_chart(self): feepivotdata = DataPool(series=[{ 'options': { 'source': Block.objects.raw( "select 1 as hash, to_char(timestamp,'MM-dd') as niceday, " "date(DATE_TRUNC('day', timestamp)) as date, sum(fee)/1000000 as fee " "from blockchain_block t1 join blockchain_kernel t2 " "on t2.block_id=t1.hash " "group by DATE_TRUNC('day', timestamp),niceday order by date" ) }, 'terms': ['niceday', 'fee'] }]) feepivcht = Chart( datasource=feepivotdata, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'niceday': [ 'fee', ] } }], chart_options={ 'title': { 'text': 'Transaction Fee Chart' }, 'xAxis': { 'title': { 'text': 'Date' } }, 'yAxis': { 'title': { 'text': 'Tx Fee' } }, 'legend': { 'enabled': False }, 'credits': { 'enabled': False } }, ) return feepivcht
def none(request): N = 1000 random_x = np.random.randn(N) random_y = np.random.randn(N) # Create a trace trace = go.Scatter(x=random_x, y=random_y, mode='markers') data = [trace] # Plot and embed in ipython notebook! take_back = py.iplot(data, filename='basic-scatter') # or plot with: plot_url = py.plot(data, filename='basic-line') #Step 1: Create a DataPool with the data we want to retrieve. weatherdata = \ DataPool( series= [{'options': { 'source': Monthly.objects.all()}, 'terms': [ 'month', 'houston_temp', 'boston_temp']} ]) #Step 2: Create the Chart object cht = Chart(datasource=weatherdata, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'month': ['boston_temp', 'houston_temp'] } }], chart_options={ 'title': { 'text': 'Weather Data of Boston and Houston' }, 'xAxis': { 'title': { 'text': 'Month number' } } }) #Step 3: Send the chart object to the template. return render_to_response('plot.html', {'take_back': basic - scatter})
def chart_view(request): """ :param request: :return: """ weatherdata = \ DataPool( series= [{'options': { 'source': Data.objects.all()}, 'terms': [ 'id', 'pub_date' ]} ]) cht = Chart(datasource=weatherdata, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'id': ['pub_date'] } }], chart_options={ 'title': { 'text': 'Datas' }, 'xAxis': { 'title': { 'text': 'Data number' } } }) from multiprocessing import Process, Queue from sockedserve import run run() # i1 = Queue() # ip1 = Process(target=run, args=("hhhh")) # ip1.start() # # ip1.join() return render(request, "back/graph/graph.html", locals())
def barview(usuario_id): usuario_id = usuario_id query = Item.objects.raw( 'SELECT count(li.id) as id, lm.palavra as monitoramento FROM twitter_monitor_item li INNER JOIN twitter_monitor_monitoramento lm ON li.monit_id = lm.id WHERE lm.usuario_id= %s GROUP BY lm.id', [usuario_id]) info =\ DataPool( series= [{ 'options': { 'source': query}, 'terms': [ {'Total':'id'}, {'Palavra': 'monitoramento'}]} ]) cht5 = Chart(datasource=info, series_options=[{ 'options': { 'type': 'bar', 'maxPointWidth': 25, 'stacking': False }, 'terms': { 'Palavra': ['Total'] } }], chart_options={ 'animation': { 'duration': 3000 }, 'colors': ['#ff8e24'], 'title': { 'text': 'Total por monitoramento' }, 'xAxis': { 'title': { 'text': 'Palavra' } }, 'yAxis': { 'allowDecimals': False, 'title': { 'text': 'Total' } } }) return cht5
def sensorchart(request, detailid): from chartit import DataPool, Chart ref = IloStatusDetail.objects.get(id=detailid) sensors = DataPool(series=[{ 'options': { 'source': IloStatusDetail.objects.filter( ilostatus__hardwareobject=ref.ilostatus.hardwareobject, item=ref.item, component=ref.component, name=ref.name).order_by("-id").all()[:96] }, 'terms': [('ilostatus__time', lambda d: time.mktime(d.timetuple())), 'value'] }]) # Step 2: Create the Chart object cht = Chart( datasource=sensors, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'ilostatus__time': ['value'] } }], chart_options={ 'title': { 'text': 'Valori sensore ' + ref.name + " - " + unicode(ref.ilostatus.hardwareobject) }, 'xAxis': { 'title': { 'text': 'Giorno' } }, 'yAxis': { 'title': { 'text': ref.um } } }, x_sortf_mapf_mts=( None, lambda i: datetime.fromtimestamp(i).strftime("%d %b %H:%M"), False)) return render_to_response('hpilo/sensorgraph.html', {'sensorgraph': cht})