def k_visualize(grid): p = figure(title="Cost per k-bats iteration", ) p.add_layout(Title(text="Iterations", align="center"), "below") p.add_layout(Title(text="Cost", align="center"), "left") lower = [] cycler = [] rand = [] scitt = [] iterations = [] s_size = 100 for i in tqdm(range(20)): lower_bound(grid) lower.append(grid.score()) grid.reset() for j in range(s_size): battery_cycler(grid) cycler.append(grid.score()) grid.reset() random_sampler(grid) rand.append(grid.score()) grid.reset() iterations.append(i) for j in range(s_size): scitt.append(i) k_means(grid) grid.reset() p.scatter(scitt, rand, color="blue", legend="Random Connect") p.scatter(scitt, cycler, color="green", legend="Battery Cycler") p.line(iterations, lower, color="red", legend="Lower bound") show(p)
def _style_plot(self, p): ''' Adds styling to the plot :param p: plot object :return: styled plot object ''' p.toolbar.logo = None p.toolbar_location = 'below' p.xgrid.grid_line_color = self.f_color p.xgrid.grid_line_width = 0 p.xgrid.grid_line_alpha = 0 p.ygrid.grid_line_color = None p.xaxis.axis_line_width = 0 p.yaxis.axis_line_width = 0 p.xaxis.axis_line_color = None p.yaxis.minor_tick_line_color = None p.yaxis.major_tick_line_color = None p.xaxis.major_tick_line_color = None p.xaxis.minor_tick_line_color = None p.axis.major_label_text_color = self.f_color p.axis.major_label_text_font_size = '10px' p.background_fill_color = self.bg_color p.outline_line_width = 0 p.border_fill_color = self.bg_color t = Title() t.text = self.title_text t.text_color = self.f_color p.title = t p = self._num_axis_formatter(p) return p
def plot_line(self, title, save_name, job=LOSS_PLOT): t1, t2 = title.split("\n") p = figure(plot_width=600, plot_height=250, # , title=title x_axis_label="epochs", y_axis_label=job) p.add_layout(Title(text=t2), 'above') p.add_layout(Title(text=t1), 'above') color1, color2 = ("orange", "red") if job == LOSS_PLOT else ("green", "blue") if job == LOSS_PLOT: y_axis_train = self._loss_vec_train # if job == LOSS_PLOT else self._accuracy_vec_train y_axis_dev = self._loss_vec_dev # if job == LOSS_PLOT else self._accuracy_vec_dev elif job == CORR_PLOT: y_axis_train = self._corr_vec_train y_axis_dev = self._corr_vec_dev elif job == R2_PLOT: y_axis_train = self._r2_vec_train y_axis_dev = self._r2_vec_dev elif job == ACCURACY_PLOT: y_axis_train = self._accuracy_vec_train y_axis_dev = self._accuracy_vec_dev elif job == AUC_PLOT: y_axis_train = self._auc_vec_train y_axis_dev = self._auc_vec_dev x_axis = list(range(len(y_axis_dev))) p.line(x_axis, y_axis_train, line_color=color1, legend_label="train") p.line(x_axis, y_axis_dev, line_color=color2, legend_label="dev") output_file(save_name + " " + job + "_fig.html") save(p)
def render_missing_impact_1vn(itmdt: Intermediate, plot_width: int, plot_height: int) -> Tabs: """ Render the plot from `plot_missing(df, "x")` """ dfs = itmdt["data"] x = itmdt["x"] meta = itmdt["meta"] panels = [] for col, df in dfs.items(): fig = render_hist(df, col, meta[col], plot_width, plot_height) shown, total = meta[col]["partial"] if shown != total: fig.title = Title( text=f"Missing impact of {x} by ({shown} out of {total}) {col}" ) else: fig.title = Title(text=f"Missing impact of {x} by {col}") panels.append(Panel(child=fig, title=col)) tabs = Tabs(tabs=panels) return tabs
def _setup_graph_renderer(self, circle_size, draw_components): #graph_renderer will have the actual logic for drawing graph_renderer = GraphRenderer() self.vertex_keys = list(self.graph.vertices.keys()) # add the vertex data as instructions for drawing nodes graph_renderer.node_renderer.data_source.add( [vertex.label for vertex in self.vertex_keys], 'index') if draw_components: graph_renderer.node_renderer.data_source.add( self._get_connected_component_colors(), "color") else: graph_renderer.node_renderer.data_source.add( self._get_random_colors(), "color") graph_renderer.node_renderer.glyph = Circle(size=circle_size, line_color="black", fill_color="color") graph_renderer.edge_renderer.data_source.data = self._get_edge_indices( ) self.randomize() self.plot.add_layout(Title(text="Whys", align="left"), "left") self.plot.add_layout(Title(text="Exes", align="center"), "below") graph_renderer.layout_provider = StaticLayoutProvider( graph_layout=self.pos) self.plot.renderers.append(graph_renderer)
def render_missing_impact_1v1(itmdt: Intermediate, plot_width: int, plot_height: int) -> Union[Tabs, Figure]: """ Render the plot from `plot_missing(df, "x", "y")` """ x, y = itmdt["x"], itmdt["y"] meta = itmdt["meta"] if is_numerical(meta["dtype"]): panels = [] fig = render_hist(itmdt["hist"], y, meta, plot_width, plot_height) panels.append(Panel(child=fig, title="Histogram")) fig = render_dist(itmdt["dist"], y, "pdf", plot_width, plot_height) panels.append(Panel(child=fig, title="PDF")) fig = render_dist(itmdt["dist"], y, "cdf", plot_width, plot_height) panels.append(Panel(child=fig, title="CDF")) fig = render_boxwhisker(itmdt["box"], plot_width, plot_height) panels.append(Panel(child=fig, title="Box")) tabs = Tabs(tabs=panels) return tabs else: fig = render_hist(itmdt["hist"], y, meta, plot_width, plot_height) shown, total = meta["partial"] if shown != total: fig.title = Title( text=f"Missing impact of {x} by ({shown} out of {total}) {y}") else: fig.title = Title(text=f"Missing impact of {x} by {y}") return fig
def get(self, request, name): query = "select id, name, year, sum(count) as count from frequency where name=%s group by year, name" name = {request.session['nameSearch']} results = Frequency.objects.raw(query,name) try : results[0] except IndexError: messages.error(request, 'Sorry, name '+request.session['nameSearch']+' was not found.', extra_tags='find') del request.session['nameSearch'] return redirect(reverse('find:index')) total = 0 year=[] count=[] for r in results: total += int(r.count) year.append(r.year) count.append(r.count) context = { 'names' : results[0], 'total' : total } ### Making the Graph ### source = ColumnDataSource( data=dict( year=year, count=count, ) ) p = figure(plot_width=800, plot_height=450, tools=['hover','pan','wheel_zoom','reset','save'], active_drag="pan", active_scroll="wheel_zoom") p.line(year,count,source=source, line_width=2) hover = p.select(dict(type=HoverTool)) hover.tooltips = """ <table class="tooltips"> <tr> <td>Birth Year</td> <td>@year</td> </tr> <tr> <td>Count</td> <td>@count</td> </tr> </table> """ hover.mode = 'mouse' p.add_layout(Title(text="Birth Year", align="center"), "below") p.add_layout(Title(text="Count", align="center"), "left") script, div = components(p, CDN) context['bokehScript'] = script context['bokehDiv'] = div if 'id' in request.session: faveNames = [] faveList = Favorites.objects.filter(user_id=request.session['id']) for n in faveList: faveNames.append(n.frequency_id.name) context['faveNames']=faveNames return render(request, 'find/graph.html', context)
def bk_title(p, title="", subtitle=""): p.add_layout( Title(text=subtitle, text_font_style="italic", text_font_size="100%"), 'above') p.add_layout( Title(text=title, text_font_style="bold", text_font_size="125%"), 'above') return p
def make_plot_scatter(source_df, category_list, color_col, color_palette, x_col, y_col, hover_list, x_label, y_label, title, subtitle): """ This function provide a scatter plot to show the relationship among COVID-19 positive cases, deaths and election results in the swing states Args: - source_df: (pandas.dataframe) the data used to make a plot - category_list: (list) - color_col, x_col, y_col: (string) names of columns used for color, x axis and y axis - color_palette: (list) a list of color codes - hover_list: (list) a list of tuples shown in the hover - x_label, y_label: (string) names of x axis and y axis - title: (string) the title of the plot - subtitle: (string) the subtitle of the plot Returns: - plots: one bokeh plot """ plot = figure(plot_height=400, toolbar_location=None) plot.scatter(x=x_col, y=y_col, source=source_df, color=factor_cmap(color_col, palette=color_palette, factors=category_list), size=10, legend=color_col) plot.title.text = title plot.xaxis.axis_label = x_label plot.yaxis.axis_label = y_label hover = HoverTool() hover.tooltips = hover_list plot.background_fill_color = "beige" plot.add_tools(hover) plot.legend.location = "top_left" # plot.border_fill_color = "whitesmoke" plot.title.text_font_size = "15px" sub_text = Title(text=subtitle, align='left', text_font_size='12px', text_color="#A6ACAF") plot.add_layout(sub_text, 'above') sub_text = Title(text="", align='left', text_font_size='12px', text_color="#A6ACAF") plot.add_layout(sub_text, 'below') return plot
def plot(): user_id = user_id_get(current_user.username) results = user_data_all_get(user_id) if len(results) == 0: return "No data yet..." deltas = timedeltas(results) time_points = [0] + list(np.cumsum(deltas)) timeStrings = [i[1] for i in results] colors = ["blue" if i[2] == 0 else "red" for i in results] plot = figure() for i in range(len(time_points)): this_sec = time_points[i] this_color = colors[i] plot.line([this_sec, this_sec], [0, 1], line_color=this_color) plot.circle([this_sec, this_sec], [0, 1], fill_color=this_color, line_color=this_color, size=6) a = time_points plot.xaxis.ticker = a plot.xaxis.major_label_overrides = { a[i]: timeStrings[i] for i in range(len(a)) } #p.xaxis.major_label_overrides = {1: 'A', 2: 'B', 3: 'C'} plot.yaxis.major_tick_line_color = None # turn off y-axis major ticks plot.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks plot.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels plot.xaxis.major_label_orientation = -pi / 4 plot.background_fill_color = "LightGrey" plot.background_fill_alpha = 0.2 plot.xaxis.axis_label = "Timestamp" #plot.add_layout(Title(text=" Try ZOOM for a closer look."), 'above') plot.add_layout( Title( text= "Tip: Timestamps on the x-axis may be overlapping and messy. Try ZOOM for a closer look." ), 'above') plot.add_layout( Title(text="Events: Blue = Button 0, Red = Button 1 ", text_font_size="16pt"), 'above') script, div = components(plot) return render_template("plot.html", the_div=div, the_script=script)
def request_handler(request): if (request["method"] == 'POST'): return do_POST(request) elif (request["method"] == 'GET'): if ('type' not in request["args"]): return "Error please enter the type of graph" else: #data from SQL data = get_data() #type of graph from input graph = request['values']['type'] if graph == "ekg": index = 0 t = ("Graph for the EKG") elif graph == "steps": index = 1 t = ("Graph for the Steps") else: return "error please enter either ekg or steps" #time axis xaxis = [] for i in range(len(data[index])+1): xaxis.append(i*5) #bokeh stuff p = figure(title = t, plot_width=400, plot_height=400) p.line(xaxis, data[index], line_width=2) #titles p.add_layout(Title(text="Time (s)", align="center"), "below") if index == 0: p.add_layout(Title(text="Heart Rate (BPM)", align="left"), "left") else: p.add_layout(Title(text="Steps (steps per second)", align="left"), "left") p.title.text_font_size = "20px" p.toolbar.logo = None script, div = components(p) output = r"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Bokeh Scatter Plots</title> <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.css" type="text/css" /> <script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.js"></script> {} </head> <body> {} </body> </html>""".format(script,div) return output
def stim_select_callback(attr, old, new, kwargs=plot_kwargs): # Values from widget are not exact stimuli names stim = get_filename(META, stim_select.value) x_dim = int(META[stim]['x_dim']) y_dim = int(META[stim]['y_dim']) station_count = META[stim]['station_count'] city = META[stim]['txt_name'] title = Title(stim_select.value + '--') matrix_plot.title = title # Retaining other settings color = color_select.value # TODO # metric = metric.select.value image_cds.data = get_img(stim, [0], [0]).data matrix_cds.data = get_matrix_cds(stim, USERS, DF, color, METRIC).data # Updating image_plot.x_range.start = 0 image_plot.y_range.start = 0 image_plot.x_range.end = x_dim image_plot.y_range.end = y_dim plot_w = x_dim + kwargs['min_border_left'] + kwargs['min_border_right'] plot_h = y_dim + kwargs['min_border_top'] + kwargs['min_border_bottom']
def render_missing_impact_1vn( itmdt: Intermediate, plot_width: int, plot_height: int, ) -> Dict[str, Any]: """ Render the plot from `plot_missing(df, "x")` """ dfs = itmdt["data"] x = itmdt["x"] meta = itmdt["meta"] panels = [] for col, df in dfs.items(): fig = render_hist(df, col, meta[col], plot_width, plot_height, False) fig.frame_height = plot_height fig.title = Title(text=f"Missing impact of {x} by {col}") panels.append(Panel(child=fig, title=col)) legend_colors = [CATEGORY10[count] for count in range(len(LABELS))] return { "layout": [panel.child for panel in panels], "container_width": plot_width * 3, "legend_labels": [ {"label": label, "color": color} for label, color in zip(LABELS, legend_colors) ], }
def plot_date_data(x_data, y_data, y_label, title): # create a new plot title_eng = title p = figure( tools="pan,box_zoom,wheel_zoom,reset,save", x_axis_type='datetime', x_axis_label='Date', y_axis_label=y_label, plot_width=600, plot_height=400, ) p.axis.axis_label_text_font_style = 'normal' p.add_layout(Title(text=title_eng, text_font_size="16pt"), 'above') p.line(x=x_data, y=y_data, line_width=3) # ------------------------Data File------------------------------ target_dir = os.path.join(settings.BASE_DIR, 'media', 'temp') target_file = "temp_export.csv" target_file_path = os.path.join(target_dir, target_file) target_url = os.path.join(settings.MEDIA_ROOT, 'temp', target_file) with open(target_file_path, 'w') as data_file: writer = csv.writer(data_file) writer.writerow(["Date", y_label]) writer.writerows(itertools.zip_longest(x_data, y_data)) scirpt, div = components(p, CDN) return scirpt, div, target_url
def _plot_res_bokeh(y_target, y_hat, title=None, env='jupyter'): import bokeh.plotting as plt from bokeh.layouts import column, row from bokeh.io import output_notebook from bokeh.models import LinearAxis, Range1d, Title, Legend if env == 'jupyter': notebook_handle = True output_notebook() # plot 1 with numerical x index (Time hours) p1 = plt.figure(plot_width=800, plot_height=350) plt.hold() # Title titre = Title(text=title, align='center', text_font_size='12pt') # Axis p1.yaxis.axis_label = "Discharge (m³/s)" p1.xaxis.axis_label = "Time (hours)" # plot discharge p1.line(x=range(len(y_hat)), y=y_target, line_width=2.0, legend='Q_obs') p1.line(x=range(len(y_hat)), y=y_hat, line_width=2.0, color='orangered', legend='Q_sim') p1.add_layout(titre, 'above') t = plt.show(p1, notebook_handle=notebook_handle) return None
def _make_piechart(src, startAngle, endAngle, title, bottomTitle, tooltips): p = figure(plot_height=200, plot_width=280, toolbar_location=None, title=title) p.wedge(x=0, y=1, radius=0.5, start_angle=startAngle, end_angle=endAngle, line_color='white', fill_color='color', source=src) p.axis.axis_label = None p.axis.visible = False p.grid.grid_line_color = None hover = HoverTool(tooltips=tooltips) p.add_tools(hover) p.add_layout(Title(text=bottomTitle, align="center"), "below") return p
def hex_freq(self, season=None): """ Generates a hex bin plot that compares a player's shooting percentages to the leagues by zone. Shows accuracy compared to league. Takes season as a string, defaults to last played season... Identical to hex_accuracy excepf sort_all_bins replaced with sort_all_bins_freq""" if self.error_flag == 1: error = Error() return error.error_graph() else: shots = self.generate_shots(season) if shots.empty: p = figure(title='No Data for the Selected Season', tools="wheel_zoom,reset", match_aspect=True, background_fill_color='#BB7E3B', name='plot') p.grid.visible = False p.axis.visible = False draw_court(p) else: all_bins = sort_all_bins_freq(shots) p = figure(title=self.name + ' Heatmap: frequency compared to league', tools="wheel_zoom,reset", match_aspect=True, background_fill_color='#BB7E3B', name='plot') p.grid.visible = False p.axis.visible = False p.hex_tile(q="q", r="r", size=0.1, line_color='black', source=all_bins, fill_color=linear_cmap('counts', cc.coolwarm, self.percent_low / 2, self.percent_hi / 2)) draw_court(p) color_mapper = LinearColorMapper(palette=cc.coolwarm, low=self.percent_low / 2, high=self.percent_hi / 2) color_bar = ColorBar(color_mapper=color_mapper, location=(0, 0)) p.add_layout(color_bar, 'right') p.add_layout( Title( text= "Percentage of shots taken in zone compared to league", align='center'), 'right') hover = HoverTool(tooltips=[("%" + "difference", "@counts" + "%")], mode="mouse", point_policy="follow_mouse") p.add_tools(hover) return p
def test_Title() -> None: title = Title() assert title.level == 'annotation' assert title.text == "" assert title.vertical_align == 'bottom' assert title.align == 'left' assert title.offset == 0 assert title.text_font == 'helvetica' assert title.text_font_size == '13px' assert title.text_font_style == 'bold' assert title.text_color == '#444444' assert title.text_alpha == 1.0 assert title.text_line_height == 1.0 check_fill_properties(title, "background_", None, 1.0) check_line_properties(title, "border_", None, 1.0, 1.0) check_properties_existence( title, ANNOTATION + [ "text", "vertical_align", "align", "offset", "standoff", ], TEXT, prefix("border_", LINE), prefix("background_", FILL), )
def test_Title() -> None: title = Title() assert title.level == 'annotation' assert title.text == "" assert title.vertical_align == 'bottom' assert title.align == 'left' assert title.offset == 0 assert title.text_font == 'helvetica' assert title.text_font_size == '13px' assert title.text_font_style == 'bold' assert title.text_color == '#444444' assert title.text_alpha == 1.0 assert title.text_line_height == 1.0 check_fill_properties(title, "background_", None, 1.0) check_line_properties(title, "border_", None, 1.0, 1.0) check_properties_existence(title, [ "visible", "level", "text", "vertical_align", "align", "offset", "standoff", "text_font", "text_font_size", "text_font_style", "text_color", "text_alpha", "text_line_height", "x_range_name", "y_range_name", "render_mode"], prefix('border_', LINE), prefix('background_', FILL))
def plot_histogram(self, channel_label_or_number, source='xform', subsample=False, bins=None): """ Returns a histogram plot of the specified channel events, available as raw, compensated, or transformed data. Plot also contains a curve of the gaussian kernel density estimate. :param channel_label_or_number: A channel's PnN label or number to use for plotting the histogram :param source: 'raw', 'comp', 'xform' for whether the raw, compensated or transformed events are used for plotting :param subsample: Whether to use all events for plotting or just the sub-sampled events. Default is False (all events). Plotting sub-sampled events can be much faster. :param bins: Number of bins to use for the histogram. If None, the number of bins is determined by the Freedman-Diaconis rule. :return: Matplotlib figure of the histogram plot with KDE curve. """ channel_index = self.get_channel_index(channel_label_or_number) channel_data = self.get_channel_data(channel_index, source=source, subsample=subsample) p = plot_utils.plot_histogram(channel_data, x_label=self.pnn_labels[channel_index], bins=bins) p.title = Title(text=self.original_filename, align='center') return p
def plot(self, width=500, height=500): pres = self.__iteration_series() infos = self.model.getinfo() descr = "" for k, v in infos.iteritems(): descr += "%s: %s, " % (k, v) descr = descr[:-2].replace("_", " ") p = figure(width=width, height=height) i = 0 for k, l in pres.iteritems(): p.line(range(0, len(l)), l, line_width=2, color=cols[i], legend=self.srev[k]) i += 1 p.title.text = self.model.get_name() p.xaxis.axis_label = 'Iterations' p.yaxis.axis_label = '#Nodes' p.ygrid[0].grid_line_alpha = 0.5 p.xgrid[0].grid_line_alpha = 0.5 p.add_layout(Title(text=descr, align="center"), "below") p.legend.orientation = "horizontal" return p
def title(self, title=None): """Plot title Keyword Arguments: title {String} -- plot title (default: {None}) """ self.plot.title = Title(text=title)
def _create_plot() -> (Figure, ColumnDataSource): """Utility function for creating and styling the bar plot.""" global source, aspects, stats pos_counts, neg_counts = ([ stats.loc[(asp, pol, False), "Quantity"] for asp in aspects ] for pol in POLARITIES) np.seterr(divide="ignore") source = ColumnDataSource( data={ "aspects": aspects, "POS": pos_counts, "NEG": neg_counts, "log-POS": np.log2(pos_counts), "log-NEG": np.log2(neg_counts), }) np.seterr(divide="warn") p = figure( plot_height=145, sizing_mode="scale_width", x_range=aspects, toolbar_location="right", tools="save, tap", ) rs = [ p.vbar( x=dodge("aspects", -0.207, range=p.x_range), top="log-POS", width=0.4, source=source, color="limegreen", legend=value("POS"), name="POS", ), p.vbar( x=dodge("aspects", 0.207, range=p.x_range), top="log-NEG", width=0.4, source=source, color="orangered", legend=value("NEG"), name="NEG", ), ] for r in rs: p.add_tools( HoverTool(tooltips=[("Aspect", "@aspects"), (r.name, "@" + r.name)], renderers=[r])) p.add_layout( Title(text=" " * 7 + "Sentiment Count (log scale)", align="left", text_font_size="23px"), "left", ) p.yaxis.ticker = [] p.y_range.start = 0 p.xgrid.grid_line_color = None p.xaxis.major_label_text_font_size = "20pt" p.legend.label_text_font_size = "20pt" return p, source
def __init__(self, df, scale=13, border_day=0.25, border_month=0.4, border_year=0.4, title=None, hover=None, not_hover=tuple(), all_hover=False): self._hover_args = (hover, not_hover, all_hover) start, finish = df.index.min(), df.index.max() delta_year = 7 * (1 + border_day) + border_year self._df = df self._df_all = pd.DataFrame(data={CALENDAR_SIZE: 1, CALENDAR_RADIUS: 0.5}, index=pd.date_range(start, finish)) self._set_date(self._df) self._set_xy(self._df, start, finish, border_day, border_month, delta_year) self._set_date(self._df_all) self._set_xy(self._df_all, start, finish, border_day, border_month, delta_year) xlo = self._df_all[CALENDAR_X].min() xhi = self._df_all[CALENDAR_X].max() ylo = self._df_all[CALENDAR_Y].min() yhi = self._df_all[CALENDAR_Y].max() nx = int(scale * (xhi - xlo)) ny = int(scale * (yhi - ylo)) plot = Plot(x_range=Range1d(xlo - 4, xhi + 4), y_range=Range1d(ylo - 1, yhi + 4), width=nx, height=ny, title=Title(text=title)) self._add_labels(plot, start, finish, xlo, xhi, yhi, border_day, delta_year) self._plot = plot
def __init__(self, **kwargs): names = ['processes', 'disk-read', 'cores', 'cpu', 'disk-write', 'memory', 'last-seen', 'memory_percent', 'host'] self.source = ColumnDataSource({k: [] for k in names}) columns = {name: TableColumn(field=name, title=name.replace('_percent', ' %')) for name in names} cnames = ['host', 'cores', 'processes', 'memory', 'cpu', 'memory_percent'] formatters = {'cpu': NumberFormatter(format='0.0 %'), 'memory_percent': NumberFormatter(format='0.0 %'), 'memory': NumberFormatter(format='0 b'), 'latency': NumberFormatter(format='0.00000'), 'last-seen': NumberFormatter(format='0.000'), 'disk-read': NumberFormatter(format='0 b'), 'disk-write': NumberFormatter(format='0 b'), 'net-send': NumberFormatter(format='0 b'), 'net-recv': NumberFormatter(format='0 b')} table = DataTable( source=self.source, columns=[columns[n] for n in cnames], ) for name in cnames: if name in formatters: table.columns[cnames.index(name)].formatter = formatters[name] mem_plot = Plot( title=Title(text="Memory Usage (%)"), toolbar_location=None, x_range=Range1d(start=0, end=1), y_range=Range1d(start=-0.1, end=0.1), **kwargs ) mem_plot.add_glyph( self.source, Circle(x='memory_percent', y=0, size=10, fill_alpha=0.5) ) mem_plot.add_layout(LinearAxis(), 'below') hover = HoverTool( point_policy="follow_mouse", tooltips=""" <div> <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span> <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span> </div> """ ) mem_plot.add_tools(hover, BoxSelectTool()) if 'sizing_mode' in kwargs: sizing_mode = {'sizing_mode': kwargs['sizing_mode']} else: sizing_mode = {} self.root = column(mem_plot, table, id='bk-worker-table', **sizing_mode)
def generate_growth_chart(plot_fish): if type(plot_fish) == models.Individual: len_dets = models.IndividualDet.objects.filter(anidc_id__name="Length").filter(anix_id__indv_id=plot_fish) weight_dets = models.IndividualDet.objects.filter(anidc_id__name="Weight").filter(anix_id__indv_id=plot_fish) else: indv_list, grp_list = plot_fish.fish_in_cont(select_fields=[]) len_dets = models.IndividualDet.objects.filter(anidc_id__name="Length").filter(anix_id__indv_id__in=indv_list) weight_dets = models.IndividualDet.objects.filter(anidc_id__name="Weight").filter(anix_id__indv_id__in=indv_list) x_len_data = [] y_len_data = [] for len_det in len_dets: x_len_data.append(datetime.combine(len_det.detail_date, datetime.min.time())) y_len_data.append(len_det.det_val) x_weight_data = [] y_weight_data = [] for weight_det in weight_dets: x_weight_data.append(datetime.combine(weight_det.detail_date, datetime.min.time())) y_weight_data.append(weight_det.det_val) # create a new plot title_eng = "Growth Chart for fish" p_len = figure( tools="pan,box_zoom,wheel_zoom,reset,save", x_axis_type='datetime', x_axis_label='Date', y_axis_label='Length', plot_width=600, plot_height=300, ) p_weight = figure( tools="pan,box_zoom,wheel_zoom,reset,save", x_axis_type='datetime', x_axis_label='Date', y_axis_label='Weight', plot_width=600, plot_height=300, ) p_len.axis.axis_label_text_font_style = 'normal' p_weight.axis.axis_label_text_font_style = 'normal' p_len.add_layout(Title(text=title_eng, text_font_size="16pt"), 'above') p_len.x(x=x_len_data, y=y_len_data, size=10) p_weight.x(x=x_weight_data, y=y_weight_data, size=10) # ------------------------Data File------------------------------ target_dir = os.path.join(settings.BASE_DIR, 'media', 'temp') target_file = "temp_export.csv" target_file_path = os.path.join(target_dir, target_file) target_url = os.path.join(settings.MEDIA_ROOT, 'temp', target_file) with open(target_file_path, 'w') as data_file: writer = csv.writer(data_file) writer.writerow(["Growth information for Fish {}".format(plot_fish.__str__())]) writer.writerow(["Date", " Length (cm)", " Date", " Weight (g)"]) writer.writerows(itertools.zip_longest(x_len_data, y_len_data, x_weight_data, y_weight_data)) scirpt, div = components(column(p_len, p_weight), CDN) return scirpt, div, target_url
def prepare_figure(self, title, xlabel, ylabel, figure=None): """ Create a bokeh figure according to the set parameters or modify an existing one :param title: title of the figure :param xlabel: label on the x-axis :param ylabel: label on the y-axis :param figure: bokeh figure, optional, if given the operations are performed on the object otherwise a new figure is created :returns: the created or modified bokeh figure """ from bokeh.plotting import figure as bokeh_fig from bokeh.models import Title if figure is None: p = bokeh_fig(**self['figure_kwargs']) else: p = figure if self['background_fill_color'] is not None: p.background_fill_color = self['background_fill_color'] if title is not None: p.title = Title(text=title) if xlabel is not None: p.xaxis.axis_label = xlabel if ylabel is not None: p.yaxis.axis_label = ylabel p.yaxis.axis_line_width = self['axis_linewidth'] p.xaxis.axis_line_width = self['axis_linewidth'] p.xaxis.axis_label_text_font_size = self['label_fontsize'] p.yaxis.axis_label_text_font_size = self['label_fontsize'] p.yaxis.major_label_text_font_size = self['tick_label_fontsize'] p.xaxis.major_label_text_font_size = self['tick_label_fontsize'] if self['y_axis_formatter'] is not None: p.yaxis.formatter = self['y_axis_formatter'] if self['x_axis_formatter'] is not None: p.xaxis.formatter = self['x_axis_formatter'] if self['x_ticks'] is not None: p.xaxis.ticker = self['x_ticks'] if self['y_ticks'] is not None: p.xaxis.ticker = self['y_ticks'] if self['x_ticklabels_overwrite'] is not None: p.xaxis.major_label_overrides = self['x_ticklabels_overwrite'] if self['y_ticklabels_overwrite'] is not None: p.yaxis.major_label_overrides = self['y_ticklabels_overwrite'] if self['x_range_padding'] is not None: p.x_range.range_padding = self['x_range_padding'] if self['y_range_padding'] is not None: p.y_range.range_padding = self['y_range_padding'] return p
def create_plot(source): p = figure(x_range=FactorRange(*x), y_axis_label='Percentage', plot_width=1030) p.title.text = "Confirmed_case% VS Population% by races" p.title.align = "center" p.title.text_font_size = "20px" p.vbar(x='x', top='counts', width=0.9, source=source, line_color="white", fill_color=factor_cmap('x', factors=percentages, palette=["#c9d9d3", "#718dbf"], start=1, end=2)) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" p.xgrid.grid_line_color = None p.add_tools( HoverTool(tooltips=[('Race, category', "@x"), ('Percentage', "@counts")], )) p.add_layout( Title( text="Data " "published by latimes.com/coronavirustracker; download data " "from " "https://github.com/datadesk/california-coronavirus-data/cdph-race" "-ethnicity.csv in GitHub", text_font_style="italic"), 'below') p.add_layout( Title( text="Data Source: California Department of Public Health " "https://www.cdph.ca.gov/Programs/CID/DCDC/Pages/COVID-19/Race-Ethnicity.aspx", text_font_style="italic"), 'below') p.add_layout( Title(text="Date of last update: 2020-10-14", text_font_style="italic"), 'below') return p
def add_plot_title(self, plot, data, *extra_lines): """Annotate plot with titles.""" for line in extra_lines: plot.add_layout( Title(text=line, text_line_height=0.5, text_font_style='italic', text_color='grey'), 'above', ) for identkey in ['source', 'fasta', 'reference', 'read_group']: if not data.get(identkey): continue plot.add_layout(Title( text=data[identkey], text_line_height=0.5, ), 'above')
def add_title(self): if 'title_text' in pytplot.tplot_opt_glob: if pytplot.tplot_opt_glob['title_text'] != '': title1 = Title(text=pytplot.tplot_opt_glob['title_text'], align=pytplot.tplot_opt_glob['title_align'], text_font_size=pytplot.tplot_opt_glob['title_size']) self.fig.title = title1 self.fig.plot_height += 22