def make_chart_daily_max_long_short(stats): chart = Highchart() options = { 'chart': { 'zoomType': 'x' }, 'title': { 'text': 'Max Long/Short intra day' }, 'xAxis': { 'type': 'datetime' }, 'yAxis': { 'title': { 'text': '$' } }, 'legend': { 'enabled': False } } chart.set_dict_options(options) timestamps = stats.index.astype(np.int64) // 1000000 long_data = np.dstack((timestamps, stats["max_long"].values))[0].tolist() chart.add_data_set(long_data, 'column', 'Max Long') short_data = np.dstack( (timestamps, -stats["max_short"].values))[0].tolist() chart.add_data_set(short_data, 'column', 'Max Short') return chart
def create_line_chart(categories, values, title, filename, charttype, orientation, axisreverse, stack): chart = Highchart() options = { 'chart': { 'type': charttype }, 'title': { 'text': title }, 'xAxis': { 'categories': categories, 'labels': { 'rotation': 45 } }, 'yAxis': { 'title': { 'text': '#Cases' }, 'stackLabels': { 'enabled': False, 'verticalAlign': 'top', 'y': 100 } }, 'plotOptions': { 'series': { 'dataLabels': { 'enabled': True }, 'stacking': 'normal' } }, 'legend': { 'enabled': True }, 'tooltip': { 'enabled': True, 'shared': True, 'formatter': "function(){ var s = '<b>'+ this.x +'</b>'; var s1=''; var sum = 0; $.each(this.points, function(i, point) { s1 += '<br/><b>'+ point.series.name +'</b>: '+ point.y ; sum += point.y; }); s += '<br/><b>Total</b>: '+sum ; return s+s1;}" } } chart.set_dict_options(options) print(options) colors = ['#1A5276', '#6E2C00', '#2C3E50', '#45B39D'] keys = list(values.keys()) for series in keys: data = values[series] chart.add_data_set(data, charttype, series, marker={'enabled': True}, color=colors[keys.index(series)]) print(filename) chart.save_file(filename)
def make_chart_daily_exposure(stats): chart = Highchart() options = { 'chart': { 'zoomType': 'x' }, 'title': { 'text': 'End of day exposure' }, 'xAxis': { 'type': 'datetime' }, 'yAxis': { 'title': { 'text': 'Exposure' } }, 'legend': { 'enabled': False } } chart.set_dict_options(options) timestamps = stats.index.astype(np.int64) // 1000000 plot_data = np.dstack( (timestamps, stats["day_end_exposure"].values))[0].tolist() chart.add_data_set(plot_data, 'area', 'Exposure') return chart
def make_chart_realized_pnl(stats): chart = Highchart() options = { 'chart': { 'zoomType': 'x' }, 'title': { 'text': 'Realized Cumulative Profit and Loss' }, 'xAxis': { 'type': 'datetime' }, 'yAxis': { 'title': { 'text': 'Realized P/L' } }, 'legend': { 'enabled': False } } chart.set_dict_options(options) timestamps = stats.index.astype(np.int64) // 1000000 plot_data = np.dstack( (timestamps, stats["realized_pnl"].values))[0].tolist() chart.add_data_set(plot_data, 'line', 'PnL') return chart
def make_chart_max_drawdown(stats): chart = Highchart() options = { 'chart': { 'zoomType': 'x' }, 'title': { 'text': 'Max Drawdown' }, 'xAxis': { 'type': 'datetime' }, 'yAxis': { 'title': { 'text': 'Daily P/L' } }, 'legend': { 'enabled': False } } chart.set_dict_options(options) timestamps = stats.index.astype(np.int64) // 1000000 plot_data = np.dstack( (timestamps, stats["max_drawdown"].values))[0].tolist() chart.add_data_set(plot_data, 'column', 'Max Drawdown') return chart
def create_chart(): chart = Highchart() options = { 'title': { 'text': 'Loss over time for various models' }, 'xAxis': { 'title': { 'text': 'Number of images' }, 'maxPadding': 0.05, 'showLastLabel': True }, 'yAxis': { 'title': { 'text': 'Loss' }, 'lineWidth': 2 }, 'legend': { 'enabled': True, 'layout': 'vertical', 'align': 'left', 'verticalAlign': 'middle' }, 'tooltip': { 'headerFormat': '<b>{series.name}</b><br/>', 'pointFormat': '{point.x} images: Loss = {point.y}' } } chart.set_dict_options(options) return chart
def save_map(): chart = Highchart() chart.set_options('chart', {'inverted': True}) options = { 'title': { 'text': 'LoadBoy 接口负载图' }, 'subtitle': { 'text': '响应时间/吞吐量/线程数' }, 'xAxis': { 'reversed': False, 'title': { 'enabled': True, 'text': '响应时间' }, 'labels': { 'formatter': 'function () {\ return this.value + " t/s";\ }' }, 'maxPadding': 0.05, 'showLastLabel': True }, 'yAxis': { 'title': { 'text': '线程数' }, 'labels': { 'formatter': "function () {\ return this.value + '';\ }" }, 'lineWidth': 2 }, 'legend': { 'enabled': False }, 'tooltip': { 'headerFormat': '<b>{series.name}</b><br/>', 'pointFormat': '' } } chart.set_dict_options(options) global rt2 global tps global t_num tps_data = list(zip(tps, t_num)) chart.add_data_set(tps_data, 'spline', 'tps', marker={'enabled': False}) rt_data = list(zip(rt2, t_num)) chart.add_data_set(rt_data, 'line', 'rt', marker={'enabled': False}) chart.save_file()
def hc_line_time_series(data, title, y_title=None, theme=None, xl_dates=False): """Plots a 2d array of times and data points.""" # Convert Excel dates to datetimes if necessary if xl_dates: to_date = get_type_converter("var", "datetime") data = [(to_date(d), v) for d, v in data] H = Highchart() H.set_options('chart', { 'zoomType': 'x' }) H.set_options('xAxis', { 'type': 'datetime' }) H.set_options('yAxis', { 'title': { 'text': y_title or "Values" } }) H.set_options('title', { 'text': title or "Time Series" }) H.set_options('legend', { 'enabled': False }) H.add_data_set(data, 'area') H.set_options('plotOptions', { 'area': { 'fillColor': { 'linearGradient': { 'x1': 0, 'y1': 0, 'x2': 0, 'y2': 1}, 'stops': [ [0, "Highcharts.getOptions().colors[0]"], [1, "Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')"] ]}, 'marker': { 'radius': 2 }, 'lineWidth': 1, 'states': { 'hover': { 'lineWidth': 1 } }, 'threshold': None } }) return hc_plot(H, title, theme)
def __init__(self, **kwargs): self.q_df = kwargs["question_dataframe"] self.tag = kwargs["question_tag"] self.levels = kwargs["target_levels"] self.study_groups_definition = kwargs["study_groups_definition"] self.chart = Highchart() chart_options = kwargs["chart_options"] if isinstance(chart_options, DeepChainMap): chart_options = chart_options.to_dict() self.chart.set_dict_options(chart_options) self.chart_definition = None # calculated by _chart method
def create_highcharts(device_name, results): categories = [] ssid_categories = results[3] for pair in ssid_categories: categories.append(pair[1]) chart = Highchart(width=1000, height=400) styling = '<span style="font-family: \'DejaVu Sans\', Arial, Helvetica, sans-serif; color: ' options = { 'title': { 'text': styling + '#00AEEF; font-size: 20px; line-height: 1.2640625; ">' + 'Wi-Fi Performance ' + device_name + '</span>' }, 'chart': { 'zoomType': 'x' }, 'xAxis': { 'type': 'datetime', 'title': { 'text': styling + '#F7941C; font-size: 12px; line-height: 1.4640625; font-weight: bold;">Time [h:min:s]</span>' } }, 'yAxis': [{ 'title': { 'text': styling + '#00AEEF; font-size: 12px; line-height: 1.2640625; font-weight: bold; ">Throughput [bps]</span>' }, }, { 'title': { 'text': styling + '#EC008C; font-size: 12px; line-height: 1.2640625; font-weight: bold; ">RSSI</span>' }, 'opposite': 'true' }, { 'title': { 'text': styling + '#00A650; font-size: 12px; line-height: 1.2640625; font-weight: bold; ">SSID/BSSID</span>' }, 'categories': categories, 'opposite': 'true' }], } chart.set_dict_options(options) return chart
def create_graph(self, custom_begin_date, custom_end_date, quantity, time_interval): sensor_node = SensorNode(self.node_id) timestamps = self.get_begin_and_end_timestamps(custom_begin_date, custom_end_date, time_interval) line_graph = Highchart() time_label = '' sensor_node.set_measurements( self.select_measurements(timestamps[0], timestamps[1], quantity)) measurement_types = sensor_node.get_distinct_measurement_types() for m_type in measurement_types: data_list = sensor_node.create_data_list(m_type) line_graph.add_data_set( data_list, series_type='line', name=(sensor_node.get_sensor_description(m_type))) if time_interval == TimeInterval.TODAY or time_interval == TimeInterval.YESTERDAY: time_label = "'hour': '%H:%M'" elif time_interval == TimeInterval.LAST_WEEK: time_label = "'day': '%e. %b'" options = { 'title': { 'text': str(quantity) + " meetdata van bijenkast " + str(sensor_node.node_id) }, 'subtitle': { 'text': "iBee 2017-2018" }, 'xAxis': { 'type': "datetime", 'dateTimeLabelFormats': {time_label}, 'title': { 'text': "Tijd" } }, 'yAxis': { 'title': { 'text': quantity } } } line_graph.set_dict_options(options) return line_graph
def stat(): ''' Pagina con le statistiche nel periodo selezionato ''' # input GET if request.method == 'GET': start_date = request.args.get('start_date', '') stop_date = request.args.get('stop_date', '') # calcolo consumo dati = calcoloConsumo() auto_selezionata = 'Fiesta' ind = (dati['data'] >= datetime.datetime.strptime(start_date,'%Y-%m-%d')) & \ (dati['data'] <= datetime.datetime.strptime(stop_date,'%Y-%m-%d')) & \ (dati['auto'] == auto_selezionata) dati_filt = dati.loc[ind, :].drop( ['id', 'insertdate', 'chilometri_last', 'chilometri_delta'], axis=1).reset_index(drop=True).copy() # Grafico chart = Highchart(width=600, height=500) chart.add_data_set(dati_filt[['data', 'euro al litro']].values.tolist(), series_type='line', name='Prezzo (€/litro)') chart.add_data_set(dati_filt[['data', 'chilometri con un litro']].values.tolist(), series_type='line', name='km con un litro') chart.add_data_set(dati_filt[['data', 'chilometri con un litro CUM' ]].values.tolist(), series_type='line', name='km con un litro avg') chart.set_options('xAxis', {'type': 'datetime', 'gridLineWidth': 1}) # chart.set_options('chart', {'backgroundColor':'transparent'}) chart.set_options('tooltip', {'formatter': 'default_tooltip'}) chart.set_options('title', {'text': 'Statistiche consumo'}) chart.htmlcontent return render_template( 'gas_stat.html', start_date=start_date, stop_date=stop_date, df1=dati_filt.to_html(classes='table', index=False, escape=True).replace( '<th>', '<th style = "background-color: #000099" >'), fig1_head=chart.htmlheader, fig1_body=chart.content)
def plot_2d(self): h = Highchart(width=750, height=600) options = { 'title': { 'text': 'Value Function Iteration' }, 'xAxis': { 'title': { 'text': "K - Capital Level" } }, 'yAxis': { 'title': { 'text': "Value of Capital" } }, 'tooltip': { 'crosshairs': False, 'shared': True, }, 'legend': {} } h.set_dict_options(options) for x in range(0, len(self.z_vector)): df1 = pd.DataFrame({ 'k': self.k_vector[1:], 'value': self.value_matrix[1:, [x]].flatten() }) df1 = df1[['k', 'value']] df1 = df1.values.tolist() h.add_data_set(df1, 'spline', 'z_' + str(x) + ' = ' + str(self.z_vector[x]), zIndex=1, marker={ 'fillColor': 'white', 'lineWidth': 2, 'lineColor': 'Highcharts.getOptions().colors[1]' }) html_str = h.htmlcontent.encode('utf-8') html_file = open("chart.html", "w") html_file.write(html_str) html_file.close()
def fuel_stat(request, auto_id=None, start_date=None, end_date=None): '''Stat for supply''' common = {"name": "Fuel"} # Initial-default values last_auto = models.Supply.objects.latest('id').auto start_date_init = timezone.now().date() + timezone.timedelta(days=-60) end_date_init = timezone.now().date() # get form form = forms.FuelStatForm(request.GET) if form.is_valid(): common["auto"] = form.cleaned_data['auto'] common["start_date"] = form.cleaned_data['start_date'] common["end_date"] = form.cleaned_data['end_date'] else: form = forms.FuelStatForm(initial={"auto":last_auto, "start_date":start_date_init, "end_date":end_date_init}) common["auto"] = last_auto common["start_date"] = start_date_init common["end_date"] = end_date_init # Get data Supply = models.Supply.objects.filter(auto=common["auto"]).filter(event_date__gte=common["start_date"]) \ .filter(event_date__lte=common["end_date"]).order_by('event_date').all() cum_sum = [[0, 0, 0]] # calcolo la somma, per ottenere la cumulata for supply in Supply: supply.calcStat() cum_sum.append([supply.event_date, cum_sum[-1][1]+supply.distance, cum_sum[-1][2]+supply.volume]) cum_sum.pop(0) # Highchart chart = Highchart(height = 500) chart.add_data_set([[1000*(a.event_date-datetime.date(1970,1,1)).total_seconds(), int(a.pricevolume*100)/100] for a in Supply], series_type='line', name='Prezzo (€/litro)') chart.add_data_set([[1000*(a.event_date-datetime.date(1970,1,1)).total_seconds(), int(a.consumption1*100)/100] for a in Supply], series_type='line', name='km con un litro') chart.add_data_set([[1000*(a[0]-datetime.date(1970,1,1)).total_seconds(), int(a[1]/a[2]*100)/100] for a in cum_sum], series_type='line', name='km con un litro (tendenza)') chart.set_options('xAxis', {'type': 'datetime', 'gridLineWidth': 1}) # chart.set_options('chart', {'backgroundColor':'transparent'}) chart.set_options('tooltip', {'formatter': 'default_tooltip'}) chart.set_options('title', {'text': f"Statistiche consumo {common['auto']}"}) chart.htmlcontent; chart_dict = {"header": chart.htmlheader, "content":chart.content} return render(request, 'alldoc/fuel_stat.html', {"common": common, "Supply": Supply, "form": form, "chart": chart_dict})
def piscinaStat(): ''' Pagina con le statistiche degli allenamenti nel periodo selezionato ''' # input GET if request.method == 'GET': start_date = request.args.get('start_date', '') stop_date = request.args.get('stop_date', '') # Scarico i dati da DB: allenamenti compresi tra le date specificate query_text = ("""SELECT strftime('%Y',data) AS anno , strftime('%m',data) AS mese , count(0) AS Nvolte , sum(n_vasche * 25 / lung_vasche) AS somma_vasche , round(avg(n_vasche * 25 / lung_vasche), 1) AS media_vasche , sum(n_vasche * lung_vasche) AS somma_metri , round(avg(n_vasche * lung_vasche), 0) AS media_metri FROM piscina_allenamenti JOIN nome_piscina ON piscina_allenamenti.id_nome_piscina = nome_piscina.id WHERE data >= date('"""+start_date+"""') AND data < date('"""+stop_date+"""') GROUP BY anno , mese""") dati = pd.read_sql_query(query_text, engine) dati['media_metri'] = dati['media_metri'].astype('int') # Grafico chart = Highchart(width = 600, height = 500) dff=[] for i in range(len(dati)): dff.append(str(dati.anno[i])+'/'+str(dati.mese[i])) chart.set_options('xAxis', {'categories': dff, 'gridLineWidth': 1}) chart.set_options('tooltip', {'formatter': 'default_tooltip'}) chart.set_options('title', {'text': 'Statistiche mensili allenamenti'}) # chart.set_options('chart', {'backgroundColor':'transparent'}) chart.add_data_set(dati.Nvolte.values.tolist(), series_type='bar', name='Numero allenamenti') chart.add_data_set(dati.media_metri.values.tolist(), series_type='line', name='Media metri') chart.add_data_set(dati.somma_metri.values.tolist(), series_type='bar', name='Somma metri') chart.htmlcontent; return render_template('piscina_stat.html', start_date=start_date, stop_date=stop_date, df1=dati.to_html(classes='table',index=False,escape=True).replace('<th>','<th style = "background-color: #000099" >'), fig1_head=chart.htmlheader, fig1_body=chart.content)
def renderChart(stats, bottom, left="Workflow Job"): keys = [k for k, _ in stats.items()] values = [v for _, v in stats.items()] chart = Highchart() chart.set_options("chart", {"inverted": True}) options = { "title": { "text": "{0} by {1}".format(bottom, left) }, "xAxis": { "categories": keys, "title": { "text": left }, "maxPadding": 0.05, "showLastLabel": True, }, "yAxis": { "title": { "text": bottom }, "labels": { "formatter": "function () {\ return this.value;\ }" }, "lineWidth": 2, }, "legend": { "enabled": False }, "tooltip": { "headerFormat": "<b>{series.name}</b><br/>", "pointFormat": "{point.x} : {point.y}", }, } chart.set_dict_options(options) chart.add_data_set(values, "bar") return str(chart)
def hc_basic_line(data, title, subtitle=None, y_axis=None, labels=None, theme=None): H = Highchart() H.set_options("title", { "text": title }) if subtitle: H.set_options("subtitle", { "text": subtitle }) if y_axis: H.set_options("yAxis", { "title": { "text": y_axis } }) H.set_options("legend", { "layout": "vertical", "align": "right", "verticalAlign": "middle" }) # transform the data from a list of rows to a list of columns data_t = list(zip(*data)) # Use the first column as the X axis x_axis = data_t[0] H.set_options("xAxis", { "categories": x_axis, "tickmarkPlacement": "on" }) # And the remaining columns as the graph data if not labels: labels = ["series_%d" % i for i in range(len(data_t)-1)] for label, series in zip(labels, data_t[1:]): H.add_data_set(series, series_type='line', name=label) return hc_plot(H, title, theme)
def plot_bar_chart_from_pandas_dataframe(df): assert list(df[df.columns[0]]) == list( range(1, len(chart_config.OFIG_X_AXIS_CATEGORIES) + 1)), "Dataframe categories are in the wrong order" assert len(df.index) == len( chart_config.OFIG_X_AXIS_CATEGORIES ), "Dataframe does not contain values for every category" question_export_tag = df.columns[0] chart = Highchart() chart.set_dict_options( chart_config.OfigChartOptions.CHART_OPTIONS.to_dict()) for series_name in df.columns[1:]: data = list(df[series_name]) chart.add_data_set( data, series_type="bar", name=series_name, color=chart_config.THISCOVERY_RED, ) return output_to_files(chart, question_export_tag)
def make_chart_asset_allocation(product_map, account): allocations = list( map(functools.partial(get_position_value, product_map, account), account.get_ids())) capital = account.get_stats().tail(1)['day_end_capital'][0] allocations.append({'name': 'Cash', 'value': capital}) total_allocations = sum(map(lambda x: x['value'], allocations)) allocations_percent = list( map( lambda x: { 'name': x['name'], 'y': x['value'] / total_allocations * 100 }, allocations)) chart = Highchart() options = { 'chart': { 'zoomType': 'x' }, 'title': { 'text': 'Asset allocation' }, 'xAxis': { 'type': 'datetime' }, 'yAxis': { 'title': { 'text': 'Daily P/L' } }, 'legend': { 'enabled': False } } chart.set_dict_options(options) chart.add_data_set(allocations_percent, 'pie', 'Asset allocation') return chart
def cat_page(): # return render_template('cat_page.html') url = 'http://catsgalore.me/api/breeds/' r = requests.get(url) breeds = r.json()['breeds'] data = [br['weight'] for br in breeds] weights = [map(float, tuple(b[1:b.find(')')].split(' to '))) for b in data] chart = Highchart() chart.add_data_set(weights, 'scatter', 'Cat Weights') chart.set_dict_options(options) w = BeautifulSoup(open(BASE_URL + "templates/cat_page.html")) c = BeautifulSoup(str(chart.htmlcontent)) scripts = c.find_all(lambda tag: (tag.has_attr('src') and tag.name == 'script') or tag.name == 'link') chart_script = c.find_all( lambda tag: not tag.has_attr('type') and tag.name == 'script')[0] loading = c.div head = w.head div = w.find_all('div', class_='table-wrapper')[0] div.insert(0, loading) div.insert(1, chart_script) for s in scripts: head.append(s) html = w.prettify("utf-8") with open(BASE_URL + "templates/cats.html", "wb") as f: f.write(html) return render_template("cats.html")
def plot_grid(molmap, htmlpath='./', htmlname=None): ''' molmap: the object of molmap htmlpath: the figure path ''' if not os.path.exists(htmlpath): os.makedirs(htmlpath) title = 'Assignment of %s by %s emmbedding result' % (molmap.ftype, molmap.method) subtitle = 'number of %s: %s, metric method: %s' % ( molmap.ftype, len(molmap.flist), molmap.metric) name = '%s_%s_%s_%s_%s' % (molmap.ftype, len( molmap.flist), molmap.metric, molmap.method, 'molmap') if htmlname: name = name = htmlname + '_' + name filename = os.path.join(htmlpath, name) print_info('generate file: %s' % filename) m, n = molmap.fmap_shape colormaps = molmap.extract.colormaps position = np.zeros(molmap.fmap_shape, dtype='O').reshape(m * n, ) position[molmap._S.col_asses] = molmap.flist position = position.reshape(m, n) x = [] for i in range(n): x.extend([i] * m) y = list(range(m)) * n v = position.reshape(m * n, order='f') df = pd.DataFrame(list(zip(x, y, v)), columns=['x', 'y', 'v']) bitsinfo = molmap.extract.bitsinfo subtypedict = bitsinfo.set_index('IDs')['Subtypes'].to_dict() subtypedict.update({0: 'NaN'}) df['Subtypes'] = df.v.map(subtypedict) df['colors'] = df['Subtypes'].map(colormaps) H = Highchart(width=1000, height=850) H.set_options('chart', {'type': 'heatmap', 'zoomType': 'xy'}) H.set_options('title', {'text': title}) H.set_options('subtitle', {'text': subtitle}) # H.set_options('xAxis', {'title': '', # 'min': 0, 'max': molmap.fmap_shape[1]-1, # 'allowDecimals':False, # 'labels':{'style':{'fontSize':20}}}) # H.set_options('yAxis', {'title': '', 'tickPosition': 'inside', # 'min': 0, 'max': molmap.fmap_shape[0]-1, # 'reversed': True, # 'allowDecimals':False, # 'labels':{'style':{'fontSize':20}}}) H.set_options( 'xAxis', { 'title': None, 'min': 0, 'max': molmap.fmap_shape[1], 'startOnTick': False, 'endOnTick': False, 'allowDecimals': False, 'labels': { 'style': { 'fontSize': 20 } } }) H.set_options( 'yAxis', { 'title': { 'text': ' ', 'style': { 'fontSize': 20 } }, 'startOnTick': False, 'endOnTick': False, 'gridLineWidth': 0, 'reversed': True, 'min': 0, 'max': molmap.fmap_shape[0], 'allowDecimals': False, 'labels': { 'style': { 'fontSize': 20 } } }) H.set_options( 'legend', { 'align': 'right', 'layout': 'vertical', 'margin': 1, 'verticalAlign': 'top', 'y': 60, 'symbolHeight': 12, 'floating': False, }) H.set_options('tooltip', { 'headerFormat': '<b>{series.name}</b><br>', 'pointFormat': '{point.v}' }) H.set_options('plotOptions', {'series': {'turboThreshold': 5000}}) for subtype, color in colormaps.items(): dfi = df[df['Subtypes'] == subtype] if len(dfi) == 0: continue H.add_data_set( dfi.to_dict('records'), 'heatmap', name=subtype, color=color, #dataLabels = {'enabled': True, 'color': '#000000'} ) H.save_file(filename) print_info('save html file to %s' % filename) return df, H
# used to represent the frequency of posts by user # used to create dynamic graphs from highcharts import Highchart chart = Highchart() # new highchart object # graph attributes options = { 'chart': { 'type': 'bar', 'zoomType': 'xy' }, 'title': { 'text': 'Highchart Bar' }, 'legend': { 'enabled': True }, 'xAxis': { 'categories': ['User 1', 'User 2', 'User 3', 'User 4', 'User 5'], }, 'yAxis': { 'title': { 'text': 'Number of posts (thousands)' } }, } # we can use our own data data1 = [107, 31, 635, 203, 2] data2 = [133, 156, 947, 408, 6]
from highcharts import Highchart chart = Highchart() options = { 'chart': { 'type':'bar'}, 'title':{ 'text':'Top 10 Hashtags'}, 'xAxis':{ 'categories':['1','2','3','4','5','6','7','8','9','10']}, 'yAxis':{ 'title':{ 'text':'Number of times mentioned'} }, } data1 #This is an array. make size 10. first means first graoh chart.set_dict_options(options) chart.add_data_set(data1, 'bar', 'Count') chart.save_file('./bar-highcharts')
""" Jugal Marfatia Macroeconomics homework 3. """ import numpy as np import numpy.matlib as mt import pandas as pd from highcharts import Highchart H = Highchart(width=750, height=600) H1 = Highchart(width=750, height=600) A = 1.0 alpha = 0.36 beta = 0.9 kss = (alpha*beta)**(1/(1-alpha)) # steady state # comment for Part (d) # L = 0.95 # factor lower bound # U = 1.05 # factor upper bound # n = 2 # number of grid points # uncomment for Part (d) L = 0.6 # idem U = 1.4 # idem n = 100 # idem k = np.linspace(L * kss, U * kss, n) criteria = 1.0 # init criterion for stopping iterations tol = 1e-6 # tolerance
# -*- coding: utf-8 -*- """ Highcharts Demos Bubble chart: http://www.highcharts.com/demo/bubble """ from highcharts import Highchart H = Highchart(width=850, height=400) options = { 'chart': { 'type': 'bubble', 'zoomType': 'xy' }, 'title': { 'text': 'Highcharts Bubbles' }, } data1 = [[97, 36, 79], [94, 74, 60], [68, 76, 58], [64, 87, 56], [68, 27, 73], [74, 99, 42], [7, 93, 87], [51, 69, 40], [38, 23, 33], [57, 86, 31]] data2 = [[25, 10, 87], [2, 75, 59], [11, 54, 8], [86, 55, 93], [5, 3, 58], [90, 63, 44], [91, 33, 17], [97, 3, 56], [15, 67, 48], [54, 25, 81]] data3 = [[47, 47, 21], [20, 12, 4], [6, 76, 91], [38, 30, 60], [57, 98, 64], [61, 17, 80], [83, 60, 13], [67, 78, 75], [64, 12, 10], [30, 77, 82]] H.set_dict_options(options) H.add_data_set(data1, 'bubble') H.add_data_set(data2, 'bubble') H.add_data_set(data3, 'bubble') H.htmlcontent
if query == 1: data = q.topHashtags() plot = [] if data is None: print("Sorry, No Results Are Found!") else: table = PrettyTable() table.field_names = ["Hashtag", "Count"] for row in data: hashtag = row[1] count = row[0] table.add_row([hashtag, count]) plot.append([hashtag, count]) print(table) chart = Highchart(width=664, height=400) chart.set_options('chart', {'inverted': False}) options = { 'chart': { 'type': 'pie', 'options3d': { 'enabled': True, 'alpha': 45 } }, 'title': { 'text': 'Top Hashtags' }, 'subtitle': {
def create_chart(categories, values, title, filename, charttype, orientation, axisreverse, stack): chart = Highchart() options = { 'chart': { 'type': charttype }, 'title': { 'text': title }, 'xAxis': { 'reversed': axisreverse, 'categories': categories, 'maxPadding': 0.05, 'showLastLabel': True }, 'yAxis': { 'title': { 'text': '#Cases' }, 'stackLabels': { 'enabled': stack, 'style': { 'color': 'black' } }, 'lineWidth': 2 }, 'plotOptions': { 'series': { 'dataLabels': { 'enabled': True, 'style': { 'fontWeight': 'bold', 'color': 'gray' } }, 'stacking': 'normal' } }, 'legend': { 'enabled': True }, 'tooltip': { 'shared': True, 'enabled': True } } chart.set_dict_options(options) print(options) colors = ['#1A5276', '#6E2C00', '#2C3E50'] keys = list(values.keys()) for series in keys: data = values[series] chart.add_data_set(data, charttype, series, marker={'enabled': True}, color=colors[keys.index(series)]) print(filename) chart.save_file(filename)
def plot_scatter(molmap, htmlpath='./', htmlname=None, radius=3): ''' molmap: the object of molmap htmlpath: the figure path, not include the prefix of 'html' htmlname: the name radius: int, defaut:3, the radius of scatter dot ''' title = '2D emmbedding of %s based on %s method' % (molmap.ftype, molmap.method) subtitle = 'number of %s: %s, metric method: %s' % ( molmap.ftype, len(molmap.flist), molmap.metric) name = '%s_%s_%s_%s_%s' % (molmap.ftype, len( molmap.flist), molmap.metric, molmap.method, 'scatter') if not os.path.exists(htmlpath): os.makedirs(htmlpath) if htmlname: name = htmlname + '_' + name filename = os.path.join(htmlpath, name) print_info('generate file: %s' % filename) xy = molmap.embedded.embedding_ colormaps = molmap.extract.colormaps df = pd.DataFrame(xy, columns=['x', 'y']) bitsinfo = molmap.extract.bitsinfo.set_index('IDs') df = df.join(bitsinfo.loc[molmap.flist].reset_index()) df['colors'] = df['Subtypes'].map(colormaps) H = Highchart(width=1000, height=850) H.set_options('chart', {'type': 'scatter', 'zoomType': 'xy'}) H.set_options('title', {'text': title}) H.set_options('subtitle', {'text': subtitle}) H.set_options( 'xAxis', { 'title': { 'enabled': True, 'text': 'X', 'style': { 'fontSize': 20 } }, 'labels': { 'style': { 'fontSize': 20 } }, 'gridLineWidth': 1, 'startOnTick': True, 'endOnTick': True, 'showLastLabel': True }) H.set_options( 'yAxis', { 'title': { 'text': 'Y', 'style': { 'fontSize': 20 } }, 'labels': { 'style': { 'fontSize': 20 } }, 'gridLineWidth': 1, }) # H.set_options('legend', {'layout': 'horizontal','verticalAlign': 'top','align':'right','floating': False, # 'backgroundColor': "(Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'", # 'borderWidth': 1}) H.set_options( 'legend', { 'align': 'right', 'layout': 'vertical', 'margin': 1, 'verticalAlign': 'top', 'y': 40, 'symbolHeight': 12, 'floating': False, }) H.set_options( 'plotOptions', { 'scatter': { 'marker': { 'radius': radius, 'states': { 'hover': { 'enabled': True, 'lineColor': 'rgb(100,100,100)' } } }, 'states': { 'hover': { 'marker': { 'enabled': False } } }, 'tooltip': { 'headerFormat': '<b>{series.name}</b><br>', 'pointFormat': '{point.IDs}' } }, 'series': { 'turboThreshold': 5000 } }) for subtype, color in colormaps.items(): dfi = df[df['Subtypes'] == subtype] if len(dfi) == 0: continue data = dfi.to_dict('records') H.add_data_set(data, 'scatter', subtype, color=color) H.save_file(filename) print_info('save html file to %s' % filename) return df, H
def hchart_json(): chart = Highchart() data = [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8] chart.add_data_set(data, series_type='line', name='Example Series') chart.save_file()
# -*- coding: utf-8 -*- """ Highcharts Demos Heatmap: http://www.highcharts.com/demo/heatmap """ from highcharts import Highchart H = Highchart() data = [ [0, 0, 10], [0, 1, 19], [0, 2, 8], [0, 3, 24], [0, 4, 67], [1, 0, 92], [1, 1, 58], [1, 2, 78], [1, 3, 117], [1, 4, 48], [2, 0, 35], [2, 1, 15], [2, 2, 123], [2, 3, 64], [2, 4, 52], [3, 0, 72], [3, 1, 132], [3, 2, 114], [3, 3, 19], [3, 4, 16], [4, 0, 38], [4, 1, 5],