def plot_t_eff(dataframe): def create_data_source(df): return ColumnDataSource(data=dict(t_eff=df['t_eff'],expnum=df['expnum'],program=df['program'],attnum=df['attnum'],band=df['band'],b_eff=df['b_eff'],c_eff=df['c_eff'],f_eff=df['f_eff'])) line_colors = ['black','blue','yellow','pink'] plots = [] # Creating scatter plot p = figure(tools = [PanTool(),BoxZoomTool(),ResizeTool(),WheelZoomTool(),ResetTool(),HoverTool(tooltips = [('expnum','@expnum'),('band','@band'),('program', '@program'),('t_eff','@t_eff'),('b_eff','@b_eff'),('c_eff','@c_eff'),('f_eff','@f_eff'),('attempt','@attnum')])], x_axis_label = "expnum", y_axis_label = "t_eff", title = 't_eff',width=1000,height=500 ) for i,prog in enumerate(dataframe.program.unique()): df_false = dataframe[(dataframe['assessment']=='False') & (dataframe['program'] ==prog)] df_true = dataframe[(dataframe['assessment']=='True') & (dataframe['program'] ==prog)] df_unknown = dataframe[(dataframe['assessment']=='Unknown') & (dataframe['program']==prog)] p.scatter('expnum','t_eff',source=create_data_source(df_false),fill_color='red',line_color=line_colors[i],size=8,line_width=3,legend = prog) p.scatter('expnum','t_eff',source=create_data_source(df_true),fill_color='green',line_color=line_colors[i],size=8,line_width = 3, legend = prog) p.scatter('expnum','t_eff',source=create_data_source(df_unknown),fill_color='orange',line_color=line_colors[i],size=8,line_width=3,legend = prog) p.xaxis[0].formatter = NumeralTickFormatter(format="000000") plots.append(p) # Creating histogram dataframe.t_eff = dataframe.t_eff.convert_objects(convert_numeric=True) p2 = figure(x_axis_label = "t_eff", y_axis_label = "expnum", title = 't_eff',width=1000,height=500) h,edges = np.histogram(dataframe.t_eff.values, bins=np.linspace(float(min(dataframe.t_eff)),float(max(dataframe.t_eff)),35)) p2.quad(top=h, bottom=0, left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#033649") text = """Mean: {mean} Min: {min} Max: {max}""".format(mean=round(dataframe.t_eff.mean(skipna=True),3),min = dataframe.t_eff.min(),max=dataframe.t_eff.max()) mytext = glyphs.Text(x=edges[-1]-(edges[-1]/3),y=h.max()-(h.max()/3),text=[text],text_font_size='10pt') p2.add_glyph(mytext) plots.append(p2) return plots
def lineChart(df, xlabel, vFields, color=None, clustered=None, title=None): ylabel = ','.join(v for v in vFields) x = list(df[xlabel].values) if df[xlabel].dtype == object: p = figure(y_axis_label=ylabel, x_axis_label=xlabel, title=title, x_range=x, **self.get_common_figure_options()) else: p = figure(y_axis_label=ylabel, x_axis_label=xlabel, title=title, **self.get_common_figure_options()) if clustered is not None: colors = self.colorPalette(len(df[clustered].unique())) if color is None else color df[clustered] = df[clustered].astype(str) for j,c in enumerate(list(df[clustered].unique())) if clustered else enumerate([None]): df2 = df[df[clustered] == c] if c else df df2 = df2.drop(clustered, axis=1) if c else df2 for i,v in enumerate(vFields): y = list(df2[v].values) l = v if self.isSubplot() else c p.line(x, y, line_width=2, color=colors[i] if self.isSubplot() else colors[j], legend=l if self.showLegend() else None) else: colors = self.colorPalette(len(vFields)) if color is None else color for i,v in enumerate(vFields): y = list(df[v].values) p.line(x, y, line_width=2, color=colors[i], legend=v if self.showLegend() else None) p.legend.location = "top_left" hover = HoverTool() hover.tooltips = [(xlabel, '@x'), (ylabel, '@y{0.00}'), ('x', '$x'), ('y', '$y')] p.add_tools(hover) return p
def pca_plot(fp_list, clusters): np_fps = [] for fp in fp_list: arr = numpy.zeros((1,)) DataStructs.ConvertToNumpyArray(fp, arr) np_fps.append(arr) pca = PCA(n_components=3) pca.fit(np_fps) np_fps_r = pca.transform(np_fps) p1 = figure(x_axis_label="PC1", y_axis_label="PC2", title="PCA clustering of PAINS") p2 = figure(x_axis_label="PC2", y_axis_label="PC3", title="PCA clustering of PAINS") color_vector = ["blue", "red", "green", "orange", "pink", "cyan", "magenta", "brown", "purple"] print len(set(clusters)) for clust_num in set(clusters): print clust_num local_cluster = [] for i in xrange(len(clusters)): if clusters[i] == clust_num: local_cluster.append(np_fps_r[i]) print len(local_cluster) p1.scatter(np_fps_r[:,0], np_fps_r[:,1], color=color_vector[clust_num]) p2.scatter(np_fps_r[:,1], np_fps_r[:,2], color=color_vector[clust_num]) return HBox(p1, p2)
def data_retrieval(): conn = lite.connect('/Users/shanekenny/PycharmProjects/WiFinder/app/website/WiFinderDBv02.db') with conn: df = pd.read_sql_query("SELECT W.Log_Count, W.Time, W.Hour, W.Datetime, R.RoomID, R.Capacity, C.ClassID, C.Module, C.Reg_Students, O.Occupancy, O.OccID FROM WIFI_LOGS W JOIN CLASS C ON W.ClassID = C.ClassID JOIN ROOM R ON C.Room = R.RoomID JOIN OCCUPANCY O ON C.ClassID = O.ClassID WHERE R.RoomID = 'B002' AND W.Datetime = '2015-11-12' GROUP BY W.LogID;", conn) df['Time'] = df['Time'].apply(pd.to_datetime) p = figure(width=800, height=250, x_axis_type="datetime", ) p.extra_y_ranges = {"foo": Range1d(start=0, end=1)} p.line(df['Time'], df['Log_Count'], color='red',legend='Log Count') p.line(df['Time'], df['Reg_Students'], color='green',legend='Registered Students') p.line(df['Time'], df['Capacity'], color='blue', legend='Capacity') p.line(df['Time'], df['Occupancy']*100, color='orange', legend='Occupancy') p.add_layout(LinearAxis(y_range_name="foo"), 'left') p2 = figure(width=800, height=250, x_axis_type="datetime", x_range=p.x_range,) p2.line(df['Time'], df['Log_Count'], color='red', legend='Log Count') r= gridplot([[p, p2]], toolbar_location=None) js_resources = INLINE.render_js() css_resources = INLINE.render_css() script, div = components(r) return flask.render_template( 'explore.html', script=script, div=div, js_resources=js_resources, css_resources=css_resources,)
def test_return_type(self): plot1 = figure() plot1.circle([], []) plot2 = figure() plot2.circle([], []) # This is a testing artefact, users dont' have to do this in practice curdoc().add_root(plot1) curdoc().add_root(plot2) r = bes.components(plot1) assert len(r) == 2 _, divs = bes.components((plot1, plot2)) assert isinstance(divs, tuple) _, divs = bes.components([plot1, plot2]) assert isinstance(divs, tuple) _, divs = bes.components({"Plot 1": plot1, "Plot 2": plot2}) assert isinstance(divs, dict) assert all(isinstance(x, string_types) for x in divs.keys()) _, divs = bes.components(OrderedDict([("Plot 1", plot1), ("Plot 2", plot2)])) assert isinstance(divs, OrderedDict) assert all(isinstance(x, string_types) for x in divs.keys())
def bokeh2(X): Y = de_mean_matrix(X) TOOLS="resize,crosshair,pan,wheel_zoom,box_zoom,reset,previewsave,box_select" hover = HoverTool( tooltips=[ ("index", "$index"), ("(x,y)", "($x, $y)"), ("desc", "@desc"), ] ) bplt.output_file("data.html", title="Rescaling") s1 = bplt.figure(width=500, plot_height=250, title="Data", tools=[hover, TOOLS]) s1.scatter(X[:,0].A1, X[:,1].A1, marker="circle", line_color="#6666ee", fill_color="#ee6666", fill_alpha=0.5, size=12) s2 = bplt.figure(width=500, plot_height=250, title="De-meaned", tools=TOOLS) s2.scatter(Y[:,0].A1, Y[:,1].A1, marker="circle", line_color="#6666ee", fill_color="#ee6666", fill_alpha=0.5, size=12) # put all the plots in a VBox p = bplt.vplot(s1, s2) # show the results bplt.show(p)
def plot_3(data, ss): """t-SNE embedding of the parameters, colored by score """ scores = np.array([d['mean_test_score'] for d in data]) # maps each parameters to a vector of floats warped = np.array([ss.point_to_moe(d['parameters']) for d in data]) # Embed into 2 dimensions with t-SNE X = TSNE(n_components=2).fit_transform(warped) e_scores = np.exp(scores) mine, maxe = np.min(e_scores), np.max(e_scores) color = (e_scores - mine) / (maxe - mine) mapped_colors = map(rgb2hex, cm.get_cmap('RdBu_r')(color)) bk.figure(title='t-SNE (unsupervised)') bk.hold() df_params = nonconstant_parameters(data) df_params['score'] = scores bk.circle( X[:, 0], X[:, 1], color=mapped_colors, radius=1, source=ColumnDataSource(df_params), fill_alpha=0.6, line_color=None, tools=TOOLS) cp = bk.curplot() hover = cp.select(dict(type=HoverTool)) format_tt = [(s, '@%s' % s) for s in df_params.columns] hover.tooltips = OrderedDict([("index", "$index")] + format_tt) xax, yax = bk.axis() xax.axis_label = 't-SNE coord 1' yax.axis_label = 't-SNE coord 2'
def main(): xs = np.linspace(-np.pi, np.pi, 100, endpoint=True) xs = np.linspace(0, 4*np.pi, 100) ys_exp = np.exp(xs) ys_sin = np.sin(xs) ys_cos = np.sin(xs) ys_tan = np.tan(xs) output_file("grid_example.html") fig1 = figure(width=250, plot_height=250, title=None) fig1.circle(xs, ys_exp, size=10, color="navy", alpha=0.5) fig2 = figure(width=250, plot_height=250, x_range=fig1.x_range, title=None) fig2.triangle(xs, ys_sin, size=10, color="firebrick", alpha=0.5) fig3 = figure(width=250, height=250, x_range=fig2.x_range, y_range=fig2.y_range, title=None) fig3.square(xs, ys_cos, color="olive") fig4 = figure(width=250, height=250, title=None) fig4.line(xs, ys_tan, color="green") show(gridplot([[fig1, fig2], [fig3, fig4]]))
def test_gridplot_merge_tools_with_None(): p1, p2, p3, p4 = figure(), figure(), figure(), figure() gridplot([[p1, None, p2], [p3, p4, None]], merge_tools=True) for p in p1, p2, p3, p4: assert p.toolbar_location is None
def distribution(): mu, sigma = 0, 0.5 measured = np.random.normal(mu, sigma, 1000) hist, edges = np.histogram(measured, density=True, bins=20) x = np.linspace(-2, 2, 1000) pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) cdf = (1 + scipy.special.erf((x - mu) / np.sqrt(2 * sigma ** 2))) / 2 output_server("distribution_reveal") hold() figure(title="Interactive plots", tools="pan, wheel_zoom, box_zoom, reset, previewsave", background_fill="#E5E5E5") quad(top=hist, bottom=np.zeros(len(hist)), left=edges[:-1], right=edges[1:], fill_color="#333333", line_color="#E5E5E5", line_width=3) # Use `line` renderers to display the PDF and CDF line(x, pdf, line_color="#348abd", line_width=8, alpha=0.7, legend="PDF") line(x, cdf, line_color="#7a68a6", line_width=8, alpha=0.7, legend="CDF") xgrid().grid_line_color = "white" xgrid().grid_line_width = 3 ygrid().grid_line_color = "white" ygrid().grid_line_width = 3 legend().orientation = "top_left" return curplot(), cursession()
def animated(): from numpy import pi, cos, sin, linspace, zeros_like N = 50 + 1 r_base = 8 theta = linspace(0, 2 * pi, N) r_x = linspace(0, 6 * pi, N - 1) rmin = r_base - cos(r_x) - 1 rmax = r_base + sin(r_x) + 1 colors = ["FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8", "#253494", "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"] * 5 cx = cy = zeros_like(rmin) output_server("animated_reveal") figure(title="Animations") hold() annular_wedge( cx, cy, rmin, rmax, theta[:-1], theta[1:], x_range=[-11, 11], y_range=[-11, 11], inner_radius_units="data", outer_radius_units="data", fill_color=colors, line_color="black", tools="pan,wheel_zoom,box_zoom,reset,previewsave" ) return curplot(), cursession()
def knit_html(self,es): #col1 fig1 = figure(width=250,height=250) vis_bokeh.draw_1d_hist_from_es("dummy1",0,35,30,es,"run*",ax=fig1) #changes fig1, but also returns it fig2=figure(width=250,height=250) xmin,xmax = 0,65 xbins = 20 xname = "hcalEnergy" ymin,ymax = 0,65 ybins = 20 yname = "muonHits" vis_bokeh.draw_2d_hist_from_es(xname,xmin,xmax,xbins,yname,ymin,ymax,ybins,es, index="run*",ax=fig2) fig_column1 = vplot(fig1,fig2) #col2 fig3 = figure(width=250,height=250) fig3=vis_bokeh.draw_1d_hist_from_es("dummy23",0,100,30,es,"run*",ax=fig3,hist_drawer="classic") fig4 = figure(width=250,height=250) fig4=vis_bokeh.draw_1d_hist_from_es("dummy45",0,40,30,es,"run*",ax=fig4) fig_column2 = vplot(fig3,fig4) fig_grid = hplot(fig_column1,fig_column2) return vis_bokeh.fig_to_html(fig_grid)
def animated(): M = 5 N = M*10 + 1 r_base = 8 theta = linspace(0, 2*pi, N) r_x = linspace(0, 6*pi, N-1) rmin = r_base - cos(r_x) - 1 rmax = r_base + sin(r_x) + 1 colors = ["FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8", "#253494", "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"] * 5 p = figure(title="Animations", x_range=[-11, 11], y_range=[-11, 11]) # figure() function auto-adds the figure to curdoc() p = figure(x_range=(-11, 11), y_range=(-11, 11)) r = p.annular_wedge(0, 0, rmin, rmax, theta[:-1], theta[1:], fill_color=colors, line_color="white") def update_animated(plot): ds = r.data_source rmin = roll(ds.data["inner_radius"], 1) rmax = roll(ds.data["outer_radius"], -1) ds.data.update(inner_radius=rmin, outer_radius=rmax) curdoc().add_periodic_callback(update_animated, 50) return p
def bokeh_plot(df): tooltip = """ <div> <div> <img src="@image_files" height="60" alt="image" style="float: left; margin: 0px 15px 15px 0px; image-rendering: pixelated;" border="2" ></img> </div> <div> <span style="font-size: 17px;">@source_filenames</span> </div> </div> """ filenames = b64_image_files(df['images']) df['image_files'] = filenames colors_raw = cm.viridis((df['time'] - df['time'].min()) / (df['time'].max() - df['time'].min()), bytes=True) colors_str = ['#%02x%02x%02x' % tuple(c[:3]) for c in colors_raw] df['color'] = colors_str source = ColumnDataSource(df) bplot.output_file('plot.html') hover0 = HoverTool(tooltips=tooltip) hover1 = HoverTool(tooltips=tooltip) tools0 = [t() for t in TOOLS] + [hover0] tools1 = [t() for t in TOOLS] + [hover1] pca = bplot.figure(tools=tools0) pca.circle('PC1', 'PC2', color='color', source=source) tsne = bplot.figure(tools=tools1) tsne.circle('tSNE-0', 'tSNE-1', color='color', source=source) p = bplot.gridplot([[pca, tsne]]) bplot.show(p)
def __init__(self): xs = np.linspace(-np.pi, np.pi, 11) ys = xs Xs, Ys = np.meshgrid(xs, ys) self.Xs, self.Ys = Xs.flatten(), Ys.flatten() initdegree = 0 mat = rot_mat(initdegree) transXs, transYs = mat @ np.array([self.Xs, self.Ys]) TOOLS = "pan,lasso_select,save,reset" self.source = ColumnDataSource(data=dict(Xs=self.Xs, Ys=self.Ys, transXs=transXs, transYs=transYs)) self.fig = figure(tools=TOOLS, title="target", x_range=(-np.pi*np.sqrt(2)-1, np.pi*np.sqrt(2)+1), y_range=(-np.pi*np.sqrt(2)-1, np.pi*np.sqrt(2)+1)) self.fig.circle('Xs', 'Ys', source=self.source) self.transfig = figure(tools=TOOLS, title="transformed", x_range=self.fig.x_range, y_range=self.fig.y_range) self.transfig.circle('transXs', 'transYs', source=self.source, size=6) self.rot_param = Slider(title="degree", value=0, start=0, end=360, step=1) self.rot_param.on_change('value', self.update_data) self.plot = column(self.rot_param, gridplot([[self.fig, self.transfig]]))
def create_standard_plot(h=600, w=600, title='', x_range=None, tools='previewsave'): '''Create a standard plot and set consistent theme. Saves specifiying these every time. Args: h (int): The height (in pixels) of the plot. w (int): The width (in pixels) of the plot. title (str): The title of the plot. x_range (list): A list of variables for the x axis. tools (str): The tools to be displayed at the top of the chart. Returns: A plot object. ''' if x_range is not None: plot = bp.figure(tools=tools, background_fill_color='#E5E5E5', x_range=x_range, title=title, plot_height=h, plot_width=w) else: plot = bp.figure(tools=tools, background_fill_color='#E5E5E5', title=title, plot_height=h, plot_width=w) plot.xgrid.grid_line_color = 'white' plot.ygrid.grid_line_color = 'white' plot.grid.grid_line_width = 1 plot.xaxis.major_label_text_font_size='10pt' plot.yaxis.major_label_text_font_size='10pt' plot.xaxis.axis_label_text_font_size='12pt' plot.yaxis.axis_label_text_font_size='12pt' return plot
def test_axis(self): plt.figure() p = plt.circle([1,2,3], [1,2,3]) self.assertEqual(len(plt.axis()), 2) expected = set(plt.axis()) ax = LinearAxis() expected.add(ax) p.above.append(ax) self.assertEqual(set(plt.axis()), expected) ax2 = LinearAxis() expected.add(ax2) p.below.append(ax2) self.assertEqual(set(plt.axis()), expected) ax3 = LinearAxis() expected.add(ax3) p.left.append(ax3) self.assertEqual(set(plt.axis()), expected) ax4 = LinearAxis() expected.add(ax4) p.right.append(ax4) self.assertEqual(set(plt.axis()), expected)
def test_gridplot_merge_tools_flat(): p1, p2, p3, p4 = figure(), figure(), figure(), figure() lyt.gridplot([[p1, p2], [p3, p4]], merge_tools=True) for p in p1, p2, p3, p4: assert p.toolbar_location is None
def test_layout_sizing_mode(sizing_mode): p1, p2, p3, p4 = figure(), figure(), figure(), figure() lyt.layout([[p1, p2], [p3, p4]], sizing_mode=sizing_mode) for p in p1, p2, p3, p4: assert p1.sizing_mode == sizing_mode
def bokeh_plot(self): import os from bokeh.plotting import line from bokeh.plotting import hold, figure, show, output_file import numpy as np import bokeh.embed as embed figure() hold() for i in self.SensorDict: line( self.SensorDict[i]['dates'], self.SensorDict[i]['values'] ) print(len(self.SensorDict[i]['dates'])) #print(self.SensorDict[i]['dates'][0]) #print(self.SensorDict[i]['values'][0]) print('tjo') os.chdir('..') os.chdir('..') output_file('plot.html', title='Plot22') show()
def create_plot(team="LAA", year=2012): expr = bz.by(db.Salaries.teamID, avg=db.Salaries.salary.mean(), max=db.Salaries.salary.max(), ratio=db.Salaries.salary.max() / db.Salaries.salary.min()) expr = expr.sort('ratio', ascending=False) df_salary_gb = into(pd.DataFrame, expr) source1 = into(ColumnDataSource, df_salary_gb[["teamID", "avg"]]) plot1 = plt.figure(title="Salary ratio by team", x_range=list(df_salary_gb["teamID"])) plot1.scatter(x="teamID", y="avg", source=source1, size=20) plot1.xaxis.major_label_orientation = np.pi/3 df = into(pd.DataFrame, db.Salaries) df = df[df["teamID"] == team] df = df[df["yearID"] == year] df = df[["playerID","salary"]].sort('salary') source_team = into(ColumnDataSource, df) p_team = plt.figure(title="Salary of players for %s during %s" % (team, year), x_range=list(df["playerID"]))#, tools=TOOLS) p_team.scatter(x="playerID", y="salary", source=source_team, size=20) p_team.xaxis.major_label_orientation = np.pi/3 p = plt.gridplot([[plot1, p_team]]) return p
def bokeh_brushed(): """these are taken EXACTLY from http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html """ # prepare some date N = 300 x = np.linspace(0, 4*np.pi, N) y0 = np.sin(x) y1 = np.cos(x) # NEW: create a column data source for the plots to share source = bkm.ColumnDataSource(data=dict(x=x, y0=y0, y1=y1)) # create a new plot and add a renderer left = bkp.figure(tools=BOKEH_TOOLS, width=350, height=350, title=None) left.circle('x', 'y0', source=source) # create another new plot and add a renderer right = bkp.figure(tools=BOKEH_TOOLS, width=350, height=350, title=None) right.circle('x', 'y1', source=source) # put the subplots in a gridplot p = bkp.gridplot([[left, right]]) return bke.components(p)
def __init__(self, size): self.size = size self.time = RingBuffer(size) self.i_corr = RingBuffer(size) self.q_corr = RingBuffer(size) self.phase_error = RingBuffer(size) self.delay_error = RingBuffer(size) plot = figure(title='i corr', plot_width=250, plot_height=250, tools="pan,wheel_zoom,box_zoom,reset,save") plot.line(self.time.get(), self.i_corr.get(), size=12, alpha=0.7, name='i_corr') self.i_corr_plot = plot plot = figure(title='q corr', plot_width=250, plot_height=250, tools="pan,wheel_zoom,box_zoom,reset,save") plot.line(self.time.get(), self.q_corr.get(), size=12, alpha=0.7, name='q_corr') self.q_corr_plot = plot plot = figure(title='phase error', plot_width=250, plot_height=250, tools="pan,wheel_zoom,box_zoom,reset,save") plot.line(self.time.get(), self.phase_error.get(), size=12, alpha=0.7, name='phase_error') self.phase_error_plot = plot plot = figure(title='delay error', plot_width=250, plot_height=250, tools="pan,wheel_zoom,box_zoom,reset,save") plot.line(self.time.get(), self.delay_error.get(), size=12, alpha=0.7, name='delay_error') self.delay_error_plot = plot children = [self.i_corr_plot, self.q_corr_plot, self.phase_error_plot, self.delay_error_plot] self.plot = hplot(*children, name="tracking outputs")
def pca(target, control, title, name_one, name_two): np_fps = [] for fp in target + control: arr = numpy.zeros((1,)) DataStructs.ConvertToNumpyArray(fp, arr) np_fps.append(arr) ys_fit = [1] * len(target) + [0] * len(control) names = ["PAINS", "Control"] pca = PCA(n_components=3) pca.fit(np_fps) np_fps_r = pca.transform(np_fps) p1 = figure(x_axis_label="PC1", y_axis_label="PC2", title=title) p1.scatter(np_fps_r[:len(target), 0], np_fps_r[:len(target), 1], color="blue", legend=name_one) p1.scatter(np_fps_r[len(target):, 0], np_fps_r[len(target):, 1], color="red", legend=name_two) p2 = figure(x_axis_label="PC2", y_axis_label="PC3", title=title) p2.scatter(np_fps_r[:len(target), 1], np_fps_r[:len(target), 2], color="blue", legend=name_one) p2.scatter(np_fps_r[len(target):, 1], np_fps_r[len(target):, 2], color="red", legend=name_two) return HBox(p1, p2)
def __init__(self, predit_funct=None): Callback.__init__(self) # output_notebook() self.loss = np.array([]) self.psnrs = np.array([]) output_server("line") self.imagew = 512 self.min_loss = 10000 self.predit_funct = predit_funct self.p = figure() self.p2 = figure() self.x = np.array([]) self.y = np.array([]) self.bx = np.array([]) self.by = np.array([]) self.cx = np.array([]) self.epochNo = 0 self.p.line(self.x, self.y, name='line', color="tomato", line_width=2) self.p.line(self.bx, self.by, name='batch_line', color="blue", line_width=2) self.p2.line(self.cx, self.psnrs, name='psnr', color="green", line_width=2) show(self.p) # show(self.p2) # self.p2 = figure(x_range=[0, self.imagew], y_range=[0, self.imagew]) # self.p2.image_rgba(name='image', image=[np.array((self.imagew, self.imagew), dtype='uint32')], x=0, y=0, dw=self.imagew, dh=self.imagew) # show(self.p2) self.psnr = 0
def plot_hist(values, logx=False, title=""): """Plot bokeh histograms""" t = "{2} distribution (μ={0:.2f}, σ={0:.2f})".format( np.mean(values), np.std(values), title) if logx: p1 = figure(title=t, x_axis_type="log") p1.xaxis.axis_label = 'Log(x)' else: p1 = figure(title=t) p1.xaxis.axis_label = 'x' hist, edges = np.histogram(values, density=True, bins='fd') p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#036564") p1.legend.location = "center_right" p1.legend.background_fill_color = "darkgrey" p1.yaxis.axis_label = 'Pr(x)' p1.xaxis.major_label_text_font = 'helvetica' p1.yaxis.major_label_text_font = 'helvetica' p1.title.text_font = 'helvetica' p1.xaxis.axis_label_text_font = 'helvetica' return p1
def make_trip_distance_histogram(self): bins = self.trip_distance_bins centers = pd.rolling_mean(bins, 2)[1:] figure(title="trip distance in miles", title_text_font='12pt', plot_width=300, plot_height=200, x_range=[bins[0], bins[-1]], y_range=[0, 1], tools="pan,wheel_zoom,box_zoom,select,reset" ) source = HistogramDataSource( data_url="/bokeh/taxidata/distancehist/", ) hold() plot = rect("centers", "y", np.mean(np.diff(centers)) * 0.7, "counts", source=source) self.trip_distance_source = plot.select({'type' : ColumnDataSource})[0] self.trip_distance_ar_source = source plot.min_border=0 plot.h_symmetry=False plot.v_symmetry=False select_tool = _get_select_tool(plot) if select_tool: select_tool.dimensions = ['width'] self.distance_histogram = plot
def plot_circle_density(nodes, degrees, plot_width=800, plot_height=800): print("Plotting circle density graph") TOOLS="hover,pan,wheel_zoom,box_zoom,reset,click,previewsave" plt.figure(plot_width=plot_width, plot_height=plot_height, tools=TOOLS) theta = np.random.uniform(0, 2*np.pi, size=len(nodes)) max_d, min_d = np.max(degrees), np.min(degrees) scale = 1.0/np.log(degrees) - 1.0/np.log(max_d) xs = np.cos(theta)*scale ys = np.sin(theta)*scale source_dict = dict( xs = xs, ys = ys, degrees = degrees, nodes = nodes, alphas = np.log(degrees)/np.log(max(degrees)), ) source = ColumnDataSource(source_dict) plt.hold(True) plt.circle('xs', 'ys', source=source, radius=0.0025, fill_alpha='alphas', x_axis_type=None, y_axis_type=None, title="Density Distribution of Degrees") plt.text([max(xs), max(xs)], [.95*max(ys), .85*max(ys)], ["distance from center = 1 / log(deg)", "angle = random"], angle=0, text_baseline="bottom", text_align="right") hover = [t for t in plt.curplot().tools if isinstance(t, HoverTool)][0] hover.tooltips = OrderedDict([ ('node', '@nodes'), ('degree', '@degrees') ]) plt.hold(False) return plt.curplot()
def _make_figures(self,ep,trainerr,metvals): self._datasources = [] figures = [] fig = figure(title='Total Training Cost',x_axis_label='Epoch',y_axis_label='Cost') fig.line([ep],[trainerr],name='plot') ds = fig.select(dict(name='plot'))[0].data_source self._datasources.append(ds) if self._plotmetricmean: figures.append(fig) fig = figure(title='Metric Mean',x_axis_label='Epoch',y_axis_label='Mean') fig.line([ep],[np.nanmean(metvals)],name='plot') ds = fig.select(dict(name='plot'))[0].data_source self._datasources.append(ds) figures.append(fig) for mv,(mk,m) in zip(metvals,self.metrics): if m.metric in xnn.metrics.metric_names: name = xnn.metrics.metric_names[m.metric] else: name = m.metric.__name__ fig = figure(title=mk,x_axis_label='Epoch',y_axis_label=name) fig.line([ep],[mv],name='plot') ds = fig.select(dict(name='plot'))[0].data_source self._datasources.append(ds) figures.append(fig) allfigs = vplot(*figures) push()
def bokeh_linked(): """these are taken EXACTLY from http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html """ # prepare some data N = 100 x = np.linspace(0, 4*np.pi, N) y0 = np.sin(x) y1 = np.cos(x) y2 = np.sin(x) + np.cos(x) # create a new plot s1 = bkp.figure(width=250, plot_height=250, title=None) s1.circle(x, y0, size=10, color="navy", alpha=0.5) # NEW: create a new plot and share both ranges s2 = bkp.figure( x_range=s1.x_range, y_range=s1.y_range, width=250, plot_height=250, title=None ) s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5) # NEW: create a new plot and share only one range s3 = bkp.figure(x_range=s1.x_range, width=250, plot_height=250, title=None) s3.square(x, y2, size=10, color="olive", alpha=0.5) # NEW: put the subplots in a gridplot p = bkp.gridplot([[s1, s2, s3]], toolbar_location=None) return bke.components(p)
39.56752, 39.36423, 39.22605, 39.11656, 38.95788, 38.81393, 38.60929, 38.40118, 38.21500, 38.21472, 38.10272, 37.97469, 37.78990, 37.56670, 37.35363, 37.20443, 37.09597, 37.01706, 36.99908, 36.99908, 36.99926, 36.99910, 36.99831, 36.99845, 36.99828, 37.00383, 37.00325, 37.00247, 37.00102, 37.00147, 37.00166, 37.00097, 37.00105, 37.00094, 37.00048, 37.00012, 37.00017, 37.00022, 36.99998, 36.99998, 36.99998, 36.99998, 36.99998, 36.99998, 37.00040, 37.00040, 37.13439, 37.47222, 37.70735, 37.77873, 37.95499, 38.20495, 38.55049, 38.75165, 38.90545, 39.08777, 39.23851, 39.36296, 39.45715, 39.61018, 39.75817, 39.99994, 40.09896, 40.30302, 40.49580 ] from bokeh.plotting import figure from bokeh.io import output_file, show p = figure(x_axis_label='longtitude (degrees)', y_axis_label='latitude (degrees)') ''' INSTRUCTIONS * Create a list of the longitude positions for each state as x. This has already been done for you. * Create a list of the latitude positions for each state as y. The variable names for the latitude positions are az_lats, co_lats, nm_lats, and ut_lats. * Use p.patches() to add the patches glyph to the figure p. Supply the x and y lists as arguments along with a line_color of 'white'. ''' # Create a list of az_lons, co_lons, nm_lons and ut_lons: x x = [az_lons, co_lons, nm_lons, ut_lons] # Create a list of az_lats, co_lats, nm_lats and ut_lats: y y = [az_lats, co_lats, nm_lats, ut_lats] # Add patches to figure p with line_color=white for x and y
import numpy as np from bokeh.layouts import row, widgetbox from bokeh.models import CustomJS, Slider from bokeh.plotting import figure, output_file, show, ColumnDataSource A1 = -14.72757 A2 = 79.9554 x0 = 7.74771 dx = 0.41551 x = np.linspace(9.5, 6, 100) y = A2 + (A1 - A2) / (1 + np.exp((x - x0) / dx)) plot = figure(y_range=(-24, 90), plot_width=400, plot_height=400) plot.line(x, y, line_width=3, line_alpha=0.6) x = [9] y = [A2 + (A1 - A2) / (1 + np.exp((x[0] - x0) / dx))] source = ColumnDataSource( data=dict(x=x, y=y, time_left=[f'{y[0]:.0f} hours'], text_color=['green'])) plot.circle('x', 'y', source=source, color='red', size=10) plot.text(8.5, -7, text='time_left', text_color='text_color', alpha=0.6667, text_font_size='36pt', text_baseline='middle', text_align='center', source=source)
from bokeh.plotting import figure, output_file, show if __name__ == '__main__': output_file('graficado_simple.html') fig = figure() total_vals = int(input('Cuantos valores quieres graficar')) x_vals = list(range(total_vals)) y_vals = [] for x in x_vals: val = int(input(f'Valor y para la x {x}')) y_vals.append(val) fig.line(x_vals, y_vals, line_width=2) show(fig)
def image(self, *kargs, **kwargs): fig = figure() fig.image(*kargs, **kwargs) self.figures.append(fig)
import numpy as np from numpy import pi from bokeh.client import push_session from bokeh.driving import cosine from bokeh.plotting import figure, curdoc x = np.linspace(0, 4 * pi, 80) y = np.sin(x) p = figure() r1 = p.line([0, 4 * pi], [-1, 1], color="firebrick") r2 = p.line(x, y, color="navy", line_width=4) # open a session to keep our local document in sync with server session = push_session(curdoc()) @cosine(w=0.03) def update(step): # updating a single column of the the *same length* is OK r2.data_source.data["y"] = y * step r2.glyph.line_alpha = 1 - 0.8 * abs(step) curdoc().add_periodic_callback(update, 50) session.show(p) # open the document in a browser session.loop_until_closed() # run forever
from bokeh.sampledata.iris import flowers from bokeh.plotting import figure, output_file, save from bokeh.models import ColumnDataSource, HoverTool colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} flowers['colors'] = [colormap[x] for x in flowers['species']] hover = HoverTool( tooltips=[("Sepal length", "@sepal_length"), ( "Sepal width", "@sepal_width"), ("Petal length", "@petal_length"), ("Species", "@species")]) p = figure(title="Iris Morphology", plot_height=500, plot_width=500, tools=[hover, "pan,reset,wheel_zoom"]) p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle('petal_length', 'petal_width', color='colors', fill_alpha=0.2, size=10, source=ColumnDataSource(flowers)) output_file("docs/index.html", title="Iris Morphology") save(p)
symbol = 'AAPL' start = datetime.datetime(2015, 1, 1) end = datetime.datetime(2016, 1, 1) df = data.DataReader(name=symbol, data_source="yahoo", start=start, end=end) inc = df.Close > df.Open dec = df.Open > df.Close w = 12 * 60 * 60 * 1000 #half day in milliseconds TOOLS = "pan,wheel_zoom,box_zoom,reset,save" p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, title="AAPL Candlestick") p.segment(df.index, df.High, df.index, df.Low, color="black") #p.vbar(df.index[inc], w, df.Open[inc], df.Close[inc], color="#32CD32", line_color="green") #p.vbar(df.index[dec], w, df.Open[dec], df.Close[dec], color="#FF4500", line_color="red") p.rect(df.index[inc], (df.Open[inc] + df.Close[inc]) / 2, w, df.Close[inc] - df.Open[inc], fill_color="green") p.rect(df.index[dec], (df.Open[dec] + df.Close[dec]) / 2, w, df.Open[dec] - df.Close[dec], fill_color="red")
def get_boxplot(): # generate some synthetic time series for six different categories cats = list("abcdef") yy = np.random.randn(2000) g = np.random.choice(cats, 2000) for i, l in enumerate(cats): yy[g == l] += i // 2 df = pd.DataFrame(dict(score=yy, group=g)) # find the quartiles and IQR for each category groups = df.groupby('group') q1 = groups.quantile(q=0.25) q2 = groups.quantile(q=0.5) q3 = groups.quantile(q=0.75) iqr = q3 - q1 upper = q3 + 1.5 * iqr lower = q1 - 1.5 * iqr # find the outliers for each category def outliers(group): cat = group.name return group[(group.score > upper.loc[cat]['score']) | (group.score < lower.loc[cat]['score'])]['score'] out = groups.apply(outliers).dropna() # prepare outlier data for plotting, we need coordinates for every outlier. if not out.empty: outx = [] outy = [] for keys in out.index: outx.append(keys[0]) outy.append(out.loc[keys[0]].loc[keys[1]]) p = figure(tools="", background_fill_color="#efefef", x_range=cats, toolbar_location=None) # if no outliers, shrink lengths of stems to be no longer than the minimums or maximums qmin = groups.quantile(q=0.00) qmax = groups.quantile(q=1.00) upper.score = [ min([x, y]) for (x, y) in zip(list(qmax.loc[:, 'score']), upper.score) ] lower.score = [ max([x, y]) for (x, y) in zip(list(qmin.loc[:, 'score']), lower.score) ] # stems p.segment(cats, upper.score, cats, q3.score, line_color="black") p.segment(cats, lower.score, cats, q1.score, line_color="black") # boxes p.vbar(cats, 0.7, q2.score, q3.score, fill_color="#E08E79", line_color="black") p.vbar(cats, 0.7, q1.score, q2.score, fill_color="#3B8686", line_color="black") # whiskers (almost-0 height rects simpler than segments) p.rect(cats, lower.score, 0.2, 0.01, line_color="black") p.rect(cats, upper.score, 0.2, 0.01, line_color="black") # outliers if not out.empty: p.circle(outx, outy, size=6, color="#F38630", fill_alpha=0.6) p.xgrid.grid_line_color = None p.ygrid.grid_line_color = "white" p.grid.grid_line_width = 2 p.xaxis.major_label_text_font_size = "12pt" return p
from bokeh.plotting import figure, output_file, show import numpy as np # prepare some data x = np.linspace(0, 2.0 * np.pi, 101) sine = np.sin(x) cosine = np.cos(x) # output to static HTML file output_file("lines.html") # create a new plot with a title and axis labels p = figure(title="simple sine curve", x_axis_label='x', y_axis_label='y') # add a line renderer with legend and line thickness p.line(x, sine, legend="$\sin$", line_width=2, color='red') p.line(x, cosine, legend="$\cos$", line_width=2, color='green') # show the results show(p)
from bokeh.io import curdoc, reset_output from bokeh.layouts import row, column, widgetbox from bokeh.models import ColumnDataSource, CustomJS from bokeh.models.widgets import Slider, Dropdown, CheckboxButtonGroup, RadioButtonGroup from bokeh.plotting import figure import utils.utils as util #Init variables data_directory = "/Users/Jingwei/PycharmProjects/distributed_use/venv/TestDataset/UCR_TS_Archive_2015" dataset = data_directory + "/FordA/FordA_TRAIN" t_stamp = 0 window_size = 5 forget_degree = 0 TSClass = None plot_window = figure(plot_height=150, plot_width=500, title='New Incoming TS micro-batch', tools="reset") plot_all = figure(plot_height=150, plot_width=500, title='All historical TS') # Set up widgets menu_C = [("Normal", "Class: 1"), ("Abnormal", "Class: -1")] class_select = Dropdown(label="Select Class", button_type="success", menu=menu_C) winSize_slider = Slider(start=0, end=20, value=5, step=1, title="Window Size") fDegree_slider = Slider(start=0, end=20, value=5, step=1, title="Forgetting Degree")
def GainLossPlot(tblGainLoss): tblGainLoss['strDate'] = tblGainLoss['timestamp'].dt.strftime( '%Y-%m-%d %H:%M') tblGainLoss['pp_PriceDelta'] = tblGainLoss['PriceDelta'].round(2).astype( str) gain_source = ColumnDataSource(tblGainLoss[tblGainLoss['PriceDelta'] < 0]) loss_source = ColumnDataSource(tblGainLoss[tblGainLoss['PriceDelta'] >= 0]) gnl_source = ColumnDataSource(tblGainLoss) hover = HoverTool( tooltips=[ ('Date:', '@strDate'), ('Net Gain/Loss:', '$@pp_PriceDelta'), # use @{ } for field names with spaces ], formatters={ 'Date:': 'datetime', }, # display a tooltip whenever the cursor is vertically in line with a glyph mode='vline', names=['line', 'buy']) tools = [hover, WheelZoomTool(), 'box_zoom', 'pan', LassoSelectTool()] gain_loss_plot = figure( x_axis_type="datetime", title="Net Performance Accross All Owned CryptoCurrencies", y_range=(0, 10000), plot_width=1000, plot_height=400, tools=tools) gain_loss_plot.grid.grid_line_alpha = 0.2 gain_loss_plot.xaxis.axis_label = 'Date' gain_loss_plot.yaxis.axis_label = 'Net Gain/Loss (USD)' gain_loss_plot.line('timestamp', 'PriceDelta', color='darkgrey', alpha=0.3, name="line", source=gnl_source) gain_loss_plot.circle('timestamp', 'PriceDelta', size=4, legend='Gains', color='black', alpha=0.6, source=loss_source) gain_loss_plot.circle('timestamp', 'PriceDelta', size=4, legend='Losses', color='darkred', alpha=0.6, source=gain_source) zero = Span(location=0, dimension='width', line_color='grey', line_dash='solid', line_width=0.5, name='buy') gain_loss_plot.add_layout(zero) gain_loss_plot.legend.location = "top_left" return gain_loss_plot
def make_box(area): a = get_data(area) h = np.array(a['F(Horiba)'], dtype=float)[~np.isnan(np.array(a['F(Horiba)']))] m = np.array(a['F(Merck)'])[~np.isnan(np.array(a['F(Merck)']))] raw_data = { 'device': ['Horiba', 'Merck'], 'high': [max(h), max(m)], 'low': [min(h), min(m)], 'average': [ float(x) for x in ['{:01.2f}'.format(y) for y in [np.mean(h), np.mean(m)]] ], 'color': ["#0d3362", "#c64737"], 'text': ['Average of F(Horiba)', 'Average of F(Merck)'], 'size': [np.mean(h) * 10, np.mean(m) * 10] } df = pd.DataFrame( raw_data, columns=['device', 'high', 'low', 'average', 'color', 'text', 'size']) source = ColumnDataSource(data=df) box = figure(title='Result differences based on Mobilab', y_axis_label="Diference degree = F(x)", x_axis_label='Devices', x_range=np.array(df.device), y_range=(-1, 20), plot_width=340, plot_height=350, toolbar_location=None) box.grid.grid_line_alpha = 1 box.segment('device', 'high', 'device', 'low', color='color', source=source) box.rect('device', 'low', 0.2, 0.01, line_color='color', source=source) box.rect('device', 'high', 0.2, 0.01, line_color='color', source=source) box.circle('device', 'average', size='size', color='color', source=source, legend='text') labels = LabelSet(x="device", y="average", text="average", x_offset=0, y_offset=-4, text_font_size="7pt", text_color="white", source=source, text_align='center') box.add_layout(labels) citation = Label( x=10, y=-60, x_units='screen', y_units='screen', text= "F(x)=|result from Mobilab-result from 'x'| Conclusion: Horiba is more similar than Merck", render_mode='css', border_line_color='white', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) box.add_layout(citation) return box
def plot(df): source = ColumnDataSource(df) # Setting up colors by mapper (linear_cmap function) palette = [cc.rainbow[i * 15] for i in range(17)] mini, maxi = min(df['xG_diff']), max(df['xG_diff']) if abs(min(df['xG_diff'])) > abs(max(df['xG_diff'])): mini, maxi = min(df['xG_diff']), -min(df['xG_diff']) else: mini, maxi = -max(df['xG_diff']), max(df['xG_diff']) mapper = linear_cmap(field_name='xG_diff', palette=palette, low=mini, high=maxi) # Tooltips tooltips = [("Name", "@player_name"), ("Games", "@games"), ("Goals", "@goals"), ("xG", "@xG"), ("(xG - goals)", "@xG_diff")] # Draw plot p = figure( title= "Premier League - difference between xG and goals (last 5 games or 30 days ago)", x_range=df['player_name'], height=800, width=1600) # x_range !!! do source? # Title style p.title.text_color = "#dddddd" p.title.text_font = "Consolas" p.title.text_font_size = '24px' p.title.align = 'center' # Displaying data on plot r1 = p.circle("player_name", "xG", size=10, color=mapper, source=source) # xG (circles) r2 = p.square('player_name', 'goals', size=10, fill_color=mapper, line_color=None, source=source) # goals (rectangle) r3 = p.segment('player_name', 'xG', 'player_name', 'goals', color=mapper, source=source) # xG - goals (lines) # Styling plot p.yaxis.axis_label = 'Goals and xG' p.yaxis.axis_label_text_color = '#dddddd' # color of y label text p.yaxis.axis_label_text_font = 'Consolas' p.xaxis.major_label_orientation = pi / 4 p.axis.major_label_text_color = '#dddddd' # color of axis's values p.axis.major_label_text_font = 'Consolas' p.axis.axis_line_color = '#dddddd' p.border_fill_color = "#1b1b1b" p.background_fill_color = "#1b1b1b" p.grid.grid_line_color = "#242424" p.min_border_top = 40 p.min_border_left = 60 # Legend legend = Legend(items=[ LegendItem(label='xG', renderers=[r1]), LegendItem(label='goals', renderers=[r2]), LegendItem(label='(xG - goals)', renderers=[r3]) ], background_fill_color="#1b1b1b", label_text_color='#dddddd', label_text_font='Consolas') p.add_layout(legend, 'right') p.legend.click_policy = "hide" # HoverTool on_hover = HoverTool(renderers=[r1, r2], tooltips=tooltips) p.add_tools(on_hover) # Show plot on screen and save it to file show(p) output_file("data/Premier_League_goals_and_xG_difference.html", title="Premier League - difference between goals and xG") save(p)
def WalletPlot(coinHistory): coinHistory['PercentCoin'] = coinHistory['coins_transacted'] / coinHistory[ 'coins_transacted'].sum() coinHistory['PercentUSD_Purchase'] = coinHistory[ 'price_at_transaction'] / coinHistory['price_at_transaction'].sum() coinHistory['PercentUSD_Current'] = coinHistory[ 'CurrentPrice'] / coinHistory['CurrentPrice'].sum() coinHistory['NetGainLoss'] = coinHistory[ 'CurrentWalletVallue'] - coinHistory['USD_In'] currentValue = coinHistory.sort_values('NetGainLoss').groupby('name').sum() coinName = [] coinPriceStart = [] coinPriceStop = [] coinNet = [] coinCurrent = [] colors = [] amount = [] previousCoin = 0 coins = list(set(coinHistory.name)) numCoins = len(coins) for coin, price, net, amt, color in zip(currentValue.index, currentValue.CurrentWalletVallue, currentValue.NetGainLoss, currentValue.coins_transacted, Category20[numCoins]): coinName.append(coin) coinPriceStart.append(previousCoin) coinPriceStop.append(previousCoin + price) colors.append(color) coinNet.append(net) amount.append(amt) coinCurrent.append(price) previousCoin += price percent_gainloss = [] colors = [] # yea i know I'll fix it for c in coinName: colors.append(colorDict[c]) # do some rounding and convert to string to make things look better. pp_coinCurrent = [str(float("{:.2f}".format(X))) for X in coinCurrent] pp_coinNet = [str(float("{:.2f}".format(X))) for X in coinNet] pp_amount = [str(float("{:.5f}".format(X))) for X in amount] totalDollars = { 'Coin': coinName, 'PriceStart': coinPriceStart, 'PriceStop': coinPriceStop, 'Color': colors, 'Net': coinNet, 'Amount': amount, 'Current': coinCurrent, 'pp_Net': pp_coinNet, 'pp_Amount': pp_amount, 'pp_Current': pp_coinCurrent, 'Position': [0 for x in range(len(coinName))] } print(totalDollars) hover = HoverTool(tooltips=[('Coin:', '@Coin'), ('Amount Owned:', '@pp_Amount'), ('Current Value (USD):', '$@pp_Current'), ('Net Gain/Loss:', '$@pp_Net')], ) source = ColumnDataSource(data=totalDollars) total_balance = int(coinHistory['CurrentWalletVallue'].sum()) coinBar = figure(plot_width=200, plot_height=800, tools=[hover], y_range=(0, total_balance + 500), toolbar_location=None) coinBar.vbar(x='Position', width=0.5, bottom='PriceStart', top='PriceStop', color='Color', source=source) money_invested = Span(location=coinHistory['USD_In'].sum(), dimension='width', line_color='black', line_dash='dashed', line_width=3) money_inValue = '$' + str( float("{:.2f}".format(coinHistory['USD_In'].sum()))) cValue = '$' + str( float("{:.2f}".format(coinHistory['CurrentWalletVallue'].sum()))) # money_inValueText = Label(x=0.25, y=coinHistory['USD_In'].sum() , x_units='screen', text=money_inValue, render_mode='css', # border_line_color='black', border_line_alpha=0.0, # background_fill_color='white', background_fill_alpha=0.0) currentValueText = Label(x=50, y=coinHistory['CurrentWalletVallue'].sum(), x_units='screen', text=cValue, render_mode='css', border_line_color='black', border_line_alpha=0.0, background_fill_color='white', background_fill_alpha=0.0) coinBar.add_layout(money_invested) coinBar.add_layout(currentValueText) # coinBar.add_layout(money_inValueText) coinBar.xaxis.visible = False coinBar.yaxis.visible = False coinBar.xgrid.grid_line_color = None coinBar.ygrid.grid_line_color = None return coinBar
def _stacked_hist(dataframe, x_col, stack_col, x_label, width, height, x_range=None, y_range=None): data = {"x": sorted(dataframe[x_col].unique().astype(str))} for stack_value in dataframe[stack_col].unique(): x_values = dataframe.groupby(stack_col).get_group( stack_value).groupby(x_col).count() data[str(stack_value)] = [ float(x_values[x_values.index == i][stack_col].values) if i in x_values.index else 0 for i in sorted(dataframe[x_col].unique()) ] colors = Category20[dataframe[stack_col].nunique()] if ( 2 < dataframe[stack_col].nunique() < 21) else viridis( dataframe[stack_col].nunique()) legend = [ stack_col + ": " + i for i in dataframe[stack_col].unique().astype(str).tolist() ] if x_range is None and y_range is None: p = figure(x_range=sorted(dataframe[x_col].unique().astype(str)), height=height, width=width, toolbar_location=None, tools="", tooltips="$name: @$name") elif x_range is None and y_range is not None: p = figure(x_range=sorted(dataframe[x_col].unique().astype(str)), y_range=y_range, height=height, width=width, toolbar_location=None, tools="", tooltips="$name: @$name") elif x_range is not None and y_range is None: p = figure(x_range=x_range, height=height, width=width, toolbar_location=None, tools="", tooltips="$name: @$name") else: p = figure(x_range=x_range, y_range=y_range, height=height, width=width, toolbar_location=None, tools="", tooltips="$name: @$name") p.vbar_stack(sorted(dataframe[stack_col].unique().astype(str)), x="x", source=pd.DataFrame(data), color=colors, width=0.8, legend_label=legend) p.xaxis.axis_label = x_label p.yaxis.axis_label = "Counts" p.js_on_event(events.DoubleTap, toggle_legend_js(p)) p.legend.click_policy = "hide" return p
def trend_chart(self, policy_names: list, compounding: bool = False, height: int = 350, width: int = 800): """Trend chart of the result using Bokeh. Parameters ---------- policy_names : list List of selected policy names compounding : bool, default False Whether returns are reinvested back into the account. height : int Height of the plot width : int Width of the plot Returns ------- None """ selected_rst_dict = {key: self.rst_dict[key] for key in policy_names} data = pd.DataFrame(selected_rst_dict) data["strategy_return"] = self.strategy_return if compounding: cum = (data + 1).cumprod() else: cum = data.cumsum() + 1 if compounding: mdd = (cum / cum.cummax() - 1) else: mdd = cum - cum.cummax() source = ColumnDataSource(data=cum) source_mdd = ColumnDataSource(data=mdd) p = figure(x_axis_type="datetime", title="Trend Line", plot_height=height, plot_width=width) p.xgrid.grid_line_color = None p.ygrid.grid_line_alpha = 0.5 p.xaxis.axis_label = 'Time' p.yaxis.axis_label = 'Total Return' p_mdd = figure(x_axis_type="datetime", title="Max Drawdown", plot_height=height, plot_width=width, x_range=p.x_range) p_mdd.xgrid.grid_line_color = None p_mdd.ygrid.grid_line_alpha = 0.5 p_mdd.xaxis.axis_label = 'Time' p_mdd.yaxis.axis_label = 'MDD' lines = [] for i in range(len(cum.columns)): lines.append( p.line("Date", cum.columns[i], source=source, line_width=2, line_alpha=0.8, line_color=Spectral10[i % 10], legend_label=cum.columns[i], muted_color=Spectral10[i % 10], muted_alpha=0.1)) lines_mdd = [] for i in range(len(mdd.columns)): lines_mdd.append( p_mdd.line("Date", mdd.columns[i], source=source_mdd, line_width=2, line_alpha=0.8, line_color=Spectral10[i % 10], legend_label=mdd.columns[i], muted_color=Spectral10[i % 10], muted_alpha=0.1)) p.legend.location = "top_left" p.legend.click_policy = "mute" p_mdd.legend.location = "bottom_left" p_mdd.legend.click_policy = "mute" LABELS = list(cum.columns) checkbox_group = CheckboxGroup(labels=LABELS) checkbox_group.active = list(range(len(LABELS))) code = """ for (var i = 0; i < lines.length; i++) { lines[i].visible = false; if (cb_obj.active.includes(i)){lines[i].visible = true;} } """ callback = CustomJS(code=code, args={'lines': lines}) checkbox_group.js_on_click(callback) callback = CustomJS(code=code, args={'lines': lines_mdd}) checkbox_group.js_on_click(callback) grid = gridplot([[p, checkbox_group], [p_mdd]]) show(grid)
def _heatmap(df: pd.DataFrame, col_x: str, col_y: str, col_values: str, color_mapper: Optional[bokeh.models.ColorMapper] = None, normalize: str = "None", height: int = 500, width: int = 500, x_range=None, y_range=None): df = df.copy() # normalize values if normalize == "Column": for name in df[col_x].unique(): df.loc[( df[col_x] == name, col_values)] /= df[df[col_x] == name][col_values].sum() elif normalize == "Row": for name in df[col_y].unique(): df.loc[( df[col_y] == name, col_values)] /= df[df[col_y] == name][col_values].sum() # ensure the x and y column are in a categorical format if df[col_x].dtype != str or df[col_y].dtype != str: df = df[[col_x, col_y, col_values]].copy() df[col_x] = df[col_x].astype(str) df[col_y] = df[col_y].astype(str) if x_range is not None and y_range is not None: p = figure(x_range=x_range, y_range=y_range, x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@' + col_values)], width=width, height=height) elif x_range is not None and y_range is None: p = figure(x_range=x_range, y_range=sorted(df[col_y].unique()), x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@' + col_values)], width=width, height=height) elif x_range is None and y_range is not None: p = figure(x_range=sorted(df[col_x].unique())[::-1], y_range=y_range, x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@' + col_values)], width=width, height=height) else: p = figure(x_range=sorted(df[col_x].unique())[::-1], y_range=sorted(df[col_y].unique()), x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@' + col_values)], width=width, height=height) p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_standoff = 0 p.rect(x=col_x, y=col_y, width=1, height=1, source=df, fill_color={ 'field': col_values, 'transform': color_mapper }, line_color=None) return p
def _categorical_2d_histogram(dataframe, category_col, hist_col, bins, range, normalize, precision, color_mapper, hist_col_is_categorical, width, height): data = {"x": np.array([]), "y": [], "z": np.array([])} hist_min = dataframe[hist_col].min() if range is None else range[0] hist_max = dataframe[hist_col].max() if range is None else range[1] if hist_max < hist_min: hist_max = hist_min * 1.1 for group in dataframe.groupby(category_col): if hist_col_is_categorical: bins = dataframe[hist_col].nunique() unique_values = dataframe[hist_col].unique() x, z = np.unique(group[1][hist_col], return_counts=True) data["y"] += [str(group[0])] * bins z = np.array( [float(z[x == i]) if i in x else 0 for i in unique_values]) if normalize: z = z / z.sum() data["x"] = np.append(data["x"], unique_values.astype(str)) data["z"] = np.append(data["z"], z) else: z, x = np.histogram(group[1][hist_col], bins=bins, range=(hist_min, hist_max)) if normalize: z = z / z.sum() data["y"] += [str(group[0])] * bins data["x"] = np.append(data["x"], x[:-1].round(precision).astype(str)) data["z"] = np.append(data["z"], z) df = pd.DataFrame(data) color_bar, color_mapper = _create_colorbar_and_color_mapper( data["z"].min(), data["z"].max(), color_mapper) # create the 2d histogram p = figure(x_range=sorted(df["x"].unique().astype(str)), y_range=sorted(df["y"].unique().astype(str)), x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@z')], width=width, height=height, x_axis_label=hist_col, y_axis_label=category_col) p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_standoff = 0 p.rect(x="x", y="y", width=1, height=1, source=df, fill_color={ 'field': "z", 'transform': color_mapper }, line_color=None) p.add_layout(color_bar, 'right') return p
def histogram(values: Union[np.ndarray, List[np.ndarray]], bins: int = 10, range: Tuple[int] = None, density: bool = False, remove_tools: bool = False, linked_axis=True, title="", x_label="", y_label="", orientation="horizontal", width: int = 500, height: int = 500) -> bokeh.plotting.Figure: "Creates a histogram" if isinstance(values, np.ndarray): if orientation == "vertical": x_label, y_label = y_label, x_label p = figure(width=width, height=height, title=title, x_axis_label=x_label, y_axis_label=y_label) counts, edges = np.histogram(values, bins=bins, range=range, density=density) if orientation == "horizontal": p.quad(top=counts, bottom=0, left=edges[:-1], right=edges[1:]) elif orientation == "vertical": p.quad(top=edges[1:], bottom=edges[:-1], left=0, right=counts) if remove_tools: p.toolbar.logo = None p.toolbar_location = None return p elif isinstance(values, list): if not isinstance(title, list): title = [title] * len(values) if not isinstance(x_label, list): x_labels = [x_label] * len(values) if not isinstance(y_label, list): y_labels = [y_label] * len(values) if orientation == "vertical": x_labels, y_labels = y_labels, x_labels plot_list = [] for values_element, plot_title, x_label, y_label in zip( values, title, x_labels, y_labels): if len(plot_list) == 0 or linked_axis == False: p = figure(width=width, height=height, title=plot_title, x_axis_label=x_label, y_axis_label=y_label) else: p = figure(width=width, height=height, x_range=plot_list[0].x_range, y_range=plot_list[0].y_range, title=plot_title, x_axis_label=x_label, y_axis_label=y_label) counts, edges = np.histogram(values_element, bins=bins, range=range, density=density) if orientation == "horizontal": p.quad(top=counts, bottom=0, left=edges[:-1], right=edges[1:]) elif orientation == "vertical": p.quad(top=edges[1:], bottom=edges[:-1], left=0, right=counts) if remove_tools: p.toolbar.logo = None p.toolbar_location = None plot_list.append(p) return plot_list else: raise TypeError("values has to be of type list or np.ndarray")
def barplot(counts: Union[np.ndarray, List[np.ndarray]], values: Union[np.ndarray, List[np.ndarray]], bar_type: Literal["horizontal", "vertical"] = "horizontal", linked_axis=True, width: int = 500, height: int = 500, **kwargs) -> bokeh.plotting.Figure: """Creates a figure with a barplot, were the counts is the bar height and values are the labels for the bars.""" if isinstance(counts, list) and isinstance(values, list): plot_list = [] for counts_element, values_element in zip(counts, values): values_element = [str(entry) for entry in values_element] if bar_type == "horizontal": if len(plot_list) == 0: p = figure(width=width, height=height, y_range=values_element) p.hbar(y=values_element, left=0, right=counts_element, height=0.9) display(pn.Row(p)) else: if linked_axis: p = figure(width=width, height=height, y_range=plot_list[0].y_range, x_range=plot_list[0].x_range) else: p = figure(width=width, height=height, y_range=values_element) p.hbar(y=values_element, left=0, right=counts_element, height=0.9) elif bar_type == "vertical": if len(plot_list) == 0: p = figure(width=width, height=height, x_range=values_element) p.vbar(x=values_element, bottom=0, top=counts_element, width=0.9) else: if linked_axis: p = figure(width=width, height=height, x_range=plot_list[0].x_range, y_range=plot_list[0].y_range) else: p = figure(width=width, height=height, x_range=values_element) p.vbar(x=values_element, bottom=0, top=counts_element, width=0.9) else: raise ValueError( "hist_type has to be of 'horizontal' or 'vertical'") plot_list.append(p) return plot_list elif isinstance(counts, np.ndarray) and isinstance(values, np.ndarray): values = [str(entry) for entry in values] if bar_type == "horizontal": p = figure(width=width, height=height, y_range=values) p.hbar(y=values, left=0, right=counts, height=0.9) elif bar_type == "vertical": p = figure(width=width, height=height, x_range=values) p.vbar(x=values, bottom=0, top=counts, width=0.9) else: raise ValueError( "hist_type has to be of 'horizontal' or 'vertical'") return p else: raise TypeError( "counts and values need to be of the same type (list or np.ndarray)" )
from bokeh.plotting import figure, output_file, show # prepare some data x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] # output to static HTML file output_file("lines.html") # create a new plot with a title and axis labels p = figure(title="simple line example", x_axis_label='x', y_axis_label='y') # add a line renderer with legend and line thickness p.line(x, y, legend_label="Temp.", line_width=2) # show the results show(p)
def heatmap(data: Union[pd.DataFrame, List[pd.DataFrame]], col_x: str, col_y: str, col_values: str, color_mapper: Optional[bokeh.models.ColorMapper] = None, normalize: str = "None", link_plots: bool = True, height: int = 500, width: int = 500) -> bokeh.plotting.Figure: def _heatmap(df: pd.DataFrame, col_x: str, col_y: str, col_values: str, color_mapper: Optional[bokeh.models.ColorMapper] = None, normalize: str = "None", height: int = 500, width: int = 500, x_range=None, y_range=None): df = df.copy() # normalize values if normalize == "Column": for name in df[col_x].unique(): df.loc[( df[col_x] == name, col_values)] /= df[df[col_x] == name][col_values].sum() elif normalize == "Row": for name in df[col_y].unique(): df.loc[( df[col_y] == name, col_values)] /= df[df[col_y] == name][col_values].sum() # ensure the x and y column are in a categorical format if df[col_x].dtype != str or df[col_y].dtype != str: df = df[[col_x, col_y, col_values]].copy() df[col_x] = df[col_x].astype(str) df[col_y] = df[col_y].astype(str) if x_range is not None and y_range is not None: p = figure(x_range=x_range, y_range=y_range, x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@' + col_values)], width=width, height=height) elif x_range is not None and y_range is None: p = figure(x_range=x_range, y_range=sorted(df[col_y].unique()), x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@' + col_values)], width=width, height=height) elif x_range is None and y_range is not None: p = figure(x_range=sorted(df[col_x].unique())[::-1], y_range=y_range, x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@' + col_values)], width=width, height=height) else: p = figure(x_range=sorted(df[col_x].unique())[::-1], y_range=sorted(df[col_y].unique()), x_axis_location="above", tools="hover", toolbar_location=None, tooltips=[('', '@' + col_values)], width=width, height=height) p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_standoff = 0 p.rect(x=col_x, y=col_y, width=1, height=1, source=df, fill_color={ 'field': col_values, 'transform': color_mapper }, line_color=None) return p def _create_colorbar_and_color_mapper(min_val, max_val, color_mapper): # create color bar if color_mapper is None: color_mapper = LinearColorMapper(palette=Viridis[256], low=min_val, high=max_val) color_bar = ColorBar(color_mapper=color_mapper, major_label_text_font_size="7px", label_standoff=6, border_line_color=None, location=(0, 0)) return color_bar, color_mapper # handel multiple inputs here if isinstance(data, list): plot_list = [] if link_plots: min_value = min(df[col_values].min() for df in data) max_value = max(df[col_values].max() for df in data) color_bar, color_mapper = _create_colorbar_and_color_mapper( min_value, max_value, color_mapper) for df in data: if not link_plots: color_bar, color_mapper = _create_colorbar_and_color_mapper( df[col_values].min(), df[col_values].max(), None) temp_heatmap = _heatmap(df, col_x, col_y, col_values, color_mapper, normalize, height, width) if not link_plots: temp_heatmap.add_layout(color_bar, 'right') plot_list.append(temp_heatmap) if link_plots: c_bar_figure = figure(width=65, height=height, toolbar_location=None, min_border=0, outline_line_color=None) c_bar_figure.add_layout(color_bar, 'right') plot_list.append(c_bar_figure) return plot_list elif isinstance(data, pd.DataFrame): color_bar, color_mapper = _create_colorbar_and_color_mapper( data[col_values].min(), data[col_values].max(), color_mapper) p = _heatmap(data, col_x, col_y, col_values, color_mapper, normalize, height, width) p.add_layout(color_bar, 'right') return p else: raise TypeError("Data has to be of type list or pd.Dataframe")
from bokeh.models.widgets.markups import Div from urn import PolyaUrn from explanation import explanation_text, explanation_text_2 a, b, n, s = 5, 2, 50, 10 doc = curdoc() U = PolyaUrn(a, b, n) WalkPanel_xrange = (0, a + n + 1) WalkPanel_yrange = (0, n) WalkPanel = figure( name="WalkPanel", width=325, height=325, x_range=WalkPanel_xrange, y_range=WalkPanel_yrange, toolbar_location=None, x_axis_label="Number of White Balls in the Urn", y_axis_label="Number of Draws from the Urn", ) WalkSource = ColumnDataSource({"x": np.zeros(n + 1), "y": np.zeros(n + 1)}) WalkPanel.line(x="x", y="y", source=WalkSource) DensityPanel_xrange = (0, a + n + 1) DensityPanel_yrange = (0, 10) DensityPanel = figure( name="DensityPanel", width=325, height=325, x_range=DensityPanel_xrange, y_range=DensityPanel_yrange,
# torch.nn.init.constant_(param.data, 1.0) init.xavier_uniform_(param.data) elif 'weight_hh' in name: # torch.nn.init.constant_(param.data, 0.0) init.xavier_uniform_(param.data) elif 'bias' in name: param.data.fill_(0) source = ColumnDataSource(data={ "epochs": [], "trainlosses": [], "vallosses": [] }) plot = figure() plot.line(x="epochs", y="trainlosses", color="green", alpha=0.8, legend="Train loss", line_width=2, source=source) plot.line(x="epochs", y="vallosses", color="red", alpha=0.8, legend="Val loss", line_width=2, source=source)
def test_plot(): from bokeh.plotting import figure test_plot = figure() test_plot.circle([1, 2], [2, 3]) return test_plot
def __init__(self, bokeh_doc_name, monitor_channels=None, open_browser=False, server_url='http://localhost:5006/', colors=colors): """ Initialize a Bokeh plot! Parameters ---------- bokeh_doc_name : str The name of the Bokeh document. Use a different name for each experiment if you are storing your plots. monitor_channels : list(MonitorsChannel or Monitor) The monitor channels and monitors that you want to plot. The monitors within a :class:`MonitorsChannel` will be plotted together in a single figure. open_browser : bool, optional Whether to try and open the plotting server in a browser window. Defaults to ``True``. Should probably be set to ``False`` when running experiments non-locally (e.g. on a cluster or through SSH). server_url : str, optional Url of the bokeh-server. Ex: when starting the bokeh-server with ``bokeh-server --ip 0.0.0.0`` at ``alice``, server_url should be ``http://alice:5006``. When not specified the default configured to ``http://localhost:5006/``. colors : list(str) The list of string hex codes for colors to cycle through when creating new lines on the same figure. """ # Make sure Bokeh is available if BOKEH_AVAILABLE: monitor_channels = raise_to_list(monitor_channels) if monitor_channels is None: monitor_channels = [] self.channels = monitor_channels self.colors = colors self.bokeh_doc_name = bokeh_doc_name self.server_url = server_url output_server(self.bokeh_doc_name, url=self.server_url) # Create figures for each group of channels self.plots = {} self.figures = [] self.figure_indices = {} self.figure_color_indices = [] # add a potential plot for train_cost self.figures.append(figure(title='{} #{}'.format(bokeh_doc_name, TRAIN_COST_KEY), logo=None, toolbar_location='right')) self.figure_color_indices.append(0) self.figure_indices[TRAIN_COST_KEY] = 0 for i, channel in enumerate(self.channels): idx = i+1 # offset by 1 because of the train_cost figure assert isinstance(channel, MonitorsChannel) or isinstance(channel, Monitor), \ "Need channels to be type MonitorsChannel or Monitor. Found %s" % str(type(channel)) # create the figure self.figures.append(figure(title='{} #{}'.format(bokeh_doc_name, channel.name), x_axis_label='iterations', y_axis_label='value', logo=None, toolbar_location='right')) self.figure_color_indices.append(0) # for each monitor in this channel, assign this figure to the monitor (and train/valid/test variants) if isinstance(channel, MonitorsChannel): for monitor in channel.monitors: self.figure_indices[COLLAPSE_SEPARATOR.join([channel.name, monitor.name])] = idx if monitor.train_flag: self.figure_indices[ COLLAPSE_SEPARATOR.join([channel.name, monitor.name, TRAIN_MARKER]) ] = idx if monitor.valid_flag: self.figure_indices[ COLLAPSE_SEPARATOR.join([channel.name, monitor.name, VALID_MARKER]) ] = idx if monitor.test_flag: self.figure_indices[ COLLAPSE_SEPARATOR.join([channel.name, monitor.name, TEST_MARKER]) ] = idx else: self.figure_indices[channel.name] = idx if channel.train_flag: self.figure_indices[ COLLAPSE_SEPARATOR.join([channel.name, TRAIN_MARKER]) ] = idx if channel.valid_flag: self.figure_indices[ COLLAPSE_SEPARATOR.join([channel.name, VALID_MARKER]) ] = idx if channel.test_flag: self.figure_indices[ COLLAPSE_SEPARATOR.join([channel.name, TEST_MARKER]) ] = idx log.debug("Figure indices for monitors: %s" % str(self.figure_indices)) if open_browser: show(self.figures)
xstop = j * dx; int1 = numerically_integrate(0,xstop,dx,f1,td); int2 = numerically_integrate(0,xstop,dx,f2,td); factor = 2 * mni / td * Math.exp(-Math.pow(xstop/td,2)); L = factor * ((epni-epco) * int1 + epco * int2) / (4.*3.14*Math.pow(distance,2)); y[j] = -2.5 * Math.log10(L*wav/c)-48.3; x[j] = (dx*(1+redshift)) * j + T; } source.change.emit(); """) plot = figure( plot_height=400, plot_width=400, title="Super cool blackbody curve thing", tools="crosshair,pan,reset,save,wheel_zoom", x_range=[np.min(photometry_time) - 20, np.max(photometry_time) + 100], y_range=[np.max(photometry_mag), np.min(photometry_mag)]) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) #plot.line('x', 'yB', source=source, line_width=3, line_alpha=0.6, color="pink") #plot.line('x', 'yr', source=source, line_width=3, line_alpha=0.6, color="orange") #plot.line('x', 'yi', source=source, line_width=3, line_alpha=0.6, color="blue") #plot.line('x', 'yV', source=source, line_width=3, line_alpha=0.6, color="turquoise") #plot.line('x', 'yU', source=source, line_width=3, line_alpha=0.6, color="purple") arrayoftimes = np.array(photometry_time) text = TextInput(title="title", value='my parabola', callback=callback2)
def display_matrix(M, base_size=600): ''' Renders the matrix M as a heatmap. Args: M (numpy's matrix) Matrix to render. base_size (int) Default size (in pixels, I think) of larger dimension. ''' # Work with the underlying array. m = np.asarray(M) n = len(m.flatten()) # Get value range for color computation. min_val = m.min() max_val = m.max() # Massage data into format for plotting a bunch of rectangles. xvals = [] yvals = [] vals = [] colors = [] text_colors = [] for i in range(m.shape[0]): for j in range(m.shape[1]): datum = m[i][j] # Turn the index into plotting coordinates. x = j y = m.shape[0] - i xvals += [x] yvals += [y] # Change display based on numerical type for # cleaner look. if type(datum) is np.int64: vals += [str(datum)] else: vals += ['%0.2f' % (datum)] # Get the background and text color for the cell. bg, txt = get_color(min_val, max_val, n, datum) colors += [bg] text_colors += [txt] # This is the format we stick it in for bokeh plotting. source = ColumnDataSource(data=dict( xvals=xvals, yvals=yvals, colors=colors, )) # Create a figure and remove tje default plotting crap. (Not all of this # may be necessary.) p = figure(tools='', ) p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.minor_tick_line_color = None p.axis.major_label_text_font_size = '0pt' p.axis[0].ticker.num_minor_ticks = 0 p.toolbar_location = None # Shrink size if n_rows != n_cols. Enforce a minimum of 50px so that the # values are visible. n_rows, n_cols = m.shape[0], m.shape[1] rc_ratio = float(n_rows) / n_cols w, h = base_size, base_size if n_rows > n_cols: w = max(50.0 * n_cols, (1.0 / rc_ratio) * base_size) h = max(50.0 * n_rows, rc_ratio * w) elif n_cols > n_rows: h = max(50.0 * n_rows, rc_ratio * base_size) w = max(50.0 * n_cols, (1.0 / rc_ratio) * h) p.plot_width = int(w) p.plot_height = int(h) # Plot and display. p.rect('xvals', 'yvals', 0.9, 0.9, source=source, color='colors') p.text(np.array(xvals) - 0.25, np.array(yvals) - 0.25, vals, text_color=text_colors) show(p)
def plot_picture(dates, states, var_values, confidence_values, save_path, name_dict, s_size=0.1): ## Fig 생성 fig = figure(title=name_dict['title'], x_axis_label='Timeline', x_axis_type='datetime', y_axis_label='score', plot_width=2000, plot_height=500) fig.y_range = Range1d(start=min(var_values), end=max(var_values)) fig.line(dates, var_values, line_width=2, color=name_dict['var_color'], legend_label=name_dict['var_name']) if states is not None and len(dates) > 0: temp_start = dates[0] temp_state = states[0] temp_date = dates[0] for xc, value in zip(dates, states): if temp_state != value: if temp_state == 'prognosis': fig.add_layout( BoxAnnotation(left=temp_start, right=temp_date, fill_alpha=0.2, fill_color='blue')) if temp_state == 'abnormal': fig.add_layout( BoxAnnotation(left=temp_start, right=temp_date, fill_alpha=0.2, fill_color='orange')) temp_start = xc temp_state = value temp_date = xc if temp_state == 'prognosis': fig.add_layout( BoxAnnotation(left=temp_start, right=xc, fill_alpha=0.2, fill_color='blue')) if temp_state == 'abnormal': fig.add_layout( BoxAnnotation(left=temp_start, right=xc, fill_alpha=0.2, fill_color='orange')) if confidence_values is not None: fig.extra_y_ranges = { "var": Range1d(start=-1, end=max(confidence_values) + 1) } fig.add_layout(LinearAxis(y_range_name="var"), 'right') fig.line(dates, confidence_values, legend_label=name_dict['confidence_name'], line_width=2, y_range_name='var', color=name_dict['confidence_color'], line_alpha=.3) fig.legend.click_policy = 'hide' output_file(filename=save_path) save(fig)
def assembly_chart(df, complements): """function to assembly the chart""" print('starting the plot...') # specify the output file name output_file("movigrama_chart.html") # force to show only one plot when multiples executions of the code occur # otherwise the plots will append each time one new calling is done reset_output() # create ColumnDataSource objects directly from Pandas data frames source = ColumnDataSource(df) # use the column DT as index df.set_index('DT', inplace=True) ########################################################################### # # Movigrama Plot # ########################################################################### # build figure of the plot p = figure(x_axis_type='datetime', x_axis_label='days of moviment', y_axis_label='unities movimented', plot_width=1230, plot_height=500, active_scroll='wheel_zoom') # TODO Specify X range (not all plots have 365 days of moviment) # build the Stock Level bar r1 = p.vbar(x='DT', bottom=0, top='STOCK', width=pd.Timedelta(days=1), fill_alpha=0.4, color='paleturquoise', source=source) # build the OUT bar p.vbar(x='DT', bottom=0, top='SOMA_SAI', width=pd.Timedelta(days=1), fill_alpha=0.8, color='crimson', source=source) # build the IN bar p.vbar(x='DT', bottom=0, top='SOMA_ENTRA', width=pd.Timedelta(days=1), fill_alpha=0.8, color='seagreen', source=source) # edit title # adds warehouse title p.add_layout( Title(text=complements['warehouse'], text_font='helvetica', text_font_size='10pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="italic"), 'above') # adds product title p.add_layout( Title(text=complements['product'], text_font='helvetica', text_font_size='10pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="italic"), 'above') # adds main title p.add_layout( Title(text='Movigrama Endicon', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.9, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p.renderers.extend([hline]) # adapt the range to the plot p.x_range.range_padding = 0.1 p.y_range.range_padding = 0.1 # format the plot's outline p.outline_line_width = 4 p.outline_line_alpha = 0.1 p.outline_line_color = 'orangered' # format major labels p.axis.major_label_text_color = 'gray' p.axis.major_label_text_font_style = 'bold' # format labels p.axis.axis_label_text_color = 'gray' p.axis.axis_label_text_font_style = 'bold' # p.xgrid.grid_line_color = None # disable vertical bars # p.ygrid.grid_line_color = None # disable horizontal bars # change placement of minor and major ticks in the plot p.axis.major_tick_out = 10 p.axis.minor_tick_in = -3 p.axis.minor_tick_out = 6 p.axis.minor_tick_line_color = 'gray' # format properly the X datetime axis p.xaxis.formatter = DatetimeTickFormatter(days=['%d/%m'], months=['%m/%Y'], years=['%Y']) # initiate hover object hover = HoverTool() hover.mode = "vline" # activate hover by vertical line hover.tooltips = [("SUM-IN", "@SOMA_ENTRA"), ("SUM-OUT", "@SOMA_SAI"), ("COUNT-IN", "@TRANSACT_ENTRA"), ("COUNT-OUT", "@TRANSACT_SAI"), ("STOCK", "@STOCK"), ("DT", "@DT{%d/%m/%Y}")] # use 'datetime' formatter for 'DT' field hover.formatters = {"DT": 'datetime'} hover.renderers = [r1] # display tooltip only to one render p.add_tools(hover) ########################################################################### # # Demand analysis # ########################################################################### # change to positive values df['out_invert'] = df['SOMA_SAI'] * -1 # moving average with n=30 days df['MA30'] = df['out_invert'].rolling(30).mean().round(0) # moving standard deviation with n=30 days df['MA30_std'] = df['out_invert'].rolling(30).std().round(0) # lower control limit for 1 sigma deviation df['lcl_1sigma'] = (df['MA30'] - df['MA30_std']) # upper control limit for 1 sigma deviation df['ucl_1sigma'] = (df['MA30'] + df['MA30_std']) source = ColumnDataSource(df) p1 = figure(plot_width=1230, plot_height=500, x_range=p.x_range, x_axis_type="datetime", active_scroll='wheel_zoom') # build the Sum_out bar r1 = p1.vbar(x='DT', top='out_invert', width=pd.Timedelta(days=1), color='darkred', line_color='salmon', fill_alpha=0.4, source=source) # build the moving average line p1.line(x='DT', y='MA30', source=source) # build the confidence interval band = Band(base='DT', lower='lcl_1sigma', upper='ucl_1sigma', source=source, level='underlay', fill_alpha=1.0, line_width=1, line_color='black') p1.renderers.extend([band]) # adds title p1.add_layout( Title(text='Demand Variability', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p1.renderers.extend([hline]) # format the plot's outline p1.outline_line_width = 4 p1.outline_line_alpha = 0.1 p1.outline_line_color = 'orangered' # format major labels p1.axis.major_label_text_color = 'gray' p1.axis.major_label_text_font_style = 'bold' # format labels p1.axis.axis_label_text_color = 'gray' p1.axis.axis_label_text_font_style = 'bold' # change placement of minor and major ticks in the plot p1.axis.major_tick_out = 10 p1.axis.minor_tick_in = -3 p1.axis.minor_tick_out = 6 p1.axis.minor_tick_line_color = 'gray' # format properly the X datetime axis p1.xaxis.formatter = DatetimeTickFormatter(days=['%d/%m'], months=['%m/%Y'], years=['%Y']) # initiate hover object hover = HoverTool() hover.mode = "vline" # activate hover by vertical line hover.tooltips = [("DEMAND", '@out_invert'), ("UCL 1σ", "@ucl_1sigma"), ("LCL 1σ", "@lcl_1sigma"), ("M AVG 30d", "@MA30"), ("DT", "@DT{%d/%m/%Y}")] # use 'datetime' formatter for 'DT' field hover.formatters = {"DT": 'datetime'} hover.renderers = [r1] # display tooltip only to one render p1.add_tools(hover) ########################################################################### # # Demand grouped by month # ########################################################################### resample_M = df.iloc[:, 0:6].resample('M').sum() # resample to month # create column date as string resample_M['date'] = resample_M.index.strftime('%b/%y').values # moving average with n=3 months resample_M['MA3'] = resample_M['out_invert'].rolling(3).mean() resample_M['MA3'] = np.ceil(resample_M.MA3) # round up the column MA3 # resample to month with mean resample_M['mean'] = np.ceil(resample_M['out_invert'].mean()) # resample to month with standard deviation resample_M['std'] = np.ceil(resample_M['out_invert'].std()) # moving standard deviation with n=30 days resample_M['MA3_std'] = np.ceil(resample_M['out_invert'].rolling(3).std()) # lower control limit for 1 sigma deviation resample_M['lcl_1sigma'] = resample_M['MA3'] - resample_M['MA3_std'] # upper control limit for 1 sigma deviation resample_M['ucl_1sigma'] = resample_M['MA3'] + resample_M['MA3_std'] source = ColumnDataSource(resample_M) p2 = figure(plot_width=1230, plot_height=500, x_range=FactorRange(factors=list(resample_M.date)), title='demand groupped by month') colors = factor_cmap('date', palette=Category20_20, factors=list(resample_M.date)) p2.vbar(x='date', top='out_invert', width=0.8, fill_color=colors, fill_alpha=0.8, source=source, legend=value('OUT')) p2.line(x='date', y='MA3', color='red', line_width=3, line_dash='dotted', source=source, legend=value('MA3')) p2.line(x='date', y='mean', color='blue', line_width=3, line_dash='dotted', source=source, legend=value('mean')) band = Band(base='date', lower='lcl_1sigma', upper='ucl_1sigma', source=source, level='underlay', fill_alpha=1.0, line_width=1, line_color='black') labels1 = LabelSet(x='date', y='MA3', text='MA3', level='glyph', y_offset=5, source=source, render_mode='canvas', text_font_size="8pt", text_color='darkred') labels2 = LabelSet(x='date', y='out_invert', text='out_invert', level='glyph', y_offset=5, source=source, render_mode='canvas', text_font_size="8pt", text_color='gray') low_box = BoxAnnotation( top=resample_M['mean'].iloc[0] - resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='red') mid_box = BoxAnnotation( bottom=resample_M['mean'].iloc[0] - resample_M['std'].iloc[0], # analysis:ignore top=resample_M['mean'].iloc[0] + resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='green') high_box = BoxAnnotation( bottom=resample_M['mean'].iloc[0] + resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='red') p2.renderers.extend([band, labels1, labels2, low_box, mid_box, high_box]) p2.legend.click_policy = "hide" p2.legend.background_fill_alpha = 0.4 p2.add_layout( Title(text='Demand Grouped by Month', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p2.renderers.extend([hline]) # format the plot's outline p2.outline_line_width = 4 p2.outline_line_alpha = 0.1 p2.outline_line_color = 'orangered' # format major labels p2.axis.major_label_text_color = 'gray' p2.axis.major_label_text_font_style = 'bold' # format labels p2.axis.axis_label_text_color = 'gray' p2.axis.axis_label_text_font_style = 'bold' # change placement of minor and major ticks in the plot p2.axis.major_tick_out = 10 p2.axis.minor_tick_in = -3 p2.axis.minor_tick_out = 6 p2.axis.minor_tick_line_color = 'gray' # initiate hover object # TODO develop hoverTool # hover = HoverTool() # hover.mode = "vline" # activate hover by vertical line # hover.tooltips = [("SUM-IN", "@SOMA_ENTRA"), # ("SUM-OUT", "@SOMA_SAI"), # ("COUNT-IN", "@TRANSACT_ENTRA"), # ("COUNT-OUT", "@TRANSACT_SAI"), # ("STOCK", "@STOCK")] # hover.renderers = [r1] # display tooltip only to one render # p2.add_tools(hover) ########################################################################### # # Plot figures # ########################################################################### # put the results in a column and show show(column(p, p1, p2)) # show(p) # plot action print('plot finished')