def define_plot_parameters(list): # Input is a List of format: # list_plot_parameters = [ x_data1, y_data1, # plot_title1, x_axis_title1, y_axis_title1, # plot_size_height1, plot_size_width1, # legend_location ] # The parameters have to be controlled like this in a callback to allow # for them to be adjusted. Otherwise the plot parameters are not # interactive. # Yes! - p1.xaxis.axis_label = 'X_axis_title' # No! - p1 = figure(x_axis_label = 'X_axis_title') p1.title.text = list[2] p1.xaxis.axis_label = list[3] p1.yaxis.axis_label = list[4] p1.plot_height = list[5] p1.plot_width = list[6] p1.legend.location = list[7] # If the user wants to plot an axis as datetime then the axis needs to # be reformatted. Will do this by checking if the x_data1/y_data1 is # =='adate'. # NB: This only works if 'adate' is used as the name for the date column # and also that this is the only date column. if list[0] == 'adate': p1.xaxis.formatter = DatetimeTickFormatter(days=['%d/%m', '%a%d']) else: p1.xaxis.formatter = BasicTickFormatter() if list[1] == 'adate': p1.yaxis.formatter = DatetimeTickFormatter(days=['%d/%m', '%a%d']) else: p1.yaxis.formatter = BasicTickFormatter() return
def make_plot(srs, colsource, title): tools = "hover,box_select" p = figure(plot_height=300, tools=tools, toolbar_location='left', x_axis_type="datetime", x_axis_location="above", background_fill_color="#efefef", x_range=(srs[400], srs[3000]), output_backend="webgl", title=title) p.xaxis.axis_label = 'Timestamp' lst_col = [ 'x', 'y', 'z' ] # + df_signal.columns.difference(['timestamp', 'x', 'y', 'z']).tolist() for (colr, leg) in zip(lst_colors, lst_col): p.line('timestamp', leg, color=colr, legend_label=leg, source=colsource, name='wave') p.scatter('timestamp', leg, color=None, legend_label=leg, source=colsource, name='wave') p.xaxis.formatter = DatetimeTickFormatter(days=["%m/%d %H:%M"], months=["%m/%d %H:%M"], hours=["%m/%d %H:%M"], minutes=["%m/%d %H:%M"]) hover = p.select(dict(type=HoverTool)) hover.tooltips = [("timestamp", "@timestamp_str")] select = figure( title= "Drag the middle and edges of the selection box to change the range above", plot_height=130, y_range=p.y_range, x_axis_type="datetime", y_axis_type=None, tools="", toolbar_location=None, background_fill_color="#efefef", output_backend="webgl") for (colr, leg) in zip(lst_colors, lst_col): select.line('timestamp', leg, color=colr, source=colsource) select.ygrid.grid_line_color = None select.xaxis.formatter = DatetimeTickFormatter(days=["%m/%d %H:%M"], months=["%m/%d %H:%M"], hours=["%m/%d %H:%M"], minutes=["%m/%d %H:%M"]) return p, select
def _get_log_plots(log_data): time_stamp = log_data[0] height = log_data[1] yaw = _shift_yaw(log_data[2]) pitch = log_data[3] roll = log_data[4] is_video = log_data[5] height_plot = figure(title='Height', plot_width=700, plot_height=500) height_plot.xaxis.formatter = DatetimeTickFormatter(minsec=['%H:%M:%S'], minutes=['%H:%M:%S'], hourmin=['%H:%M:%S']) height_plot.yaxis.axis_label = 'Meters' height_plot.line(time_stamp, height) yaw_plot = figure(title='Yaw', plot_width=700, plot_height=500, x_range=height_plot.x_range) yaw_plot.xaxis.formatter = DatetimeTickFormatter(minsec=['%H:%M:%S'], minutes=['%H:%M:%S'], hourmin=['%H:%M:%S']) yaw_plot.yaxis.axis_label = 'Degrees' yaw_plot.line(time_stamp, yaw) pitch_plot = figure(title='Pitch', plot_width=700, plot_height=500, x_range=height_plot.x_range) pitch_plot.xaxis.formatter = DatetimeTickFormatter(minsec=['%H:%M:%S'], minutes=['%H:%M:%S'], hourmin=['%H:%M:%S']) pitch_plot.yaxis.axis_label = 'Degrees' pitch_plot.line(time_stamp, pitch) roll_plot = figure(title='Roll', plot_width=700, plot_height=500, x_range=height_plot.x_range) roll_plot.xaxis.formatter = DatetimeTickFormatter(minsec=['%H:%M:%S'], minutes=['%H:%M:%S'], hourmin=['%H:%M:%S']) roll_plot.yaxis.axis_label = 'Degrees' roll_plot.line(time_stamp, roll) for video_range in get_video_ranges(is_video, time_stamp): video_box1 = BoxAnnotation(left=video_range[0], right=video_range[1], fill_color='#cccccc') video_box2 = BoxAnnotation(left=video_range[0], right=video_range[1], fill_color='#cccccc') video_box3 = BoxAnnotation(left=video_range[0], right=video_range[1], fill_color='#cccccc') video_box4 = BoxAnnotation(left=video_range[0], right=video_range[1], fill_color='#cccccc') height_plot.add_layout(video_box1) yaw_plot.add_layout(video_box2) pitch_plot.add_layout(video_box3) roll_plot.add_layout(video_box4) return height_plot, yaw_plot, pitch_plot, roll_plot
def index(): if request.method == 'POST': print('if') elo_range = request.form['service'] opening_original = request.form['name'] opening = "['" + opening_original.replace(",", "', '") + "']" g = Games('/data/lichess.db', elo=elo_range, opening=opening) x = g.df.date.tolist() x = [datetime.strptime(d, '%Y.%m.%d') for d in x] y = g.df.opening_percentage_played.tolist() chart_title = "Popularity of " + opening_original + " by " + elo_range + " ELOs" p = figure(title=chart_title, x_axis_type="datetime") p.xaxis.formatter = DatetimeTickFormatter(days="%d-%b") p.line(x, y, color="darkorange", line_width=3) p.yaxis.axis_label = "% of games beginning with " + opening_original p.yaxis.axis_label_text_color = "#662900" p.xaxis.axis_label = "Date" p.xaxis.axis_label_text_color = "#662900" script1, div1 = components(p) cdn_js = CDN.js_files cdn_css = CDN.css_files return render_template('index.html', script1=script1, div1=div1, cdn_css=cdn_css, cnd_js=cdn_js) else: print('else') g = Games('/data/lichess.db', elo='ALL', opening="['d4', 'd5', 'c4']") x = g.df.date.tolist() x = [datetime.strptime(d, '%Y.%m.%d') for d in x] y = g.df.opening_percentage_played.tolist() chart_title = "Popularity of 1. d4 d5 2. c4 by All ELOs" p = figure(title=chart_title, x_axis_type="datetime") p.xaxis.formatter = DatetimeTickFormatter(days="%d-%b") p.line(x, y, color="darkorange", line_width=3) p.yaxis.axis_label = "% of games beginning with 1. d4 d5 2. c4 " p.yaxis.axis_label_text_color = "#662900" p.xaxis.axis_label = "Date" p.xaxis.axis_label_text_color = "#662900" script1, div1 = components(p) cdn_js = CDN.js_files cdn_css = CDN.css_files return render_template('index.html', script1=script1, div1=div1, cdn_css=cdn_css, cnd_js=cdn_js)
def doubleline_KPI_plot(line_name1, line_name2, plot_name): source_KPI = ColumnDataSource(DetailKPI) ymin_1st = DetailKPI[line_name1].min() ymax_1st = DetailKPI[line_name1].max() ymin_2nd = DetailKPI[line_name2].min() ymax_2nd = DetailKPI[line_name2].max() # pass plot_name (string) to file_name that to be used for saveing as. file_name = plot_name # the typ of plot_name is now converted to figure, other than string. plot_name = figure(x_axis_label='Date', y_axis_label=line_name1, y_range=(ymin_1st, ymax_1st), tools=toolkit) plot_name.line('Date', line_name1,source=source_KPI, color=lineColor, hover_color=HoverColor) plot_name.circle('Date', line_name1, source=source_KPI, color=lineColor,hover_color=HoverColor) # Setting the second y axis range name and range plot_name.extra_y_ranges = {line_name2: Range1d(start=ymin_2nd, end=ymax_2nd)} # Adding the second axis to the plot. plot_name.add_layout(LinearAxis(y_range_name=line_name2,axis_label= line_name2), 'right') plot_name.line('Date', line_name2, source=source_KPI, y_range_name=line_name2,hover_color=HoverColor) plot_name.circle('Date', line_name2, source=source_KPI,y_range_name=line_name2,hover_color=HoverColor) #plot_name.title.text = line_name plot_name.xaxis.formatter=DatetimeTickFormatter(days = formatter_days) #show(plot_name) return plot_name
def plot_scatter(src_scatter): # create plot and add tools hover = HoverTool(tooltips=[('Date', '@date{%F}'), ("Category", "@category"), ("Counts", "@counts")], formatters={'date': 'datetime'}) p = figure(tools=[hover, 'box_zoom,save,pan,reset,help'], x_axis_type="datetime", x_axis_label='Date', y_axis_label='Counts', plot_width=800, plot_height=350) p.scatter(x='date', y='counts', color='color_by_cat', legend_field='category', source=src_scatter, alpha=0.8, size=5) p.legend.location = "top_right" p.xaxis.formatter = DatetimeTickFormatter(months=['%Y-%m'], ) return p
def add_plot(stockStat, conf): p_list = [] logging.info("############################", type(conf["dic"])) # 循环 多个line 信息。 for key, val in enumerate(conf["dic"]): logging.info(key) logging.info(val) p1 = figure(width=1000, height=150, x_axis_type="datetime") # add renderers stockStat["date"] = pd.to_datetime(stockStat.index.values) # ["volume","volume_delta"] # 设置20个颜色循环,显示0 2 4 6 号序列。 p1.line(stockStat["date"], stockStat[val], color=Category20[20][key * 2]) # Set date format for x axis 格式化。 p1.xaxis.formatter = DatetimeTickFormatter(hours=["%Y-%m-%d"], days=["%Y-%m-%d"], months=["%Y-%m-%d"], years=["%Y-%m-%d"]) # p1.xaxis.major_label_orientation = radians(30) #可以旋转一个角度。 p_list.append([p1]) gp = gridplot(p_list) script, div = components(gp) return { "script": script, "div": div, "title": conf["title"], "desc": conf["desc"] }
def draw_humid_graph(data): p2 = figure(x_axis_type="datetime", title="Humidity Record", plot_width=600, plot_height=600) p2.xaxis.axis_label = 'Time' p2.yaxis.axis_label = 'Humidity' p2.line(data['time'], data['humid'], color='#B2DF8A', legend='Humidity', line_width=2) p2.xaxis.formatter = DatetimeTickFormatter(minsec=['%d %B %Y at %H:%M'], hours=["%d %B %Y at %H:%M"], minutes=['%d %B %Y at %H:%M'], hourmin=['%d %B %Y at %H:%M'], days=['%d %B %Y at %H:%M'], months=['%d %B %Y at %H:%M'], years=['%d %B %Y a5 %H:%M']) p2.legend.location = "top_left" p2.xaxis.major_label_orientation = pi / 3 output_file( '/home/pi/RaspberryPi---A1---s3608452/WebInterface/templates/HumidityLogger/humid_graph.html' ) save(p2)
def line_time(dataframe: pd.DataFrame, data_inicial, data_final): if ('hora' in dataframe.columns)==True: dataframe["data"] = pd.to_datetime(dataframe.data) + pd.to_timedelta(list(map(int, dataframe.hora)), unit='h') colors = set_color_unproportional(dataframe.cluster_label.unique()) title = "Conversão time series plot in the period: " + str(data_inicial) + "-" + str(data_final) plots = [] for cluster_label, color in zip(range(0, dataframe.cluster_label.nunique()), colors): p = figure(title="", toolbar_location=None, tools="", x_axis_label="datatime", y_axis_label="Conversão", plot_width=1300) date = pd.to_datetime(dataframe.loc[dataframe["cluster_label"] == str(cluster_label)]['data']) convertido = dataframe.loc[dataframe["cluster_label"] == str(cluster_label)]['convertido'] lengenda = "cluster " + str(cluster_label) sample_size = len(date[::1]) limite_central, limite_superior, limite_inferior = get_bootstrap_confidencial_interval(convertido) p.line(date, convertido, line_color=color, line_width=2, legend=lengenda) p.circle(date[::1], np.repeat(limite_central, sample_size), size=3, fill_color="black", line_color="black") p.circle(date[::1], np.repeat(limite_inferior, sample_size), size=3, fill_color="black", line_color="black") p.circle(date[::1], np.repeat(limite_superior, sample_size), size=3, fill_color="black", line_color="black", legend= "bootstrap confidential intervals") p.xaxis.formatter = DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) p.xaxis.major_label_orientation = 3.1614 / 4 plots.append(p) return column(plots)
def plot_us_cases_and_deaths(state='Florida', show_estimated=None): file_name = '../data/us_confirmed_pivot_data.csv' with open(file_name) as file: reader = csv.DictReader(file) actual_dates = [datetime.strptime(row['Date'], '%Y-%m-%d') for row in reader if row['Date'] not in ['(blank)', 'Grand Total']] confirmed = us_confirmed(state) deaths = us_deaths(state) plot = figure(width=500, plot_height=600, title="COVID-19 {} Cases, 2020".format(state.capitalize())) # model if show_estimated: model = confirmed_model(state, us_case=True) plot.line(actual_dates, model, line_width=2, line_color='red', line_dash='dashed', legend_label="confirmed (model)") # data plot.yaxis.axis_label = "# of Cases" plot.xaxis.formatter = DatetimeTickFormatter(days="%m/%d") plot.line(actual_dates, confirmed, line_width=2, line_color='red', legend_label='confirmed') plot.line(actual_dates, deaths, line_width=2, line_color='blue', legend_label='deaths') plot.legend.location = "top_left" return plot
def make_plot(source, country='Spain', variable='cases'): p = figure(plot_width=800, plot_height=800, title=country, tooltips=tooltips) lenght_for_forecast = source.data['forecast'].__len__() x = source.data['data_labels'][-lenght_for_forecast:] y = source.data['y'] upper_band = source.data['conf_int_upper_bound'] lower_band = source.data['conf_int_lower_bound'] # Bands are drawn as patches. That is, a polygon specified by a series of 2D points # Because points are specified in clockwise order, the lower band needs to be reverse (Hence the [::-1]) xs = np.concatenate([x, x[::-1]]) ys = np.concatenate([upper_band, lower_band[::-1]]) p.line(x, source.data['forecast'], color='blue', legend_label='Forecast') p.circle(x='data_labels', y='forecast', source=source, fill_color="blue", size=8) p.line(x, upper_band, color='blue') p.line(x, lower_band, color='blue') p.line(x, y, legend_label='Real Values', color='black') p.circle(x='data_labels', y='y', source=source, fill_color="black", size=8) p.patch(x=xs, y=ys, fill_alpha=0.3, line_alpha=0, legend_label="Interval of Confidence") p.xaxis.formatter = DatetimeTickFormatter(days=["%d/%m/%Y"]) p.xaxis.major_label_orientation = math.pi / 2 p.yaxis.axis_label = '# of new {}'.format(variable) p.legend.location = 'top_left' return p
def newrelic_get_error_rate(self, msg, region): """ Get response of application for a given region """ token = self.config['newrelic_token'] app_id = self.config['app_ids'][region] metric_name = 'Errors/all' data = Applications(token).metric_data( app_id, ['HttpDispatcher', 'Errors/all', 'OtherTransaction/all'], ['error_count', 'call_count']) ot_timeslices = [] for metric in data['metric_data']['metrics']: if metric['name'] == 'HttpDispatcher': hd_timeslices = metric['timeslices'] if metric['name'] == 'Errors/all': ea_timeslices = metric['timeslices'] if metric['name'] == 'OtherTransaction/all': ot_timeslices = metric['timeslices'] x = [] y = [] hd_timeslices.reverse() ot_timeslices.reverse() for ea_timeslice in ea_timeslices: x.append(arrow.get(ea_timeslice['to']).to('Asia/Kolkata').time()) hd_timeslice = hd_timeslices.pop() if len(ot_timeslices): ot_timeslice = ot_timeslices.pop() else: ot_timeslice = {'values': {'call_count': 0}} error_rate = 100 * ea_timeslice['values']['error_count'] / float( hd_timeslice['values']['call_count'] + ot_timeslice['values']['call_count']) y.append(error_rate) plot = figure(title="App Error Rate(%)", plot_width=800, plot_height=400, x_axis_label='Time', y_axis_label='Error Rate(%)', x_axis_type='datetime') plot.xaxis.formatter = DatetimeTickFormatter(minutes=["%H:%M"]) plot.line(x, y, legend="Response Time.", line_width=2) image_name = "app_error_rate_{0}.png".format(uuid.uuid4().hex) image_file = "/tmp/{0}".format(image_name) room = msg.frm.room token = self.bot_config.BOT_IDENTITY['token'] image = export_png(plot, filename=image_file) filepath = image hipchat_file(token, room, filepath, host='api.hipchat.com') return "I hope this helps?"
def create_figure_stock(stock_current_feature_name): if stock_current_feature_name == 'TSLA': data_stock = TSLA elif stock_current_feature_name == 'GOOG': data_stock = GOOG elif stock_current_feature_name == 'INT': data_stock = INT elif stock_current_feature_name == 'AMD': data_stock = AMD p = figure(plot_width=600, plot_height=400, toolbar_location=None, title=stock_current_feature_name + " stock volume from Quandl (" + inidate + " - " + today + ")") p.line(data_stock.index, data_stock["Total Volume"], line_width=2) p.xaxis.formatter = DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) p.xaxis.major_label_orientation = 3.14 / 4 p.yaxis.axis_label = "Total Volume" p.yaxis.formatter = NumeralTickFormatter(format="00") return p
def make_figure(x, y): # Plot time series (prices) p=figure(x_axis_type="datetime", width=1200, height=600) t = Title() t.text = 'Price' p.circle(x, y, size=10, color='red', legend='Price') p.line(x, y, color='blue') p.xaxis.formatter=DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) p.xaxis.major_label_orientation = np.pi/4 p.grid.grid_line_alpha=0.4 p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' p.title = t output_file('plot.html') script, div=components(p) return(script, div)
def stock_plot(): # Grab the inputs arguments from the URL args = flask.request.args # menu = [("Closing", "close"), ("Opening", "open"), ("High", "high"), ("Low", "low")] # dropdown = Dropdown(label="Select stock price to plot", button_type="warning", menu=menu) # dropdown.on_change('value', function_to_call) # dropdown.on_click(function_to_call) # dropdown.value # Get all the form arguments in the url with defaults user_symbol = getitem(args, 'user_symbol', "GOOG") # plot_type = getitem(args, 'plot_type', "close") # Get the data to plot geturl = 'https://www.quandl.com/api/v3/datasets/WIKI/'+user_symbol+'/data.json?api_key=insert_valid_quandl_api_key_here' r = re.get(geturl) json_data = json.loads(r.content.decode('utf-8'))['dataset_data'] df = pd.DataFrame(data=json_data['data'],columns=json_data['column_names']) dates = np.array(df['Date'][::-1],dtype='datetime64') open = np.array(df['Open'][::-1]) high = np.array(df['High'][::-1]) low = np.array(df['Low'][::-1]) close = np.array(df['Close'][::-1]) source = ColumnDataSource(data=dict(dates=dates, close=close)) # Working to add buttons to allow switching between prices text = "Closing" TOOLS = "pan,wheel_zoom,box_zoom,reset,save" # Create a graph with those arguments fig = figure(plot_height=300, plot_width=800, tools=TOOLS, toolbar_location="right", x_axis_type="datetime", x_axis_location="below", background_fill_color="#efefef", x_range=(dates[len(dates)-31], dates[len(dates)-1]), y_range=(np.min(close[len(dates)-31:len(dates)-1:1])*0.95,np.max(close[len(dates)-31:len(dates)-1:1])*1.05)) fig.line('dates', 'close', source=source) fig.yaxis.axis_label = text+" Price (in USD)" fig.xaxis.formatter=DatetimeTickFormatter( days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) fig.xaxis.major_label_orientation = pi/4 js_resources = INLINE.render_js() css_resources = INLINE.render_css() script, div = components(fig) html = flask.render_template( 'embed.html', plot_script=script, plot_div=div, js_resources=js_resources, css_resources=css_resources, user_symbol=user_symbol ) return encode_utf8(html)
def __init__(self, figure_name, x_lower_bound=None, x_upper_bound=None, y_lower_bound=None, y_upper_bound=None): # set up the figure self.p = figure(plot_width=1000, plot_height=400, tools='pan,wheel_zoom,reset', x_axis_type="datetime", toolbar_location=None, name=figure_name, x_range=DataRange1d(x_lower_bound, x_upper_bound, bounds="auto"), y_range=Range1d(y_lower_bound, y_upper_bound, bounds="auto")) self.p.sizing_mode = 'scale_width' # set up border self.p.border_fill_color = "whitesmoke" self.p.min_border_top = 15 # format x axis self.p.xaxis.formatter = DatetimeTickFormatter( hours=["%B %-d"], days=["%B %-d"], months=["%B %-d"], years=["%B %-d"], )
def pages_queried_timeseries(df, plot_width=600, plot_height=200, rule='1T'): ts = df[['url']].resample(rule, how='count').cumsum() ts.index = ts.index.tz_convert(tzlocal()) #Bokeh=0.10.0 misencodes timestamps, so we have to shift by ts.index = ts.index.shift(ts.index[0].utcoffset().total_seconds(), freq="S") ts = pd.concat([ts[:1], ts]) # prepend 0-value for Line chart compat ts.iloc[0]['url'] = 0 formatter = DatetimeTickFormatter(formats=DATETIME_FORMAT) ticker = DatetimeTicker(desired_num_ticks=3) source = ColumnDataSource(ts) plot = Plot(plot_width=plot_width, plot_height=plot_height, x_range=DataRange1d(range_padding=0.1), y_range=DataRange1d(start=0), **PLOT_FORMATS) plot.add_glyph( source, Line(x='retrieved', y='url', **LINE_FORMATS) ) plot.add_layout( DatetimeAxis(axis_label="Date Retrieved", formatter=formatter, ticker=ticker, **AXIS_FORMATS), 'below') plot.add_layout(LinearAxis(axis_label="Total Pages", **AXIS_FORMATS), 'left') return plot
def showFuelInsightsFor(fuelData, asssetId="1022017", assetType="Excavator"): p = figure(title="Fuel Refill Dates vs days it worked before refill", x_axis_label='Refill Date', y_axis_label='No of Days', plot_width=1000) x = list(fuelData[assetType + "_" + asssetId].keys()) y = list(fuelData[assetType + "_" + asssetId].values()) p.circle(x, y, fill_alpha=0.2, size=5) p.xaxis.formatter = DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) p.xaxis.major_label_orientation = pi / 4 # lastDate = x[-1] # # A naive approach to choose the next prediction date. # # We can use Machine learning time series prediction (ARIMA Approach) to predict the next few dates for refill. # delta = statistics.mode(y) # nextPredictedDate = lastDate + datetime.timedelta(days=delta) # print("Next Refill Date : " + nextPredictedDate) output_file("./templates/Fuel.html") div_exp00 = Div(text=""" <b>FUEL REFILL HISTORY GRAPH</b> """, width=300, style={'font-size': '100%'}) div_exp01 = Div( text= """ This graph analyses the history of fuel refills that happened for each asset ID. Predicting the next refill date can help us figure out when a particular asset needs fuel and can help us set alerts.""", width=300) show(column(div_exp00, div_exp01, p))
def _make_time_series_figure(title): formatter = DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) hovertool = HoverTool( tooltips=[ ('date', '@x{%d-%m-%YT%H:%M:%S}'), ('value', '@y') ], formatters={ '@x': 'datetime', }, mode='vline' ) p = figure( title=title, tools="pan,wheel_zoom,box_zoom,reset,save,box_select", x_axis_label='time', x_axis_type='datetime', y_axis_label='value', plot_width=900, active_scroll='wheel_zoom' ) p.add_tools(hovertool) p.xaxis.formatter = formatter return p
def get_multi_line_plot(dates, all_amount_by_date, signed_amount_by_date): plot = figure(plot_width=800, plot_height=500) data = { 'xs': [dates, dates], 'ys': [all_amount_by_date, signed_amount_by_date], 'labels': ['Individual', 'Pareado'], 'color': ['red', 'green'] } source = ColumnDataSource(data) plot.multi_line(xs='xs', ys='ys', legend='labels', color='color', source=source) plot.xaxis.formatter = DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) plot.xaxis.axis_label = 'Data dos Commits' plot.yaxis.axis_label = 'Quantidade de Commits' plot.title.text = 'Commits Pareados X Commits Individuais' plot.title.align = 'center' plot.title.text_font_size = '20pt' return plot
def plotLine(dataframe, x, y, title, fname, xlabel, ylabel, direc, color): """Produces a line chart HTML file""" fname = direc + fname output_file(fname) ds = ColumnDataSource(dataframe) label_dict = {} Ts = dataframe['inserted'] for c, value in enumerate(Ts, 1): label_dict[c] = value p = figure(plot_width=300, plot_height=400, title=title) p.line(source=ds, x=x, y=y, line_color=color, line_alpha=1.0, line_cap='butt') p.xaxis.axis_label = xlabel p.yaxis.axis_label = ylabel p.xaxis.formatter=DatetimeTickFormatter(hours=["%d %B %Y"],\ days=["%d %B %Y"],\ months=["%d %B %Y"],\ years=["%d %B %Y"],) p.xaxis.major_label_orientation = pi / 4 return p
def create_trend_plot(f): """Create plot for hit trend. f: Function object """ try: x = f.hit_ts to_ts = np.vectorize(lambda x: (x - datetime(1970, 1, 1)).total_seconds()) from_ts = np.vectorize(lambda x: datetime.utcfromtimestamp(x)) hist, x_bins = np.histogram(to_ts(x)) x_bins = 0.5 * (x_bins[0:-1] + x_bins[1:]) xx = from_ts(x_bins) yy = hist p = figure(tools=TOOLS, plot_height=FIG_HEIGHT, plot_width=FIG_WIDTH, x_axis_type='datetime') p.xaxis.formatter = DatetimeTickFormatter(minutes=["%H:%M %d/%b/%Y"], ) p.xaxis.major_label_orientation = np.pi / 4 p.vbar(x=xx, top=yy, width=3600, alpha=0.8, color='magenta') return components(p) except: return '<div></div>', '<div></div>'
def plot_setter(df, ticker): p = figure(width=700, height=400, title="Ticker=" + ticker, tools="") hover = HoverTool(tooltips=[ ('date', '@date{%F}'), ('close', '$@close{%0.2f}'), ], formatters={ 'date': 'datetime', 'close': 'printf' }) hover.mode = 'vline' hover.line_policy = 'nearest' p.add_tools(hover) dfcds = ColumnDataSource(df) p.line('date', 'close', source=dfcds, color="#000000") p.xaxis.formatter = DatetimeTickFormatter(days=["%d %b"]) p.x_range = Range1d(df['date'].min(), df['date'].max()) p.toolbar.logo = None p.toolbar_location = None p.title.text_color = "#000000" p.title.text_font_size = "1.5em" p.axis.major_label_text_color = "#000000" p.axis.major_label_text_font_size = "1.25em" p.xgrid.grid_line_color = None p.ygrid.grid_line_alpha = 0.5 p.ygrid.grid_line_dash = [2, 4] p.outline_line_color = None p.yaxis.axis_label = "Close" return p
def plot_water_levels(station, dates, levels): """ Function that makes a graph of the water level over time for a given station. Args: station (MonitoringStation): The desired station to graph. dates (list): The list of dates for the x-axis. levels (list): The corresponding water level for each date, y-axis. Returns: Bokeh plot object. """ output_file(station.name + ".html") p = figure(title=station.name, x_axis_label="Date", y_axis_label="Water level (m)", active_scroll="wheel_zoom") p.line(dates, levels, line_width=2) p.xaxis.formatter = DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) p.xaxis.major_label_orientation = np.pi / 4 return p
def hello_world(): def build_index(date): indexes = {} for row in model.get_all_currency_information(date)[1]: if row[1] == 'JPY' or row[1] == 'CNY' or row[1] == 'GBP' or row[1] == 'CAD' or row[1] == 'EUR': indexes[row[1]] = row[2] return indexes start_date = '2018-01-01' end_date = '2018-05-03' start_date = list(map(int,start_date.split('-'))) end_date = list(map(int,end_date.split('-'))) start_date = date_module(start_date[0], start_date[1], start_date[2]) end_date = date_module(end_date[0], end_date[1], end_date[2]) date = [] balance = [] market = [] base_index = build_index(start_date) for single_date in API.daterange(start_date, end_date): DATE = single_date.strftime("%Y-%m-%d") balance.append(model.check_portfolio('nan', DATE)[1]) date.append(single_date) performance = 0 for key, value in build_index(DATE).items(): performance = base_index[key]*1.0/value + performance market.append(performance*20000) p = figure(plot_width=800, plot_height=250) p.xaxis[0].formatter = DatetimeTickFormatter() p.line(date, balance, color='navy', alpha=0.5) p.line(date, market, color='red', alpha=0.5) script, div = components(p) return render_template("plot.html", the_div=div, the_script=script)
def generate(width=None, height=None, sizing_mode=None, x_bounds=None, y_bounds=None, x_range=None, y_range=None, title="", x_axis_visible=True, x_axis_label="", y_axis_label="", show_toolbar=True, bound_limits=None, glyphs=None): """Generate a time-figure from supplied bokeh input parameters.""" time_hover = HoverTool(tooltips=[("datum-tijd", "@datetime{%F}"), ("waarde", "@value{(0.00)}")], formatters={"@datetime": "datetime"}) tools = ["pan", "box_zoom", "xwheel_zoom", "reset", time_hover, "save"] if not x_range: x_range = Range1d(start=x_bounds['start'], end=x_bounds['end'], bounds=bound_limits) if not y_range: y_range = Range1d(start=y_bounds['start'], end=y_bounds['end'], bounds=bound_limits) time_fig = figure(title=title, tools=tools, # active_drag=None, height=height, width=width, sizing_mode=sizing_mode, x_axis_label=x_axis_label, y_axis_label=y_axis_label, x_range=x_range, y_range=y_range) time_fig.toolbar.autohide = False time_fig.title.align = "center" time_fig.xaxis.formatter = DatetimeTickFormatter(hours=["%H:%M"], days=["%d-%m-%Y"], months=["%d-%m-%Y"], years=["%d-%m-%Y"], ) time_fig.xaxis.visible = x_axis_visible if glyphs: for glyph in glyphs: glyph_type = glyph["type"] glyph.pop("type") getattr(time_fig, glyph_type)(x="datetime", y="value", **glyph) if next((True for glyph in glyphs if "legend_label" in glyph.keys()), False): time_fig.legend.click_policy = "hide" return time_fig
def make_log(): #Create figure object. p = figure(title='Log. Plot of COVID-19 ' + plot_title[sel_var] + ' (' + txt_src + ')', toolbar_location='above', plot_height=250, plot_width=500, x_axis_type='datetime', y_axis_type='log', tools='pan, wheel_zoom, box_zoom, reset', sizing_mode="scale_width") # Format your x-axis as datetime. p.xaxis[0].formatter = DatetimeTickFormatter(days='%b %d') p.circle(x='Date', y='Selected', source=source_grp, fill_color='Color', line_color='Color', legend_field='Country') p.legend.location = "top_left" p.legend.click_policy = "mute" p.add_layout(dt_span) # Add your tooltips p.add_tools(hover) return p
def plot_processed_df(self): self.graph.line(self.processed_df.index, [0] * len(self.processed_df), color='black') self.graph.line(self.processed_df.index, self.processed_df.series) self.graph.scatter(self.processed_df.index, self.processed_df.series) self.graph.xaxis.formatter = DatetimeTickFormatter(days='%Y-%m-%d') show(self.graph)
def make_trends_figure(trends, title, period): trend_figure = figure(plot_height=500, plot_width=1000, x_axis_type="datetime", x_range=(period["period"][0], period["period"][1]), title=title, toolbar_location=None, ) lines = [] max_value = 0 for i, trend in enumerate(trends): data_source = trends[trend] if max_value < data_source['amount'].max(): max_value = data_source['amount'].max() lines.append(trend_figure.step(data_source.index, data_source['amount'], line_width=2, mode="after", color=Category20[20][i % 20], )) trend_figure.y_range = Range1d(0, max_value * 1.1) trend_figure.xaxis[0].formatter = DatetimeTickFormatter(days=['%d %b']) trend_figure.yaxis[0].formatter = NumeralTickFormatter(format="0,0[.]00") legend_items = [(trend, [line]) for (trend, line) in zip(trends, lines)] legend = Legend(items=legend_items, location=(0, 0)) trend_figure.add_layout(legend, 'right') return trend_figure
def bk_overview_layout(p, num_in_row=1, min_height=360): p = bk_legend(p, location='center', orientation='horizontal') # p.legend.visible = False p.add_layout(p.legend[0], 'below') p.title.text_font_size = '100%' p.title.align = 'left' p.xaxis.formatter = DatetimeTickFormatter(days=["%b %d"], months=["%b '%y"]) p.yaxis.axis_label_text_font_size = '100%' p.yaxis.major_label_text_font_size = '80%' p.yaxis.major_tick_line_alpha = .9 p.yaxis.minor_tick_line_alpha = 0 p.toolbar_location = 'right' p.toolbar.autohide = True p = add_bokeh_footnote(p) if num_in_row > 1: p.plot_height = int(min_height * 1.2) p.plot_width = p.plot_height p.sizing_mode = 'scale_both' else: p.plot_height = int(min_height * 1.2) p.plot_width = int(min_height * 5 / 3) p.sizing_mode = 'scale_width' #Possible values are "fixed", "scale_width", "scale_height", "scale_both", and "stretch_both" return p