def compareChart(currentWeek, students, names, averageRank): if not os.path.exists(chart_folder): os.makedirs(chart_folder) raw_options['chart']['height'] = 800 options = copy.deepcopy(raw_options) options['title']['text'] = 'Normalized Rank Comparison Chart' options['yAxis']['title']['text'] = 'Normalized Rank' options['xAxis']['title']['text'] = 'Week' chart = Highchart() chart.set_dict_options(options) series = [] for student in students: if not student.is_active: continue name = names[student.user_name] data = [] for week in range(1, currentWeek + 1): rank = averageRank[week-1].get(student.user_name) if rank is not None: point = [week, rank] data.append(point) series.append({'name': name, 'data': data}) chart.add_data_set(data, 'spline', name, marker={'enabled': True}) #options['series'] = series chart.save_file(chart_folder + 'compare')
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 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 generateCharts(currentWeek, students, names, averageRank, averageToken): if not os.path.exists(chart_folder): os.makedirs(chart_folder) raw_options['chart']['height'] = 500 options = copy.deepcopy(raw_options) options['yAxis'] = [{ 'min' : -1, 'max' : 1, 'reversed': True, 'title': { 'text': 'Normalized Rank' }, 'labels': { 'formatter': "function () {\ return this.value;\ }" }, 'lineWidth': 2 }, { 'reversed': True, 'title': { 'text': 'Normalized Token' }, 'labels': { 'formatter': "function () {\ return this.value;\ }" }, 'lineWidth': 2, 'opposite': True }, ] options['xAxis']['title']['text'] = 'Week' for student in students: if not student.is_active: continue chart = Highchart() options['title']['text'] = names[student.user_name] options['chart']['renderTo'] = 'container_' + student.user_name chart.set_dict_options(options) rank_data = [] token_data = [] for week in range(1, currentWeek + 1): rank = averageRank[week-1].get(student.user_name) token = averageToken[week-1].get(student.user_name) if rank is not None and token is not None: point = [week, rank] rank_data.append(point) point = [week, token] token_data.append(point) chart.add_data_set(rank_data, 'spline', 'Normalized Rank', marker={'enabled': True}) chart.add_data_set(token_data, 'spline', 'Normalized Token', marker={'enabled': True}, yAxis=1) chart.save_file(chart_folder + student.user_name)
}, 'xAxis': { 'categories': ['User 1', 'User 2', 'User 3', 'User 4', 'User 5'], }, 'yAxis': { 'title': { 'text': 'Number of posts (thousands)' } }, } var allProductsArray = db.restaurants.find().toArray(); data1 = [1070, 301, 6035, 2003, 200] data2 = [1330, 0156, 9047, 4008, 600] data3 = [9703, 9140, 40504, 7302, 340] data4 = [105002, 9504, 40250, 7040, 308] chart.set_dict_options(options) chart.add_data_set(data1, 'bar', 'Day 1') chart.add_data_set(data2, 'bar', 'Day 2') chart.add_data_set(data3, 'bar', 'Day 3') chart.add_data_set(data4, 'bar', 'Day 4') chart.save_file('./highcharts-bar')
'enabled': True }, 'xAxis': { 'title': { 'text': 'Followers (thousands)' } }, 'yAxis': { 'title': { 'text': 'Friends (thousands)' } }, } data1 = [[161, 51], [167, 59], [159, 49], [157, 63], [155, 53]] data2 = [[174, 165], [175, 171], [193, 180], [186, 172], [187, 178]] chart.set_dict_options(options) chart.add_data_set(data1, 'scatter', 'Celebrity accounts', color='rgba(223, 83, 83,0.5)') chart.add_data_set(data2, 'scatter', 'Normal user accounts', color='rgba(119, 152, 191,0.5)') chart.save_file('./highcharts-scatter')
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')
'text': 'Observed in Kansas City, Kansas, USA' }, 'plotOptions': { 'pie': { 'innerSize': 100, 'depth': 45 } } } chart.set_dict_options(options) data = plot chart.add_data_set(data, 'pie', 'Count') chart.save_file("hashtags") elif query == 2: data = q.KCtweets() if data is None: print("Sorry, No Results Are Found!") else: table = PrettyTable() table.field_names = [ "Tweet Id ", "Place", "Create at", "Favorites", "Content" ] for row in data: t_id = row[0] place = row[1] created_at = row[2] fav = row[3]
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_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
def highchart_analyser(df, period='M', name=""): charts = Highchart() # create highcharts instance # remove time field from either of the headers lists options = { 'chart': { 'zoomType': 'x' }, 'title': { 'text': 'Shryne User/Contact Statistics at Resolution: ' + period }, 'xAxis': { 'type': 'datetime', 'crosshair': True }, 'credits': { 'enabled': False }, 'yAxis': [{ 'gridLineWidth': 0, 'title': { 'text': 'Messages (% of total)', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'labels': { 'format': '{value}', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } } }, { 'gridLineWidth': 0, 'title': { 'text': 'Sentiment', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'labels': { 'format': '{value}', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'opposite': True }, { 'gridLineWidth': 0, 'title': { 'text': 'Response Time', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'labels': { 'format': '{value}', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'opposite': True }, { 'reversed': True, 'gridLineWidth': 0, 'title': { 'enabled': False }, 'labels': { 'enabled': False }, 'opposite': True }], 'tooltip': { 'shared': True, }, 'legend': { 'layout': 'vertical', 'align': 'left', 'x': 80, 'verticalAlign': 'top', 'y': 55, 'floating': False, 'backgroundColor': "(Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'" } } x = df.index.values.tolist() x = [int(i) / 1000000 for i in x] time_vs_counts = list(zip(x, df["message_count"])) time_vs_pos_sent = list(zip(x, df["compound"])) time_vs_word_length = list(zip(x, df["response_time"])) time_vs_message_reciprocity = list(zip(x, df["message_count_reciprocity"])) time_vs_word_length_reciprocity = list(zip(x, df["probs"])) charts.set_dict_options(options) charts.add_data_set(time_vs_counts, series_type='spline', yAxis=0, name="Message Count", color='rgba(0,191,255, 1)') charts.add_data_set(time_vs_pos_sent, 'column', name="sentiment", yAxis=2, stack='sentiment', color='brown') charts.add_data_set(time_vs_word_length, series_type='spline', yAxis=2, name="Response time", color='rgba(186,85,211, 1)') charts.add_data_set(time_vs_message_reciprocity, series_type='spline', yAxis=1, name="Message Count reciprocity", color='red') charts.add_data_set(time_vs_word_length_reciprocity, series_type='spline', yAxis=1, name="Health Score", color='black') charts.save_file('plots/_time_series_' + period + str(name))
countries = {} for doc in docs: if LANG in doc: lang = doc[LANG] if lang: lang = lang.upper() if lang in langs: langs[lang] += 1 else: langs[lang] = 1 if COUNTRY in doc: country = doc[COUNTRY] if country: if country in countries: countries[country] += 1 else: countries[country] = 1 chart = Highchart() options = {TITLE : {TEXT : 'Results per Language'}} chart.set_dict_options(options) chart.add_data_set(langs.items(), series_type='pie', name='Results') chart.save_file(splitext(argv[2])[0]) chart = Highchart() options = {TITLE : {TEXT : 'Results per Country'}} chart.set_dict_options(options) chart.add_data_set(countries.items(), series_type='pie', name='Results') chart.save_file(splitext(argv[3])[0])
def create_histogram(src, dst_html, title=None, subtitle=None, x_axis_header=None, y_axis_header=None, x_axis_name=None, y_axis_name=None): """Creates basic histogram using Highcharts Args: src (string or DataFrame): Path to csv with source data or DataFrame with source data. dst_html (string): Path to destination html output title (string): Title of histogram subtitle (string): Subtitle of histogram x_axis_header (str): Name of x-axis header in csv file. Defaults to None. y_axis_header (str): Name of y-axis header in csv file. Defaults to None. x_axis_name (str): Name of x-axis to use in histogram. Defaults to None. y_axis_name (str): Name of y-axis to use in histogram. Defaults to None. Returns: None. """ # Check destination if dst_html[-5:] == '.html': dst_chart = dst_html[:-5] # Omit '.html' for exporting with Highcharts else: dst_chart = dst_html dst_html += '.html' # Import source csv into pandas DataFrame if type(src) == 'str': src_df = pd.read_csv(src) elif isinstance(src, pd.core.frame.DataFrame): src_df = src # Define headers if not given if not x_axis_header: x_axis_header = src_df.columns[0] if not y_axis_header: y_axis_header = src_df.columns[1] # Define axis names if not given if not x_axis_name: x_axis_name = x_axis_header if not y_axis_name: y_axis_name = y_axis_header # Convert source to list of lists, convert x-axis to category list for labels hist_data = [] hist_categories = [] # Explicitly define x-axis categories to workaround zoom glitch for index, row in src_df.iterrows(): hist_data.append([str(row[x_axis_header]), float(row[y_axis_header])]) hist_categories.append(str(row[x_axis_header])) # Define chart options options = { 'chart': { 'type': 'column', 'zoomType': 'x' # Causes incorrect x-axis labels if categories are not explicitly defined }, 'title': { 'text': title }, 'subtitle': { 'text': subtitle }, 'xAxis': { 'type': 'category', 'categories': hist_categories, 'title': { 'text': x_axis_name } }, 'yAxis': { 'title': { 'text': y_axis_name } }, 'tooltip': { 'shared': True, 'pointFormat': '{point.y:,.0f}' }, 'legend': { 'enabled': False }, 'plotOptions': { 'series': { 'borderWidth': 0, 'dataLabels': { 'enabled': True, 'format': '{point.y:,.0f}' } } }, } # Create chart, export, and open h = Highchart(width=1920, height=1080) h.set_dict_options(options) h.add_data_set(hist_data, 'column') h.save_file(dst_chart) webbrowser.open('file://' + dst_html)
'legend': { 'enabled': True }, 'xAxis': { 'title': { 'text': 'Followers (thousands)' } }, 'yAxis': { 'title': { 'text': 'Friends (thousands)' } }, } data1 = [[161, 51], [167, 59], [159, 49], [157, 63], [155, 53]] data2 = [[174, 165], [175, 171], [193, 180], [186, 172], [187, 178]] chart.set_dict_options(options) chart.add_data_set( data1, 'scatter', 'Celebrity accounts', color='rgba(223, 83, 83,0.5)') # data, type_of_chart, legend_text, color chart.add_data_set(data2, 'scatter', 'Normal user accounts', color='rgba(119, 152, 191,0.5)') chart.save_file('./highcharts-scatter') # write to the file and save
option is a (python) dict for options settings The way to use this method is very similar to the options object as on highcharts docs: http://www.highcharts.com/docs/getting-started/how-to-set-options 1. construct option (python) dict similar to the option object in javascript 2. input option dict using set_dict_options (for all the option details please ref to highcharts API: http://api.highcharts.com/highcharts#) """ options = { 'xAxis': { 'plotBands': [{ 'color': '#FCFFC5', 'from': 2, 'to': 4 }, { 'color': '#FCFFC5', 'from': 6, 'to': 8 }, { 'color': '#FCFFC5', 'from': 10, 'to': 12 }] } } H.set_dict_options( options) # input option object using set_dict_options method H # showing the chart on ipython H.save_file('highcharts' ) # save result as .html file with input name (and location path)
def make_inverted_error_highcharts(predictions, folder_path): """Creates htmls with actual, prediction, and error plots with yearly aggregation. Args: actual_data (dictionary): Real data with structure {Aggregation: pandas DataFrame}. predictions (dictionary): Predictions with structure {Year: {Aggregation: pandas DataFrame}}. folder_path (string): Path to folder where html files are to be saved. """ # Define validation years to check error with # Create dictionary mapping year predicted upon to list of lists of applied weather years and prediction errors inverted_dict = {} for applied_weather_year in sorted(predictions): df = predictions[applied_weather_year]['Yearly'] for predicted_year in df.Date: if int(applied_weather_year) > 2016: try: inverted_dict[str(predicted_year)].append([ str(int(applied_weather_year) + predicted_year - 2015), float(df.loc[df['Date'] == int( predicted_year)].Prediction) ]) except KeyError: inverted_dict[str(predicted_year)] = [[ str(int(applied_weather_year) + predicted_year - 2015), float(df.loc[df['Date'] == int( predicted_year)].Prediction) ]] # Create inverted error plots for year in sorted(inverted_dict): # Define chart dimensions H = Highchart(width=1920, height=800) # Initialize options options = { 'chart': { 'type': 'column' }, 'title': { 'text': 'URD Fault Prediction Error for {} with offset weather applied (Only for years in validation set)' .format(year) }, 'subtitle': { 'text': 'Click the links above to change the year predicted on.' }, 'xAxis': { 'type': 'category', 'title': { 'text': '' } }, 'yAxis': [{ 'gridLineWidth': 0, 'title': { 'text': '', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'labels': { 'format': '{value}', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'opposite': False }], 'tooltip': { 'shared': True, 'pointFormat': '{series.name}: <b>{point.y:.0f}</b> <br />' }, 'legend': { 'layout': 'vertical', 'align': 'left', 'x': 80, 'verticalAlign': 'top', 'y': 55, 'floating': True, 'backgroundColor': "(Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'" }, 'plotOptions': { 'series': { 'borderWidth': 0, 'dataLabels': { 'enabled': False, 'format': '{point.y:,.0f}', 'formatter': 'function() {if (this.y != 0) {return Math.round(this.y)} else {return null;}}' } } }, } # Plot with highcharts H.set_dict_options(options) H.add_data_set(inverted_dict[year], 'column', 'Error', dataLabels={'enabled': True}, color='#777', animation=True) # Export plot filename = os.path.join(folder_path, 'URD_Prediction_Errors_{}'.format(year)) try: H.save_file(filename) except IOError: # Raised if folder_path directory doesn't exist os.mkdir(folder_path) H.save_file(filename) # Open plot and replace beginning of file with links headstring = "<center> " for year in sorted(inverted_dict): filename = os.path.join(folder_path, 'URD_Prediction_Errors_{}.html'.format(year)) headstring += '<a href="{0}.html" style="color: #555; font-size: 24px">{1}</a>  '.format( filename[:-5], year) headstring += " </center>" for year in sorted(inverted_dict): filename = os.path.join(folder_path, 'URD_Prediction_Errors_{}.html'.format(year)) with open(filename, 'r') as f: content = f.read() with open(filename, 'w') as f: f.write(headstring) f.write(content)
def make_highcharts(actual_data, predictions, folder_path): """Creates htmls with actual, prediction, and error plots with yearly aggregation. Args: actual_data (dictionary): Real data with structure {Aggregation: pandas DataFrame}. predictions (dictionary): Predictions with structure {Year: {Aggregation: pandas DataFrame}}. folder_path (string): Path to folder where html files are to be saved. """ # Convert real data to list of lists for plotting with highcharts actual = actual_data['Time', 'Inertial'].values.tolist() # Initialize list of years l_years = [] # Create yearly plots for year in sorted(predictions): df = predictions[year]['Yearly'] if year == '.Actual': year = 'Actual' l_years.append(year) # Define chart dimensions H = Highchart(width=1920, height=800) # Initialize options options = { 'chart': { 'type': 'column' }, 'title': { 'text': 'URD Fault Predictions with {} Weather Applied to 2016 Data'. format(year) }, 'subtitle': { 'text': 'Click the links above to change the weather offset.' }, 'xAxis': { 'type': 'category', 'title': { 'text': '' } }, 'yAxis': [{ 'gridLineWidth': 0, 'title': { 'text': '', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'labels': { 'format': '{value}', 'style': { 'color': 'Highcharts.getOptions().colors[1]' } }, 'opposite': False }], 'tooltip': { 'shared': True, 'pointFormat': '{series.name}: <b>{point.y:.0f}</b> <br />' }, 'legend': { 'layout': 'vertical', 'align': 'left', 'x': 80, 'verticalAlign': 'top', 'y': 55, 'floating': True, 'backgroundColor': "(Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'" }, 'plotOptions': { 'series': { 'borderWidth': 0, 'dataLabels': { 'enabled': False, # 'format': '{point.y:,.0f}', 'formatter': 'function() {if (this.y != 0) {return Math.round(this.y)} else {return null;}}' } } }, } # Convert pandas dataframe to lists of lists for plotting with highcharts error = df.reset_index()[['Date', 'Error']].values.tolist() prediction = df.reset_index()[['Date', 'Prediction']].values.tolist() # Plot with highcharts H.set_dict_options(options) H.add_data_set(actual, 'line', 'Actual', marker={'enabled': False}, color='#A00', animation=False) H.add_data_set(prediction, 'line', 'Prediction', marker={'enabled': False}, dashStyle='dash', color='#00A', animation=False) H.add_data_set(error, 'column', 'Error', dataLabels={'enabled': True}, color='#777', animation=False) # Export plot filename = os.path.join(folder_path, 'URD_Prediction_{}_Weather'.format(year)) try: H.save_file(filename) except IOError: # Raised if folder_path directory doesn't exist os.mkdir(folder_path) H.save_file(filename) # Open plot and replace beginning of file with links headstring = "<center> " for year in l_years: filename = os.path.join(folder_path, 'URD_Prediction_{}_Weather.html'.format(year)) headstring += '<a href="{0}.html" style="color: #555; font-size: 24px">{1}</a>  '.format( filename[:-5], year) headstring += " </center>" for year in l_years: filename = os.path.join(folder_path, 'URD_Prediction_{}_Weather.html'.format(year)) with open(filename, 'r') as f: content = f.read() with open(filename, 'w') as f: f.write(headstring) f.write(content)
hc = Highchart() hc.set_options( 'yAxis', { 'categories': dataset_names, 'min': 0, 'max': len(dataset_names) - 1, 'title': { 'text': '' }, 'gridLineWidth': 0 }) hc.set_options('title', {'text': 'example'}) for s in chart.series_list(): s['supress_errors'] = True # otherwise setting attr 'linkTo' raise error hc.add_data_set(**s) hc.save_file(filename='example_horizontal') ''' Plot vertical chart to file <vertical.html> ''' hc = Highchart() hc.set_options('chart', {'inverted': True}) hc.set_options('xAxis', {'reversed': False}) hc.set_options( 'yAxis', { 'categories': dataset_names, 'min': 0, 'max': len(dataset_names) - 1, 'title': { 'text': '' }, 'gridLineWidth': 0
[1550534400000, 229.0], [1550620800000, 234.5], [1550707200000, 236.5], [1550793600000, 236.5], [1551052800000, 238.0], [1551139200000, 239.5], [1551225600000, 239.0], [1551657600000, 235.5], [1551744000000, 233.0], [1551830400000, 234.0], [1551916800000, 234.0], [1552003200000, 230.0], [1552262400000, 230.5], [1552348800000, 235.5], [1552435200000, 237.0], [1552521600000, 234.5], [1552608000000, 239.0], [1552867200000, 241.0], [1552953600000, 240.5], [1553040000000, 242.0], [1553126400000, 245.5], [1553212800000, 248.5], [1553472000000, 241.5], [1553558400000, 244.0], [1553644800000, 241.5], [1553731200000, 242.0], [1553817600000, 245.5], [1554076800000, 245.5], [1554163200000, 246.0], [1554249600000, 246.5], [1554681600000, 253.0], [1554768000000, 254.0], [1554854400000, 254.0], [1554940800000, 252.0], [1555027200000, 252.0], [1555286400000, 255.5], [1555372800000, 257.0], [1555459200000, 261.5], [1555545600000, 264.5], [1555632000000, 264.5], [1555891200000, 266.0], [1555977600000, 268.0], [1556064000000, 269.0], [1556150400000, 267.5], [1556236800000, 260.0], [1556496000000, 259.5], [1556582400000, 259.0], [1556755200000, 259.0], [1556841600000, 265.0], [1557100800000, 259.0], [1557187200000, 262.5], [1557273600000, 260.0], [1557360000000, 256.5], [1557446400000, 256.0], [1557705600000, 250.5], [1557792000000, 248.5], [1557878400000, 249.0], [1557964800000, 247.0], [1558051200000, 241.5], [1558310400000, 238.0], [1558396800000, 234.0], [1558483200000, 238.0], [1558569600000, 230.0], [1558656000000, 233.0], [1558915200000, 231.0], [1559001600000, 230.5], [1559088000000, 229.5], [1559174400000, 231.0], [1559260800000, 235.5], [1559520000000, 238.0], [1559606400000, 233.0], [1559692800000, 235.0], [1559779200000, 232.0], [1560124800000, 240.0], [1560211200000, 244.5], [1560297600000, 246.0], [1560384000000, 240.0], [1560470400000, 236.0]] chart.add_data_set(data, 'line', '股價', tooltip={'valueDecimals': 2}) chart.save_file()
from highcharts import Highchart # A chart is the container that your data will be rendered in, it can (obviously) support multiple data series within it. chart = Highchart() # Adding a series requires at minimum an array of data points. # You can also change the series type, the name, or other series options as kwargs. data = range(1,20) chart.add_data_set(data, series_type='line', name='Example Series') # This will generate and save a .html file at the location you assign chart.save_file()
'maxPadding': 0.05, 'showLastLabel': True }, 'yAxis': { 'title': { 'text': 'Temperature' }, 'labels': { 'formatter': "function () {\ return this.value + '°';\ }" }, 'lineWidth': 2 }, 'legend': { 'enabled': False }, 'tooltip': { 'headerFormat': '<b>{series.name}</b><br/>', 'pointFormat': '{point.x} km: {point.y}°C' } } chart.set_dict_options(options) data = [[0, 15], [10, -50], [20, -56.5], [30, -46.5], [40, -22.1], [50, -2.5], [60, -27.7], [70, -55.7], [80, -76.5]] chart.add_data_set(data, 'spline', 'Temperature', marker={'enabled': False}) chart.save_file(results)
H.set_options('xAxis', {'events': {'pointBreak': 'function(e){return}'}}) H.set_options('chart', {'style': {'fontFamily': 'Lucida Grande, sans-serif', "fontfontSize": '12px'}}) H.set_options('chart', {'style': {"fontfontSize": '22px'}}) H.set_options('chart', {'resetZoomButton': {'position': {'x': 10}}}) H.set_options('chart', {'resetZoomButton': {'relativeTo': 'chart'}}) """ Set up highchart options using 2. set_dict_options method: set_dict_options(options) option is a (python) dict for options settings The way to use this method is very similar to the options object as on highcharts docs: http://www.highcharts.com/docs/getting-started/how-to-set-options 1. construct option (python) dict similar to the option object in javascript 2. input option dict using set_dict_options (for all the option details please ref to highcharts API: http://api.highcharts.com/highcharts#) """ options = { 'xAxis':{ 'plotBands': [{'color': '#FCFFC5', 'from': 2, 'to': 4}, {'color': '#FCFFC5', 'from': 6, 'to': 8}, {'color': '#FCFFC5', 'from': 10, 'to': 12}] } } H.set_dict_options(options) # input option object using set_dict_options method H # showing the chart on ipython H.save_file('highcharts') # save result as .html file with input name (and location path)
'radius': 5, 'states': { 'hover': { 'enabled': True, 'lineColor': 'rgb(100,100,100)' } } }, 'states': { 'hover': { 'marker': { 'enabled': False } } }, 'tooltip': { 'headerFormat': '<b>{series.name}</b><br>', # 'pointFormat': '{point.name}:{point.x} , {point.y} ' 'pointFormat': 'Student Srid:{point.name} ' } } }, } H.set_dict_options(options) for i in range(len(name)): H.add_data_set(result[i], 'scatter', name[i]) #H.add_data_set(data2, 'scatter', 'Male', color='rgba(119, 152, 191, .5)') H.htmlcontent H.save_file()
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()
# 'legend': { # 'layout': 'vertical', # 'align': 'right', # 'verticalAlign': 'top', # 'x': -40, # 'y': 80, # 'floating': True, # 'borderWidth': 1, # 'backgroundColor': "((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF')", # 'shadow': True, # }, } H.set_dict_options(options) H.add_data_set(list([i[1] for i in z0]),'bar','网友地区分布top20') H.save_file('people_dirct') ''' ************************************************************************************** 评论粉丝性别分布可视化; ''' ''' 从MongoDB数据库中提取数据;;; ''' gender_list =[] for i in item_info.find(): if i['gender'] ==0: gender_list.append('性别未知') elif i['gender'] == 1: gender_list.append('男') else: gender_list.append('女')
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 main(): """ main function read all files , make plots and process them """ ## data location, relative dir = config.training_dir ## run over all files with '*.mat' file_type = '*.mat' # plotting setup charts = Highchart() options = { 'chart': { 'type': 'line' }, 'title': { 'text': 'test' }, 'xAxis': { 'type': 'float', 'title': { 'enabled': True, 'text': 'time (ms)' } }, 'yAxis': { 'type': 'int', 'title': { 'enabled': True, 'text': 'EEG signal' } } } charts.set_dict_options(options) list_dict = [] target_list = [] # get a list of all files to be processed file_list = glob.glob(dir + file_type) for f in file_list: name = f[-9:-4] df = convert_mat(f, config.resample_size) # create lables that will eventually use in the clasification algorithm if "1.mat" in f: target = 1 else: target = 0 values_dict = {} # get summary statistics of each channel in the EGG, save them to a list of dictionaries for i in df.columns: values_dict[i + '_mean'] = df[i].mean values_dict[i + '_median'] = df[i].median values_dict[i + '_std'] = df[i].std values_dict[i + '_min'] = df[i].min values_dict[i + '_max'] = df[i].max values_dict[i + '_kurt'] = df[i].kurt values_dict[i + '_kurtosis'] = df[i].kurtosis values_dict[i + '_skew'] = df[i].skew values_dict[i + '_var'] = df[i].var # plot each channel data = df[i].tolist() data = [float(j) for j in data] charts.add_data_set(data, 'line', i) # append summary of each measurement list_dict.append(values_dict) target_list.append(target) charts.save_file(config.out_dir + name) # get final data frame summary_df = pd.DataFrame.from_records(list_dict) summary_df['target'] = pd.Series(target_list) summary_df.to_csv(config.out_dir + 'Summary_Stats_df_Training1.csv')
'created_at'] or 'Oct' in tweet[ 'created_at'] or 'Nov' in tweet[ 'created_at'] or 'Dec' in tweet['created_at']: y16 += 1 elif tweet['created_at'][-4:] == '2017': if 'Jan' in tweet['created_at'] or 'Feb' in tweet[ 'created_at'] or 'Mar' in tweet[ 'created_at'] or 'Apr' in tweet[ 'created_at'] or 'May' in tweet[ 'created_at'] or 'Jun' in tweet['created_at']: y17 += 1 elif 'Jul' in tweet['created_at'] or 'Aug' in tweet[ 'created_at'] or 'Sept' in tweet[ 'created_at'] or 'Oct' in tweet[ 'created_at'] or 'Nov' in tweet[ 'created_at'] or 'Dec' in tweet['created_at']: y18 += 1 if (len(tweets)): earlier_tweet_id = sorted(tweet_id_list)[0] else: tweet_count = max_count g_data = [ y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17, y18 ] chart.set_dict_options(options) chart.add_data_set(g_data, 'line', 'PK') chart.save_file('./highcharts')
def main(): pwd = str(os.getcwd()) home = os.path.abspath(os.path.join(pwd, os.pardir)) # data location, relative. dir = '/data/train_1/' # define test file, layout is from when i wanted to iterate over all files # to run over all files change line to '*.mat' file_type = '1_920_0.mat' file_list = glob.glob(home + dir + file_type) for f in file_list: name = f[:-4] name = name.split('/') name = name[len(name) - 1] # load .mat file mat = scipy.io.loadmat(f) headers = [ 'channel0', 'channel1', 'channel2', 'channel3', 'channel4', 'channel5', 'channel6', 'channel7', 'channel8', 'channel9', 'channel10', 'channel11', 'channel12', 'channel13', 'channel14', 'channel15' ] # get actual data from the .mat file channels_data = mat['dataStruct'][0][0][0] # resample file rs_data = resample(channels_data, 3000, axis=0) df = pandas.DataFrame(rs_data, columns=headers) charts = Highchart() options = { 'chart': { 'type': 'line', 'zoomType': 'x' }, 'title': { 'text': 'test' }, 'xAxis': { 'type': 'float', 'title': { 'enabled': True, 'text': 'time (ms)' } }, 'yAxis': [{ 'type': 'int', 'title': { 'enabled': True, 'text': 'EEG signal' }, 'opposite': False }, { 'type': 'int', 'title': { 'enabled': True, 'text': 'variance' }, 'opposite': True }] } charts.set_dict_options(options) for i in headers: data = df[i].tolist() mean = df[i].rolling(window=2).mean() d_var = df[i].rolling(window=2).var() d_var = d_var.dropna() mean = mean.dropna() data = [float(j) for j in data] disp = [] d_var = [float(j) for j in d_var] mean = [float(j) for j in mean] for k in range(len(mean)): disp.append(d_var[k] / mean[k]) charts.add_data_set(data, 'line', i) name = str(i) + '_disp' charts.add_data_set(disp, 'line', name, yAxis=1) charts.save_file(name)
}, 'legend': { 'enabled': True }, 'xAxis': { 'categories': [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], 'title': { 'text': 'Months of the year' } }, 'yAxis': { 'title': { 'text': 'Number of followers' } }, } data1 = [7, 7, 9, 14, 18, 21, 25, 26, 30, 55, 62, 85] data2 = [11, 17, 22, 25, 56, 76, 91, 102, 150] data3 = [3, 4, 5, 8, 11, 15, 17, 36, 42, 103, 126, 148] chart.set_dict_options(options) chart.add_data_set(data1, 'line', 'User 1') chart.add_data_set(data2, 'line', 'User 2') chart.add_data_set(data3, 'line', 'User 3') chart.save_file('./line-highcharts')
}, 'title': { 'text': 'Top 10 Hashtags' }, 'xAxis': { 'categories': words }, 'yAxis': { 'title': { 'text': 'Number of times mentioned' } }, } chart.set_dict_options(options) chart.add_data_set(data1, 'column', 'Count') chart.save_file('./column-highcharts') chart2 = Highchart() options = { 'chart': { 'type': 'column' }, 'title': { 'text': 'Original Tweets and Retweeted Tweets' }, 'xAxis': { 'categories': ['Original', 'Retweets'] }, 'yAxis': { 'title': { 'text': 'Number of tweets'
}, 'legend': { 'enabled': True }, 'xAxis': { 'categories': [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], 'title': { 'text': 'Months of the year' } }, 'yAxis': { 'title': { 'text': 'Number of followers' } }, } data1 = [7, 7, 9, 14, 18, 21, 25, 26, 30, 55, 62, 85] data2 = [11, 17, 22, 25, 56, 76, 91, 102, 150] data3 = [3, 4, 5, 8, 11, 15, 17, 36, 42, 103, 126, 148] chart.set_dict_options(options) chart.add_data_set(data1, 'line', 'User 1') # data, type_of_chart, legend_text chart.add_data_set(data2, 'line', 'User 2') chart.add_data_set(data3, 'line', 'User 3') chart.save_file('./line-highcharts') # write to the file and save
'color': 'blue' }, 'onArea':True } } } } H_area.set_dict_options(options) H_area.add_data_set(Joy, 'area', 'joy',color = 'rgb(241,199,28)') H_area.add_data_set(Anger, 'area', 'anger',color ='rgb(207,46,17)') H_area.add_data_set(Disgust, 'area', 'disgust',color ='rgb(118,181,92)') H_area.add_data_set(Fear, 'area', 'fear',color ='rgb(151,77,193)') H_area.add_data_set(Sadness, 'area', 'sadness',color ='rgb(46,116,213)') H_area.save_file('output_charts_area') options_column = { 'chart': { 'type': 'column', 'renderTo': 'container_column', 'options3d': { 'enabled': True, 'alpha': 15, 'beta': 15, 'viewDistance': 25, 'depth': 40 } }, 'title': { 'text': 'Percentage of Emotions to Each Sentence'
'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] data3 = [973, 914, 4054, 732, 34] data4 = [1052, 954, 4250, 740, 38] chart.set_dict_options(options) # add options to the chart object chart.add_data_set(data1, 'bar', 'Day 1') # data, type_of_chart, legend_text chart.add_data_set(data2, 'bar', 'Day 2') chart.add_data_set(data3, 'bar', 'Day 3') chart.add_data_set(data4, 'bar', 'Day 4') chart.save_file('./highcharts-bar' ) # it will crete an html file. Used to save the html file
}, series: [{ name: 'Words', data: [ { name: 'Joy', y: c1 }, { name: 'Sadness', y: c2, sliced: true, selected: true }, { name: 'Anger', y: c3 }, { name: 'Fear', y: c4 }, { name: 'Disgust', y: c5 }, { name: 'Suprise', y: c6 }, { name: 'Shame', y: c7 }, { name: 'Guilt', y: c8 }, { name: 'Happy', y: c9 }, { name: 'Embarassment', y: c10 }, { name: 'Confuse', y: c11 } ] }] }); chart.save_file('templates/pie_highchart') if __name__ == '__main__': create_graph()