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 get_plottag(script_path): """ Saves js in script_path and returns tag for embedding in html """ import numpy as np import pandas as pd import os y_data = np.random.randn(100) x_data = pd.date_range('31-Aug-2014', periods=len(y_data)) figure(x_axis_type='datetime', tools='pan,wheel_zoom,box_zoom,reset,previewsave,crosshair', name='test plot') hold() line(x_data, y_data, line_color="#D95B43", line_width=4, alpha=0.7, legend='random', background_fill= '#cccccc') circle(x_data, y_data, color='red', fill_color=None, size=6, legend='random') curplot().title = 'Test Plot' xaxis().axis_label='date' yaxis().axis_label='some random numbers' grid().grid_line_color='white' grid().grid_line_alpha = 0.5 plotid = curplot()._id script_path = os.path.join(script_path, plotid+'.js') js, tag = autoload_static(curplot(), CDN, script_path=script_path) with open(script_path, 'w') as f: f.write(js) return tag
def bokeh_nn(s_channels, testset, errors, title='no title', swap_xy=True, x_range=None, y_range=None, radius=3.0, alpha=0.75): x_range, y_range = ranges(s_channels, x_range=x_range, y_range=y_range) xv, yv = zip(*testset) if swap_xy: x_range, y_range = y_range, x_range xv, yv = yv, xv scale = [0, max(errors)] colorbar = ColorBar(scale, ['#0000FF', '#FF0000'], continuous=True) colors = [colorbar.color(e) for e in errors] plotting.scatter(xv, yv, title=title, x_range=x_range, y_range=y_range, fill_color=colors, fill_alpha=alpha, line_color=None, radius=radius, radius_units="screen") plotting.hold(True) plotting.grid().grid_line_color = 'white' plotting.hold(False)
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 bokeh_quantiles(ticks, avgs, quantiles, color='#000055', alpha=1.0, **kwargs): plotting.line(ticks, avgs, color=color, line_alpha=alpha, title_text_font_size='6pt', **kwargs) plotting.hold(True) if quantiles is not None: print(quantiles) x_std = list(ticks) + list(reversed(ticks)) y_std = ([q_min for q_min, q_max in quantiles] + list(reversed([q_max for q_min, q_max in quantiles]))) plotting.patch(x_std, y_std, fill_color=color, fill_alpha=alpha * 0.25, line_color=None) plotting.grid().grid_line_color = 'white' plotting_axis() plotting.hold(False)
def perf_std_discrete(ticks, avgs, stds, legend=None, std_width=0.3, plot_width=1000, plot_height=300, color=BLUE, alpha=1.0, **kwargs): plotting.rect(ticks, avgs, [std_width for _ in stds], 2 * np.array(stds), line_color=None, fill_color=color, fill_alpha=alpha * 0.5, plot_width=plot_width, plot_height=plot_height, **kwargs) plotting.hold(True) plotting.line(ticks, avgs, line_color=color, line_alpha=alpha, legend=legend) plotting.circle(ticks, avgs, line_color=None, fill_color=color, fill_alpha=alpha) plotting.grid().grid_line_color = 'white' plotting_axis() plotting.hold(False)
def bokeh_nn( s_channels, testset, errors, title="no title", swap_xy=True, x_range=None, y_range=None, radius=3.0, alpha=0.75 ): x_range, y_range = ranges(s_channels, x_range=x_range, y_range=y_range) xv, yv = zip(*testset) if swap_xy: x_range, y_range = y_range, x_range xv, yv = yv, xv scale = [0, max(errors)] colorbar = ColorBar(scale, ["#0000FF", "#FF0000"], continuous=True) colors = [colorbar.color(e) for e in errors] plotting.scatter( xv, yv, title=title, x_range=x_range, y_range=y_range, fill_color=colors, fill_alpha=alpha, line_color=None, radius=radius, radius_units="screen", ) plotting.hold(True) plotting.grid().grid_line_color = "white" plotting.hold(False)
def mesh(meshgrid, s_vectors=(), s_goals=(), mesh_timescale=(1000000,), mesh_colors=(C_COLOR_H,), title='no title', e_radius=1.0, e_color=E_COLOR, e_alpha=0.75, g_radius=1.0, g_color=G_COLOR, g_alpha=0.75, swap_xy=True, tile_ratio=0.97, x_range=None, y_range=None): x_range, y_range = ranges(meshgrid.s_channels, x_range=x_range, y_range=y_range) xm = zip(*[b.bounds[0] for b in meshgrid.nonempty_bins]) ym = zip(*[b.bounds[1] for b in meshgrid.nonempty_bins]) if swap_xy: x_range, y_range = y_range, x_range xm, ym = ym, xm color = [] for b in meshgrid.nonempty_bins: t = b.elements[0][0] color.append(mesh_colors[bisect.bisect_left(mesh_timescale, t)]) plotting.rect((np.array(xm[1])+np.array(xm[0]))/2 , (np.array(ym[1])+np.array(ym[0]))/2, (np.array(xm[1])-np.array(xm[0]))*tile_ratio, (np.array(ym[1])-np.array(ym[0]))*tile_ratio, x_range=x_range, y_range=y_range, fill_color=color, fill_alpha=0.5, line_color='#444444', line_alpha=0.0, title=title) plotting.hold(True) plotting.grid().grid_line_color='white' spread(meshgrid.s_channels, s_vectors=s_vectors, s_goals=s_goals, swap_xy=swap_xy, e_radius=e_radius, e_color=e_color, e_alpha=e_alpha, g_radius=g_radius, g_color=g_color, g_alpha=g_alpha) plotting.hold(False)
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 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 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 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 startPlot(self, **kwargs): """prepare everything for a plot. returns the current figure. """ bk.figure() bk.output_file('/dev/null') bk.hold()
def plotScatter(data): data_to_plot = data.dropna() pl.output_file("scatter.html") pl.figure() pl.hold() pl.scatter(data["Fare"],data["Age"], color=data["Survived"].map(colormap),alpha=0.8, xlabel="Fare") pl.show()
def bokeh_plot(data, outfile): table = np.genfromtxt(data, names=['x', 'y']) blt.output_file(outfile) blt.hold() blt.figure(tools="pan,wheel_zoom,box_zoom,reset,previewsave,select") blt.scatter(table['x'], table['y']) blt.show()
def radialchart(nodes, edgelist): ids, times, relevances = nodes.T times *= 2 node_x, node_y = _radial_layout(nodes) nodepos = np.asarray((node_x, node_y)).T hold() circle(node_x, node_y, color="red", size=relevances * 4, alpha=relevances) coords = nodepos[edgelist].reshape((len(edgelist), 4)).T segment(coords[0], coords[1], coords[2], coords[3], line_alpha=0.35)
def mesh(meshgrid, s_vectors=(), s_goals=(), mesh_timescale=(1000000, ), mesh_colors=(C_COLOR_H, ), title='no title', e_radius=1.0, e_color=E_COLOR, e_alpha=0.75, g_radius=1.0, g_color=G_COLOR, g_alpha=0.75, swap_xy=True, tile_ratio=0.97, x_range=None, y_range=None): x_range, y_range = ranges(meshgrid.s_channels, x_range=x_range, y_range=y_range) xm = zip(*[b.bounds[0] for b in meshgrid.nonempty_bins]) ym = zip(*[b.bounds[1] for b in meshgrid.nonempty_bins]) if swap_xy: x_range, y_range = y_range, x_range xm, ym = ym, xm color = [] for b in meshgrid.nonempty_bins: t = b.elements[0][0] color.append(mesh_colors[bisect.bisect_left(mesh_timescale, t)]) plotting.rect((np.array(xm[1]) + np.array(xm[0])) / 2, (np.array(ym[1]) + np.array(ym[0])) / 2, (np.array(xm[1]) - np.array(xm[0])) * tile_ratio, (np.array(ym[1]) - np.array(ym[0])) * tile_ratio, x_range=x_range, y_range=y_range, fill_color=color, fill_alpha=0.5, line_color='#444444', line_alpha=0.0, title=title) plotting.hold(True) plotting.grid().grid_line_color = 'white' spread(meshgrid.s_channels, s_vectors=s_vectors, s_goals=s_goals, swap_xy=swap_xy, e_radius=e_radius, e_color=e_color, e_alpha=e_alpha, g_radius=g_radius, g_color=g_color, g_alpha=g_alpha) plotting.hold(False)
def posture_signals(kin_env, m_signals, title='posture graphs', color='#666666', alpha=1.0, radius_factor=1.0, swap_xy=True, x_range=[-1.0, 1.0], y_range=[-1.0, 1.0], **kwargs): for m_signal in m_signals: m_vector = kin_env.flatten_synergies(m_signal) s_signal = kin_env._multiarm.forward_kin(m_vector) xs, ys = [0.0], [0.0] for i in range(kin_env.cfg.dim): xs.append(s_signal['x{}'.format(i + 1)]) ys.append(s_signal['y{}'.format(i + 1)]) if isinstance(kin_env.cfg.lengths, numbers.Real): total_length = kin_env.cfg.lengths * kin_env.cfg.dim else: total_length = sum(kin_env.cfg.lengths) total_length += 0.0 kwargs.update({ 'x_range': x_range, 'y_range': y_range, 'line_color': color, 'line_alpha': alpha, 'fill_color': color, 'fill_alpha': alpha, 'title': title }) if swap_xy: xs, ys = ys, xs plotting.line(xs, ys, line_width=2.0 * radius_factor, **kwargs) plotting.hold(True) plotting.grid().grid_line_color = None plotting.ygrid().grid_line_color = None plotting_axis() plotting.circle(xs[:1], ys[:1], radius=radius_factor * 0.015, **kwargs) plotting.circle(xs[1:-1], ys[1:-1], radius=radius_factor * 0.008, **kwargs) plotting.circle(xs[-1:], ys[-1:], radius=radius_factor * 0.01, color='red', alpha=alpha) plotting.hold(False)
def radialchart(nodes, edgelist): ids, times, relevances = nodes.T times *= 2 node_x, node_y = _radial_layout(nodes) nodepos = np.asarray((node_x, node_y)).T hold() circle(node_x, node_y, color="red", size=relevances*4, alpha=relevances) coords = nodepos[edgelist].reshape((len(edgelist), 4)).T segment(coords[0], coords[1], coords[2], coords[3], line_alpha=0.35)
def __init__(self, username=None, serverloc=None, userapikey="nokey", arrayserver_port=10020): self.arrayserver_port = arrayserver_port super(CDXSession, self).__init__(username=username, serverloc=serverloc, userapikey=userapikey) #hack... ? plotting._config["session"] = self plotting._config["output_url"] = self.root_url plotting._config["output_type"] = "server" plotting._config["output_file"] = None plotting.hold(False)
def build_punchcard(datamap_list, concept_list, radii_list, fields_in_concept_list, datamaps, concepts, plot_width=1200, plot_height=800): source = ColumnDataSource( data=dict( datamap=datamap_list, # x concept=concept_list, # y radii=radii_list, fields_in_concept=fields_in_concept_list, ) ) output_file('') hold() figure() plot_properties = { 'title': None, 'tools': "hover,resize,previewsave", 'y_range': [get_datamap_label(datamap) for datamap in datamaps], 'x_range': concepts, 'plot_width': plot_width, 'plot_height': plot_height, } rect('concept', 'datamap', # x, y 1, 1, # height, width source=source, color='white', # put in background **plot_properties) circle('concept', 'datamap', # x, y size='radii', source=source, color='black', **plot_properties) grid().grid_line_color = None x = xaxis() x.major_label_orientation = pi / 4 hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0] hover.tooltips = OrderedDict([ ("Datamap", "@datamap"), ("Concept", "@concept"), ("Fields", "@fields_in_concept"), ]) return curplot().create_html_snippet( static_path=settings.STATIC_URL, embed_save_loc=settings.BOKEH_EMBED_JS_DIR, embed_base_url=reverse('bokeh'), )
def line(x_range, avg, std, color='#E84A5F', dashes=(4, 2), alpha=1.0): plotting.line(x_range, [avg, avg], line_color=color, line_dash=list(dashes), line_alpha=alpha) plotting.hold(True) plotting.rect([(x_range[0] + x_range[1]) / 2.0], [avg], [x_range[1] - x_range[0]], [2 * std], fill_color=color, line_color=None, fill_alpha=0.1 * alpha) plotting.hold(False)
def posture_signals( kin_env, m_signals, title="posture graphs", color="#666666", alpha=1.0, radius_factor=1.0, swap_xy=True, x_range=[-1.0, 1.0], y_range=[-1.0, 1.0], **kwargs ): for m_signal in m_signals: m_vector = kin_env.flatten_synergies(m_signal) s_signal = kin_env._multiarm.forward_kin(m_vector) xs, ys = [0.0], [0.0] for i in range(kin_env.cfg.dim): xs.append(s_signal["x{}".format(i + 1)]) ys.append(s_signal["y{}".format(i + 1)]) if isinstance(kin_env.cfg.lengths, numbers.Real): total_length = kin_env.cfg.lengths * kin_env.cfg.dim else: total_length = sum(kin_env.cfg.lengths) total_length += 0.0 kwargs.update( { "x_range": x_range, "y_range": y_range, "line_color": color, "line_alpha": alpha, "fill_color": color, "fill_alpha": alpha, "title": title, } ) if swap_xy: xs, ys = ys, xs plotting.line(xs, ys, line_width=2.0 * radius_factor, **kwargs) plotting.hold(True) plotting.grid().grid_line_color = None plotting.ygrid().grid_line_color = None plotting_axis() plotting.circle(xs[:1], ys[:1], radius=radius_factor * 0.015, **kwargs) plotting.circle(xs[1:-1], ys[1:-1], radius=radius_factor * 0.008, **kwargs) plotting.circle(xs[-1:], ys[-1:], radius=radius_factor * 0.01, color="red", alpha=alpha) plotting.hold(False)
def drawPlot(shapeFilename, zipBorough): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = {'lat_list': [], 'lng_list': []} record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: zipCodes.append(currentZip) # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start : end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("zipCodes.html") bk.hold() TOOLS="pan,wheel_zoom,box_zoom,reset,previewsave" bk.figure(title="Zip codes in NY", \ tools=TOOLS, plot_width=1200, plot_height=800) # Creates the polygons. bk.patches(polygons['lng_list'], polygons['lat_list'], \ fill_color='#fee8c8', line_color="gray") bk.show()
def perf_std_discrete(ticks, avgs, stds, legend=None, std_width=0.3, plot_width=1000, plot_height=300, color=BLUE, alpha=1.0, **kwargs): plotting.rect(ticks, avgs, [std_width for _ in stds], 2*np.array(stds), line_color=None, fill_color=color, fill_alpha=alpha*0.5, plot_width=plot_width, plot_height=plot_height, **kwargs) plotting.hold(True) plotting.line(ticks, avgs, line_color=color, line_alpha=alpha, legend=legend) plotting.circle(ticks, avgs, line_color=None, fill_color=color, fill_alpha=alpha) plotting.grid().grid_line_color = 'white' plotting_axis() plotting.hold(False)
def line(x_range, avg, std, color="#E84A5F", dashes=(4, 2), alpha=1.0): plotting.line(x_range, [avg, avg], line_color=color, line_dash=list(dashes), line_alpha=alpha) plotting.hold(True) plotting.rect( [(x_range[0] + x_range[1]) / 2.0], [avg], [x_range[1] - x_range[0]], [2 * std], fill_color=color, line_color=None, fill_alpha=0.1 * alpha, ) plotting.hold(False)
def bokeh_quantiles(ticks, avgs, quantiles, color="#000055", alpha=1.0, **kwargs): plotting.line(ticks, avgs, color=color, line_alpha=alpha, title_text_font_size="6pt", **kwargs) plotting.hold(True) if quantiles is not None: print(quantiles) x_std = list(ticks) + list(reversed(ticks)) y_std = [q_min for q_min, q_max in quantiles] + list(reversed([q_max for q_min, q_max in quantiles])) plotting.patch(x_std, y_std, fill_color=color, fill_alpha=alpha * 0.25, line_color=None) plotting.grid().grid_line_color = "white" plotting_axis() plotting.hold(False)
def plotHistogram(data): data_to_plot = data["Age"] data_to_plot = data_to_plot[-np.isnan(data_to_plot)] hist,edges = np.histogram(data_to_plot,bins=20) pl.output_file('histogram.html') pl.figure() pl.hold() pl.quad(top=hist,bottom=0,left=edges[:-1],right=edges[1:], fill_color="#036564", line_color="#033649", title="Age distribution",xlabel="Age",ylabel="Number") pl.show()
def make_box_violin_plot_2(data, maxwidth=0.9): """ data: dict[Str -> List[Number]] maxwidth: float Maximum width of tornado plot within each factor/facet Returns the plot object """ df = pd.DataFrame(columns=["group", "centers", "width", "height", "texts"]) bar_height = 50 bins = [0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6] # Compute histograms, while keeping track of max Y values and max counts for i, (group, vals) in enumerate(data.iteritems()): hist, edges = np.histogram(vals, bins) df = df.append(pd.DataFrame(dict( group = group, centers = np.arange(len(hist))*bar_height, width = np.log10(hist), height = np.ones(hist.shape)*bar_height, texts = map(str,hist), ))) df.replace(-np.inf, 0) # Normalize the widths df["width"] *= (maxwidth / df["width"].max()) hold() width, height = 800, 800 figure(plot_width=width, plot_height=height, title="Degree Distribution", tools="previewsave", x_axis_type=None, y_axis_type=None, x_range=[-420, 420], y_range=[-420, 420], x_axis_label="Number of nodes (log)", y_label="distribution of degree", min_border=0, outline_line_color=None, background_fill="#f0e1d2", border_fill="#f0e1d2") size = len(df) rect(np.zeros(size), df["centers"], height=[50 for i in range(size)], width=df["width"]*width * .8) text(np.zeros(size), df["centers"], text=df["texts"], angle=np.zeros(size), text_color= ["#000000"] + ["#FFFFFF" for i in xrange(size-1)], text_align="center", text_baseline="middle") text(np.ones(size+1) * -width/2, [(idx-0.75)*bar_height for idx in range(size+1)], text=map(str, map(int, bins)), angle=0) show()
def drawPlot(shapeFilename, zipBorough): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = {'lat_list': [], 'lng_list': []} record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: zipCodes.append(currentZip) # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start:end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("zipCodes.html") bk.hold() TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave" bk.figure(title="Zip codes in NY", \ tools=TOOLS, plot_width=1200, plot_height=800) # Creates the polygons. bk.patches(polygons['lng_list'], polygons['lat_list'], \ fill_color='#fee8c8', line_color="gray") bk.show()
def test_figure(self): p = plt.figure() self.assertEqual(plt.curplot(), p) q = plt.circle([1,2,3], [1,2,3]) self.assertEqual(plt.curplot(), q) self.assertNotEqual(p, q) r = plt.figure() self.assertEqual(plt.curplot(), r) self.assertNotEqual(p, r) self.assertNotEqual(q, r) plt.hold() s = plt.circle([1,2,3], [1,2,3]) self.assertEqual(plt.curplot(), s) self.assertEqual(r, s)
def crawlchart(nodes, edgelist): """ edges is an Nx2 array of node ids """ ids, times, relevances = nodes.T times *= 2 node_y = _rectilinear_layout(nodes) hold() #circle(times, node_y, color="gray", size=1) # Draw the relevant points in a different color circle(times, node_y, color="red", size=relevances * 6, alpha=relevances) nodepos = np.asarray((times, node_y)).T coords = nodepos[edgelist].reshape((len(edgelist), 4)).T segment(coords[0], coords[1], coords[2], coords[3], line_alpha=0.35)
def merge(*args, **kwargs): import bokeh.plotting as bk bk.figure() bk.hold() y = kwargs.get('y', None) x = kwargs.get('x', 'Pos') try: kwargs.pop('y') kwargs.pop('x') except: pass y = (y if type(y) == list else [y] * len(args)) #FIXME do the same for x for yi, p in zip(y, args): p.show(x=x, y=yi, color=next(kwargs["colors"]), **kwargs) return bk.curplot()
def merge(*args, **kwargs): import bokeh.plotting as bk bk.figure() bk.hold() y = kwargs.get('y',None) x = kwargs.get('x','Pos') try: kwargs.pop('y') kwargs.pop('x') except: pass y = (y if type(y) == list else [y]*len(args)) #FIXME do the same for x for yi,p in zip(y,args): p.show(x=x, y=yi, color=next(kwargs["colors"]), **kwargs) return bk.curplot()
def crawlchart(nodes, edgelist): """ edges is an Nx2 array of node ids """ ids, times, relevances = nodes.T times *= 2 node_y = _rectilinear_layout(nodes) hold() #circle(times, node_y, color="gray", size=1) # Draw the relevant points in a different color circle(times, node_y, color="red", size=relevances*6, alpha=relevances) nodepos = np.asarray((times,node_y)).T coords = nodepos[edgelist].reshape((len(edgelist), 4)).T segment(coords[0], coords[1], coords[2], coords[3], line_alpha=0.35)
def draw(self, x, y, z, title, func, **kwargs): import bokeh.plotting as bk #TODO: change colors if y is of list type y = (y if type(y) == list else [y]) # wrap y to a list so that we can iterate kwargs.update({ "outline_line_color":"black", #FIXME refactor "plot_width":300, "plot_height":300, }) bk.hold(True) for yi in y: x_data, y_data = self[x], self[yi] func(x=x_data, y=y_data, title=title, **kwargs) bk.hold(False) ret = bk.curplot() def _label(axis, field): label = kwargs.get(axis + '_label', False) if label: self.properties.plot_properties.insert(field, {axis + '_label':label}) else: label = self.properties.plot_properties.select(field, axis + '_label', "None") return label def _range(axis, field): from bokeh.objects import Range1d p_range_args = kwargs.get(axis + '_range', False) if p_range_args: self.properties.plot_properties.insert(field, {axis + '_range': p_range}) else: p_range = self.properties.plot_properties.select(field, axis + '_range') if not p_range: return False else: return Range1d(start=p_range[0], end=p_range[1]) bk.xaxis().axis_label = _label('x', x) if _range('x', x): ret.x_range = _range('x', x) bk.yaxis().axis_label = _label('y', y[0]) #TODO can this make sense for multiplots? if _range('y', y[0]): ret.y_range = _range('y', y[0]) return ret
def tweetsGraph(): logger.info("Drawing graphs to %s" % path_to_graphs+"Stats.html") stat_db_cursor.execute('SELECT * FROM tweets') tweets = stat_db_cursor.fetchall() date, volume, cumulative, volumePast24h = zip(*[(datetime.datetime.strptime(t['date'], "%Y-%m-%dT%H"), t['current_hour'], t['cumulative'], t['past_24h']) for t in tweets]) hourly =zip([datetime.datetime(year=d.year, month=d.month, day=d.day) for d in date],volume) hourly.sort() days, dailyVolume = zip(*[(d, sum([v[1] for v in vol])) for d,vol in itertools.groupby(hourly, lambda i:i[0])]) bokeh_plt.output_file(path_to_graphs+"Stats.html") bokeh_plt.hold() bokeh_plt.quad(days, [d+datetime.timedelta(days=1) for d in days], dailyVolume, [0]*len(dailyVolume), x_axis_type="datetime", color='gray', legend="Daily volume") bokeh_plt.line(date, volume, x_axis_type="datetime", color='red', legend="Hourly volume") bokeh_plt.line(date, volumePast24h, x_axis_type="datetime", color='green', legend="Volume in the past 24 hours") bokeh_plt.curplot().title = "Volume" bokeh_plt.figure() bokeh_plt.line(date, cumulative, x_axis_type="datetime") bokeh_plt.curplot().title = "Cumulative volume" fig, ax = matplotlib_plt.subplots() f=DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(f) matplotlib_plt.plot(date, volume) matplotlib_plt.plot(date, volumePast24h) matplotlib_plt.plot(days, dailyVolume) matplotlib_plt.xticks(np.concatenate((np.array(date)[range(0,len(date),24*7)],[date[-1]])), rotation=70) matplotlib_plt.savefig(path_to_graphs+"volume.png", bbox_inches="tight") stat_db_cursor.execute('SELECT * FROM users') users = stat_db_cursor.fetchall() date, nUsers, nUsersWithFriends = zip(*[(datetime.datetime.strptime(u['date'], "%Y-%m-%dT%H:%M:%S.%f"), u['total'], u['with_friends']) for u in users]) bokeh_plt.figure() bokeh_plt.line(date, nUsers, x_axis_type="datetime", legend="Total") bokeh_plt.line(date, nUsersWithFriends, x_axis_type="datetime", legend="Friendship collected") bokeh_plt.legend().orientation = "top_left" bokeh_plt.curplot().title = "Number of users" bokeh_plt.save() matplotlib_plt.figure() fig, ax = matplotlib_plt.subplots() f=DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(f) matplotlib_plt.plot(date, nUsers) matplotlib_plt.plot(date, nUsersWithFriends) matplotlib_plt.xticks(np.concatenate((np.array(date)[range(0,len(date),24*7)],[date[-1]])), rotation=70) matplotlib_plt.savefig(path_to_graphs+"users.png", bbox_inches="tight")
def _draw(self, x, y, z, overlay, inst_func, **kwargs): import bokeh.plotting as bk import numpy as np def greatest_divisor(number): if number == 1: return 1 for i in reversed(range(number)): if number % i == 0: return i else: return 1 if not overlay: rows = [] for name, instance in self.cases.iteritems(): bk.figure() rows.append( getattr(instance, inst_func)(x=x, y=y, title=str(name), **kwargs) #FIXME num cars ) rows = np.array(rows).reshape(greatest_divisor(len(rows)), -1).tolist() return bk.GridPlot(children=rows, title="Scatter") else: bk.hold() colors = plot.next_color() exp_legend = kwargs.get("legend", None) if exp_legend != None: kwargs.pop("legend") exp_title = kwargs.get("title", None) if exp_title != None: kwargs.pop("title") for name, instance in self.cases.iteritems(): color = next(colors) legend = (exp_legend if exp_legend != None else name) title = (exp_title if exp_title != None else "") getattr(instance, inst_func)(x=x, y=y, title=title, color=color, legend=legend, **kwargs) bk.hold(False) return bk.curplot()
def graph(): print("Graphing") with open(DATA_FILE, "rb") as fin: issues = [Issue(x) for x in pickle.load(fin)] plotting.output_file("{}.{}.html".format(GH_USER, GH_REPO), title="ghantt.py") numbers = [iss.number for iss in issues] source = ColumnDataSource( data=dict( number = [iss.number for iss in issues], ago = [iss.ago + iss.length/2 for iss in issues], length = [iss.length for iss in issues], title = [iss.title for iss in issues], pull_request = [iss.pull_request for iss in issues], color = [assign_color(iss) for iss in issues], since = ["{} days".format(int(abs(iss.ago))) for iss in issues], ), ) plotting.hold() plotting.rect("ago", "number", "length", 1, source=source, color="color", title="{}/{}".format(GH_USER, GH_REPO), y_range=(min(numbers), max(numbers)), tools="resize,hover,previewsave,pan,wheel_zoom", fill_alpha=0.8) text_props = { "source": source, "angle": 0, "color": "black", "text_align": "left", "text_baseline": "middle" } plotting.grid().grid_line_color = None hover = [t for t in plotting.curplot().tools if isinstance(t, HoverTool)][0] hover.tooltips = OrderedDict([ ("number", "@number"), ("title", "@title"), ("since", "@since"), ("pull_request", "@pull_request"), ]) plotting.show()
def count_by_day_graph(collection_name): # TODO: выделить на графике выходные дни import numpy as np from bokeh.plotting import output_file, hold, figure, line, curplot, grid, show a = count_by_day(collection_name) output_file("output/count_by_day_graph.html", title="count_by_day_graph") hold() figure(x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,previewsave", plot_width=1800) line(np.array(a["date"], 'M64'), a['count'], color='#A6CEE3', legend='Количество статей') line(np.array(a["date"], 'M64'), [averange_count(collection_name)] * len(a["date"]), color='#ff0000', legend='Среднее количество статей') curplot().title = "Количество статей по дням" grid().grid_line_alpha=0.3 show()
def build_scatter_tooltip(x, y, tt, add_line=True, radius=3, title='My Plot', xlabel='Iteration number', ylabel='Score'): bk.figure(title=title) bk.hold() bk.circle( x, y, radius=radius, source=ColumnDataSource(tt), fill_alpha=0.6, line_color=None, tools=TOOLS) if add_line: bk.line(x, y, line_width=2) xax, yax = bk.axis() xax.axis_label = xlabel yax.axis_label = ylabel cp = bk.curplot() hover = cp.select(dict(type=HoverTool)) format_tt = [(s, '@%s' % s) for s in tt.columns] hover.tooltips = OrderedDict([("index", "$index")] + format_tt)
def build_plot(datalist,logx=True): # Set the output for our plot. output_file('plot.html', title='Plot')#, js="relative", css="relative") # Create some data for our plot. colors=['red','green','blue','yellow','black'] # colors=['tomato','navy'] hold() cnt=0 for name,data in datalist: cnt+=1 x,y=zip(*data) if logx: scatter([np.log(x_el) for x_el in x] ,list(y) , color=colors[cnt], legend=name) else: scatter(list(x) ,list(y) , color=colors[cnt], legend=name) # Create an HTML snippet of our plot. snippet = curplot().create_html_snippet(embed_base_url='/static/plots/', embed_save_loc=plotdir) # Return the snippet we want to place in our page. return snippet
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", x_range=[-11, 11], y_range=[-11, 11], tools="pan,wheel_zoom,box_zoom,reset,previewsave") hold() annular_wedge( cx, cy, rmin, rmax, theta[:-1], theta[1:], inner_radius_units="data", outer_radius_units="data", fill_color=colors, line_color="black", ) return curplot(), cursession()
def bokeh_kin(kin_env, m_signal, color='#DF4949', alpha=1.0, **kwargs): m_vector = tools.to_vector(m_signal, kin_env.m_channels) s_signal = kin_env._multiarm.forward_kin(m_vector) xs, ys = [0.0], [0.0] for i in range(kin_env.cfg.dim): xs.append(s_signal['x{}'.format(i + 1)]) ys.append(s_signal['y{}'.format(i + 1)]) xs, ys = ys, xs # we swap x and y for a more symmetrical look if isinstance(kin_env.cfg.lengths, numbers.Real): total_length = kin_env.cfg.lengths * kin_env.cfg.dim else: total_length = sum(kin_env.cfg.lengths) total_length += 0.0 kwargs = { 'plot_height': int(350 * 1.60), 'plot_width': int(350 * 1.60), 'x_range': [-1.0, 1.0], 'y_range': [-1.0, 1.0], 'line_color': color, 'line_alpha': alpha, 'fill_color': color, 'fill_alpha': alpha, 'title': '' } plotting.hold() plotting.line(xs, ys, **kwargs) plotting.grid().grid_line_color = None plotting.xaxis().major_tick_in = 0 plotting.ygrid().grid_line_color = None plotting.yaxis().major_tick_in = 0 plotting.circle(xs[:1], ys[:1], radius=0.015, **kwargs) plotting.circle(xs[1:-1], ys[1:-1], radius=0.008, **kwargs) plotting.circle(xs[-1:], ys[-1:], radius=0.01, color='red') plotting.hold(False)
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 perf_astd(ticks, avgs, astds, color=BLUE, alpha=1.0, sem=1.0, plot_width=1000, plot_height=500, **kwargs): plotting.line(ticks, avgs, color=color, line_alpha=alpha, title_text_font_size='6pt', plot_width=plot_width, plot_height=plot_height, **kwargs) plotting.hold(True) if astds is not None: x_std = list(ticks) + list(reversed(ticks)) y_std = ([ a - s_min / math.sqrt(sem) for a, (s_min, s_max) in zip(avgs, astds) ] + list( reversed([ a + s_max / math.sqrt(sem) for a, (s_min, s_max) in zip(avgs, astds) ]))) plotting.patch(x_std, y_std, fill_color=color, fill_alpha=alpha * 0.25, line_color=None) plotting.grid().grid_line_color = 'white' plotting_axis() plotting.hold(False)
def coverage(s_channels, threshold, s_vectors=(), title='no title', swap_xy=True, x_range=None, y_range=None, color=C_COLOR, c_alpha=1.0, alpha=0.5, **kwargs): x_range, y_range = ranges(s_channels, x_range=x_range, y_range=y_range) try: xv, yv = zip(*(s[:2] for s in s_vectors)) except ValueError: xv, yv = [], [] if swap_xy: x_range, y_range = y_range, x_range xv, yv = yv, xv plotting.circle(xv, yv, radius=threshold, x_range=x_range, y_range=y_range, fill_color=hexa(color, 0.35), fill_alpha=c_alpha, line_color=None, title=title, **kwargs) plotting.hold(True) union = shapely.ops.unary_union([ shapely.geometry.Point(*sv_i).buffer(threshold) for sv_i in s_vectors ]) boundary = union.boundary if isinstance(boundary, shapely.geometry.LineString): boundary = [boundary] for b in boundary: x, y = b.xy x, y = list(x), list(y) if swap_xy: x, y = y, x plotting.patch(x, y, fill_color=None, line_color=hexa(color, 0.75)) plotting.hold(True) plotting_axis() plotting.hold(False)
def _hold_false(self): "Wrapper to set up the the hold function to True to avoid toggling." hold(False)
def hold(flag): return plotting.hold(flag)
def drawPlot(shapeFilename, zipBorough, grids, centers, gridLines): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = { 'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': [] } record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: # was in zipBorough: # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): zipCodes.append(currentZip) start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start:end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Calculate centers center_lngs = min(lngs) + (max(lngs) - min(lngs)) / 2 center_lats = min(lats) + (max(lats) - min(lats)) / 2 # Store centroids for current part shape polygons['centerLat_list'].append(center_lats) polygons['centerLon_list'].append(center_lngs) # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("problem3.html") bk.hold() north = 40.915 east = -73.651 south = 40.496 west = -74.256 width = east - west height = north - south x_range = [west - 0.05 * width, east + 0.05 * width] y_range = [south - 0.05 * height, north + 0.05 * height] TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave" fig = bk.figure(title="311 Complaints by Zip Code", \ tools=TOOLS, background_fill = "#f8f8f8", x_range = x_range, y_range = y_range) circleSizes = [item for sublist in grids['log_counts'] for item in sublist] # Creates the polygons cellWidth = gridLines['vLines'][1] - gridLines['vLines'][0] cellHeight = gridLines['hLines'][1] - gridLines['hLines'][0] bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color="#fee8c8", line_color="gray") circleSizes = [0.009 * (size**3.7) for size in circleSizes] bk.scatter(centers['lon'], centers['lat'], size=circleSizes, alpha=0.4, line_color=None, fill_color='red') bk.hold() #print type(centers['lon']) circleSizeArr = np.array(circleSizes) maxSize = np.max(circleSizeArr) circleSizeArr[circleSizeArr == 0] = 100 minSize = np.min(circleSizeArr) #print minSize, maxSize legendN = 5 legendCircles = list(np.linspace(minSize, maxSize, legendN)) legendCounts = [ str(int(math.exp(((size / 0.009)**(1.0 / 3.7))))) + " complaints" for size in legendCircles ] #print legendCircles fakeScatter = [0 for x in range(legendN)] fakeScatterX = [-74.23 for x in range(legendN)] fakeScatterXtext = [-74.23 + 0.05 for x in range(legendN)] #fakeScatterY = [40.8 + 0.028*y for y in range(legendN)] fakeScatterY = [ 40.8, 40.8 + 0.02, 40.8 + 0.036, 40.8 + 0.056, 40.8 + 0.083 ] #print fakeScatterX, type(fakeScatterX) #print fakeScatterY, type(fakeScatterY) bk.scatter(fakeScatterX, fakeScatterY, size=legendCircles, fill_color='red', line_color=None, alpha=0.4) bk.text(fakeScatterXtext[1:], fakeScatterY[1:], text=legendCounts[1:], angle=0, text_align="left", text_font_size="7pt", text_baseline='middle') #for i in range(len(fakeScatter)): # bk.scatter([fakeScatter[i]], [fakeScatter[i]], size = [legendCircles[i]], legend = int(legendCircles[i]), color = 'red', fill_line = None, alpha = 0.4) # Disable background grid bk.grid().grid_line_color = None #print centers ### Legend #x = -74.25 #y = 40.8 #height = 0.003 #legend_box_y = y + 0.5 * height * len(legendColors) #bk.rect([x+0.032], [legend_box_y], width = 0.12, height = height*len(legendColors)*1.15, color = "#ffffff", line_color = "gray") ##x = -74.25 ##y = 40.9 #for color in legendColors: ## #print "Color: ", a ## #print "x:", x ## #print "y:", y ## # bk.rect([x], [y], color = color, width=0.03, height=height) # #bk.text([x], [y], text = agency, angle=0, text_font_size="7pt", text_align="center", text_baseline="middle") # y = y + height #legend_bottom_y = 40.797 #legend_top_y = legend_bottom_y + 0.92 * height * len(legendColors) #bk.text([-74.225], [legend_bottom_y], text = agency2, angle = 0, text_font_size = "7pt", text_align = "left") #bk.text([-74.225], [legend_top_y], text = agency1, angle = 0, text_font_size = "7pt", text_align = "left") #bokeh.embed.components(fig, bokeh.resources.CDN) bk.show()
def drawPlot(shapeFilename, zipBorough, zipMaxAgency): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] hoverZip = [] hoverAgency = [] hoverComplaints = [] polygons = { 'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': [] } record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipMaxAgency: # was in zipBorough: # zipCodes.append(currentZip) # moving this line into the parts loop # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): zipCodes.append(currentZip) hoverZip.append(currentZip) hoverAgency.append(zipMaxAgency[currentZip][0]) hoverComplaints.append(zipMaxAgency[currentZip][1]) start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start:end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Calculate centers center_lngs = min(lngs) + (max(lngs) - min(lngs)) / 2 center_lats = min(lats) + (max(lats) - min(lats)) / 2 # Store centroids for current part shape polygons['centerLat_list'].append(center_lats) polygons['centerLon_list'].append(center_lngs) # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Palette ##d9d9d9 brewer11 = [ '#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5' ] #brewer11 = ['#a6cee3', '#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99'] #agencies = sorted(list({zipMaxAgency[zipCode] for zipCode in zipMaxAgency})) biggestComplaints = {} for zz, aa in zipMaxAgency.iteritems(): if aa[0] in biggestComplaints: biggestComplaints[aa[0]] += 1 else: biggestComplaints[aa[0]] = 1 # sorting agencies by number of zip codes (to try to get better colors) agencies = list(biggestComplaints.iteritems()) agencies = sorted(agencies, key=lambda x: x[1], reverse=True) agencies = [agency[0] for agency in agencies] # Assign colors to agencies agencyColor = {agencies[i]: brewer11[i] for i in range(len(brewer11))} polygons['colors'] = [ agencyColor[zipMaxAgency[zipCode][0]] for zipCode in zipCodes ] # Prepare hover #source = bk.ColumnDataSource(data=dict(hoverAgency=hoverAgency, hoverZip=hoverZip, hoverComplaintCount=hoverComplaintCount,)) source = bk.ColumnDataSource(data=dict(hoverZip=hoverZip, hoverAgency=hoverAgency, hoverComplaints=hoverComplaints), ) # Creates the Plot bk.output_file("problem1.html") bk.hold() TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave,hover" fig = bk.figure(title="311 Complaints by Zip Code", \ tools=TOOLS, plot_width=800, plot_height=650) # Creates the polygons. bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color=polygons['colors'], line_color="gray", source=source) # RP: add hover hover = bk.curplot().select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("Zip", "@hoverZip"), ("Agency", "@hoverAgency"), ("Number of complaints", "@hoverComplaints"), ]) ### Zip codes as text on polygons #for i in range(len(polygons['centerLat_list'])): # y = polygons['centerLat_list'][i] # x = polygons['centerLon_list'][i] # zipCode = zipCodes[i] # bk.text([x], [y], text=zipCode, angle=0, text_font_size="8pt", text_align="center", text_baseline="middle") fonts = [ "Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf dingbats", "Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf Dingbats", "Comic sans MS" ] ### Legend x = -73.66 y = 40.50 #x = -74.25 #y = 40.9 for agency, color in agencyColor.iteritems(): #print "Color: ", a #print "x:", x #print "y:", y bk.rect([x], [y], color=color, width=0.03, height=0.015) bk.text([x], [y], text=agency, angle=0, text_font_size="7pt", text_align="center", text_baseline="middle") y = y + 0.015 #bokeh.embed.components(fig, bokeh.resources.CDN) bk.show()
def bokeh_html(data): bk.output_file("test.html", title="SRS test plots") TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select" # Figure 1: Raw time series data p1 = bk.figure( plot_width=700, plot_height=700, outline_line_color="red", tools=TOOLS, title="Raw Time Series Data", x_axis_label='Time(sec)', y_axis_label='Amplitude(Volts)') for channel_idx in range(24): p1.line(data._time_data[0], data.raw_volts[channel_idx], color=cnames.keys()[channel_idx]) bk.hold() # Figure 2: SRS Frequency Response p2 = bk.figure( plot_width=1100, plot_height=800, # width and height of the entire plot in pixels, including border space outline_line_color="red", tools=TOOLS, y_axis_type="log", x_axis_type="log", title="Shock Response Spectrum (SRS)", y_axis_label='Acceleration (gs)', x_axis_label='Frequency (Hz)') for channel_idx in range(24): p2.line(data.srs_fn, data.srs_gs[channel_idx], legend=data._labels[channel_idx + 1], line_alpha=0.8, line_width=1.5, min_border=2, color=cnames.keys()[channel_idx]) bk.hold() p2.grid.grid_line_color = "grey" p2.line(data.srs_fn, data.spec_interp_plus9dB, color='black', line_dash=[4, 4]) p2.line(data.srs_fn, data.spec_interp_plus6dB, color='black', line_dash=[4, 4]) p2.line(data.srs_fn, data.spec_interp_minus3dB, color='black', line_dash=[4, 4]) p2.line(data.srs_fn, data.spec_interp_minus6dB, color='black', line_dash=[4, 4]) p2.x_range = Range1d(start=10 ** 2, end=10 ** 5) # Figure 3: SRS Freq content per accel colors = [ "#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1", "#cc7878", "#933b41", "#550b1d" ] freq = [] channel = [] color = [] rate = [] largest_gs = 0 smallest_gs = 10000 for ch_idx in range(24): for fn_idx in range(120): freq.append(data.srs_fn[fn_idx]) rate.append(data.srs_gs[ch_idx][fn_idx]) channel.append(ch_idx + 1) if largest_gs < data.srs_gs[ch_idx][fn_idx]: largest_gs = data.srs_gs[ch_idx][fn_idx] if smallest_gs > data.srs_gs[ch_idx][fn_idx]: smallest_gs = data.srs_gs[ch_idx][fn_idx] largest_gs_lg = math.log(largest_gs) smallest_gs_lg = math.log(smallest_gs) diff = largest_gs_lg - smallest_gs_lg for i in range(len(rate)): color.append(colors[int((math.log(rate[i]) - smallest_gs_lg) * 8 / diff)]) source = bk.ColumnDataSource( data=dict( freq=[str(round(x, 1)) for x in freq], # y channel=channel, # x color=color, rate=rate) ) TOOLS = "resize,hover,save" p3 = bk.figure(title="Frequency data per Channel", x_range=[str(x) for x in range(1, 25)], y_range=[str(round(x, 1)) for x in list(reversed(data.srs_fn))], outline_line_color="red", x_axis_location="above", plot_width=1100, plot_height=900, toolbar_location="left", tools=TOOLS) p3.rect("channel", "freq", 1, 1, source=source, x_axis_location="above", color="color", line_color=None, title="Freq vs Accel") p3.grid.grid_line_color = "black" p3.axis.axis_line_color = "black" p3.axis.major_tick_line_color = "black" p3.axis.major_label_text_font_size = "5pt" p3.axis.major_label_standoff = 0 hover = p3.select(dict(type=HoverTool)) hover.snap_to_data = False hover.tooltips = OrderedDict([ ('channel', '@channel'), ('freq', '@freq'), ('rate', '@rate') ]) # bk.show(bk.VBox(p1, p2, p3))
'j1': +55.83, 'j2': -51.08, 'j3': +41.44, 'j4': +44.43, 'j5': +4.67, 'j6': +2.15, 'j7': +37.23, 'j8': -3.77, 'j9': -46.70, 'j10': +56.41, 'j11': -21.08, 'j12': +13.73, 'j13': +47.23, 'j14': +7.94, 'j15': -27.26, 'j16': +56.54, 'j17': -7.77, 'j18': -18.98, 'j19': +149.46 }] plotting.output_file('html/arm_vizu.html') for i, m_signal in enumerate(m_signals): bokeh_kin(kin_env, m_signal, alpha=0.2 + i * 0.15) plotting.hold(True) bokeh_kin(kin_env2, m_signal, color='#91C46C', alpha=0.2 + i * 0.15) plotting.hold(True) plotting.show()
def make_plot(xr): yr = Range1d(start=-10, end=10) figure(plot_width=800, plot_height=350, y_range=yr, x_range=xr, tools="xpan,xwheel_zoom,hover,box_zoom,reset") hold() genes = pd.read_csv('/home/hugoshi/data/lab7/genes.refseq.hg19.bed', sep='\t', skiprows=[0], header=None) genes.rename(columns={0: "chromosome", 1: "start", 2: "end"}, inplace=True) genes = genes[genes.chromosome == 'chr5'] g_len = len(genes) quad( genes.start - 0.5, # left edge genes.end - 0.5, # right edge [2.3] * g_len, # top edge [1.7] * g_len, ['blue'] * g_len) # bottom edge exons = pd.read_csv('/home/hugoshi/data/lab7/exons.refseq.hg19.bed', sep='\t', skiprows=[0], header=None) exons.columns = ["chromosome", "start", "end", "meta1", "meta2", "meta3"] exons = exons[exons.chromosome == 'chr5'] e_len = len(exons) quad( exons.start - 0.5, # left edge exons.end - 0.5, # right edge [1.3] * e_len, # top edge [0.7] * e_len, ['blue'] * e_len) # bottom edge df = pd.read_csv('/home/hugoshi/data/lab7/CHP2.20131001.hotspots.bed', sep='\t', skiprows=[0], header=None) df.columns = ["chromosome", "start", "end", "meta1", "meta2", "meta3"] df = df[df.chromosome == 'chr5'] singles = df[df.start + 1 == df.end] widers = df[df.start + 1 != df.end] slen = len(singles) wlen = len(widers) s_source = ColumnDataSource(data=dict(start=singles.start, end=singles.end, meta1=singles.meta1, meta2=singles.meta2, meta3=singles.meta3)) rect( 'start', # x center [1] * slen, # y center [0.9] * slen, [1] * slen, color=['red'] * slen, source=s_source) # height hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0] hover.tooltips = OrderedDict([ # add to this ("position", "@start"), ("meta 1", "@meta1"), ("meta 2", "@meta2"), ("meta 3", "@meta3") ]) quad( widers.start - 0.5, # left edge widers.end - 0.5, # right edge [0.3] * wlen, # top edge [-0.3] * wlen) # bottom edge hold() return curplot()