Ejemplo n.º 1
0
    def _make_graph_plot(self) -> Plot:
        """ Builds the graph portion of the final model.

        """
        import networkx as nx

        nodes = nx.nx_pydot.graphviz_layout(self._graph, prog="dot")
        node_x, node_y = zip(*nodes.values())
        models = [self._graph.nodes[x]["model"] for x in nodes]
        node_id = list(nodes.keys())
        node_source = ColumnDataSource(
            {"x": node_x, "y": node_y, "index": node_id, "model": models}
        )
        edge_x_coords = []
        edge_y_coords = []
        for start_node, end_node in self._graph.edges:
            edge_x_coords.extend([[nodes[start_node][0], nodes[end_node][0]]])
            edge_y_coords.extend([[nodes[start_node][1], nodes[end_node][1]]])
        edge_source = ColumnDataSource({"xs": edge_x_coords, "ys": edge_y_coords})

        p2 = Plot(outline_line_alpha=0.0)
        xinterval = max(max(node_x) - min(node_x), 200)
        yinterval = max(max(node_y) - min(node_y), 200)
        p2.x_range = Range1d(
            start=min(node_x) - 0.15 * xinterval, end=max(node_x) + 0.15 * xinterval
        )
        p2.y_range = Range1d(
            start=min(node_y) - 0.15 * yinterval, end=max(node_y) + 0.15 * yinterval
        )

        node_renderer = GlyphRenderer(
            data_source=node_source,
            glyph=Circle(x="x", y="y", size=15, fill_color="lightblue"),
            nonselection_glyph=Circle(x="x", y="y", size=15, fill_color="lightblue"),
            selection_glyph=Circle(x="x", y="y", size=15, fill_color="green"),
        )

        edge_renderer = GlyphRenderer(
            data_source=edge_source, glyph=MultiLine(xs="xs", ys="ys")
        )

        node_hover_tool = HoverTool(tooltips=[("id", "@index"), ("model", "@model")])
        node_hover_tool.renderers = [node_renderer]

        tap_tool = TapTool()
        tap_tool.renderers = [node_renderer]

        labels = LabelSet(
            x="x",
            y="y",
            text="model",
            source=node_source,
            text_font_size="8pt",
            x_offset=-20,
            y_offset=7,
        )

        help = Label(
            x=20,
            y=20,
            x_units="screen",
            y_units="screen",
            text_font_size="8pt",
            text_font_style="italic",
            text="Click on a model to see its attributes",
        )
        p2.add_layout(help)
        p2.add_layout(edge_renderer)
        p2.add_layout(node_renderer)
        p2.tools.extend(
            [node_hover_tool, tap_tool, BoxZoomTool(), ResetTool(), PanTool()]
        )
        p2.renderers.append(labels)
        self._node_source = node_source
        self._edge_source = edge_source
        return p2
Ejemplo n.º 2
0
                            rssi.sort(reverse=True)
                            rssi = np.array(rssi, dtype=np.int16)
                            medians = []
                            for i in range(1, 101):
                                med = median(rssi[:int(len(rssi) * i * 0.01)])
                                medians.append(
                                    median(rssi[:int(len(rssi) * i * 0.01)]))
                            x = np.arange(1, 101, 1)
                            y = np.array(medians, dtype=np.int16)
                            rssi = np.array(rssi, dtype=np.int16)
                            title = "%s(size=%s, max=%s, min=%s, avg=%s, median=%s)" % \
                                    (filename, len(rssi), max(rssi), min(rssi), mean(rssi), median(rssi))
                            p = plot_line_chart(x=x, y=y, title=title)
                            hline1 = tx - 40 - 20 * math.log10(distance)
                            percent = int(abs(median(rssi)) - 39)
                            hline2 = y[percent + 1]
                            plot_line(picture=p,
                                      y=[hline1, hline2],
                                      color=['green', 'red'])
                            p.add_layout(
                                Label(x=0,
                                      y=0,
                                      x_units='screen',
                                      y_units='screen',
                                      text='median=%d,formula=%d' %
                                      (hline1, hline2)))
                            figures.append(p)

                        # open a browser
                    show(column(figures))
def generate_sentiment_ts_plot(sentiment_ts_data, sentiment_ts_sample_count):
    tooltips = [
        ("Date", "@date{%F}"),
        ("Mentions", "@Count"),
        ("Nett Sentiment (7 day mean)", "@NettSentiment{0.0%}"),
    ]

    line_plot = figure(title=None,
                       width=None,
                       height=None,
                       sizing_mode="scale_both",
                       x_range=(sentiment_ts_data["date"].min(),
                                sentiment_ts_data["date"].max()),
                       x_axis_type='datetime',
                       y_axis_label="Nett Sentiment (7 day mean)",
                       tools=[],
                       toolbar_location=None)
    # Setting range of y range
    line_plot.y_range = Range1d(-1, 1)

    # Adding Count range on the right
    line_plot.extra_y_ranges = {
        "count_range": Range1d(start=0,
                               end=sentiment_ts_sample_count.max() * 1.1)
    }
    secondary_axis = LinearAxis(y_range_name="count_range",
                                axis_label="Mentions")
    line_plot.add_layout(secondary_axis, 'right')

    sentiment_count_bars = line_plot.vbar(x="date",
                                          top="Count",
                                          width=pandas.Timedelta(days=0.75),
                                          color="orange",
                                          source=sentiment_ts_data,
                                          y_range_name="count_range")
    sentiment_line = line_plot.line(x="date",
                                    y="NettSentiment",
                                    color="blue",
                                    source=sentiment_ts_data,
                                    line_width=5)

    # Long Term sentiment baseline
    long_term_sentiment_span = Span(
        location=LONG_TERM_SENTIMENT,
        name="LongTermSentiment",
        dimension='width',
        line_color='red',
        line_dash='dashed',
        line_width=3,
    )
    line_plot.add_layout(long_term_sentiment_span)

    start_timestamp = sentiment_ts_data["date"].min()
    long_term_sentiment_label = Label(x=start_timestamp,
                                      y=LONG_TERM_SENTIMENT,
                                      x_offset=-10,
                                      y_offset=10,
                                      text='Sentiment Baseline',
                                      render_mode='css',
                                      border_line_color='white',
                                      border_line_alpha=0.0,
                                      angle=0,
                                      angle_units='deg',
                                      background_fill_color='white',
                                      background_fill_alpha=0.0,
                                      text_color='red',
                                      text_font_size='12pt')
    line_plot.add_layout(long_term_sentiment_label)

    hover_tool = HoverTool(renderers=[sentiment_line, sentiment_count_bars],
                           tooltips=tooltips,
                           formatters={
                               '@date': 'datetime',
                               'NettSentiment': 'printf'
                           })
    line_plot.add_tools(hover_tool)

    line_plot.xaxis.formatter = DatetimeTickFormatter(days="%Y-%m-%d")
    line_plot.yaxis.formatter = NumeralTickFormatter(format="0.[0]%")
    secondary_axis.formatter = NumeralTickFormatter(format="0.[0] a")

    line_plot.axis.axis_label_text_font_size = "12pt"
    line_plot.axis.major_label_text_font_size = "12pt"

    plot_html = file_html(line_plot, CDN, "Behavioural Sentiment Timeseries")

    return plot_html
Ejemplo n.º 4
0
             line_color='blue',
             line_width=1,
             line_dash='dashed')
p.renderers.extend([hline])

hline = Span(location=np.mean(data_out) - np.std(data_out),
             dimension='width',
             line_color='blue',
             line_width=1,
             line_dash='dashed')
p.renderers.extend([hline])

mean_str = 'Mean = ' + str(round(np.mean(data_out), 2))
citation = Label(x=260,
                 y=np.mean(data_out),
                 text=mean_str,
                 render_mode='css',
                 text_color='green')
p.add_layout(citation)
# show the results
show(p)

driver = selenium.webdriver.PhantomJS(
    executable_path=
    r'C:\Users\le165208\Apps\PhantomJS\phantomjs-2.1.1-windows\bin\phantomjs')
driver.get(
    'file:///C:/Users/le165208/githubprojects/brachy_dose_audit/output.html')
save_str = 'screens/' + quantity + '.png'
driver.save_screenshot(save_str)

print(np.mean(data_out))
plot.line('x',
          'y',
          source=line_source,
          line_width=3,
          line_alpha=0.6,
          color='black')
plot.circle('x', 'y', source=point_source, size=10, color='black')

# set up static line and annotations
plot.line(x_line, y_line, line_width=5, color='blue', line_alpha=0.3)
plot.circle(x_points, y_points, size=10, color='blue', line_alpha=0.3)

mytext = Label(x=-6.5,
               y=105,
               text='Top=100, Bottom=0, pEC50=6, Hill=1',
               text_color="blue",
               text_alpha=0.5)
plot.add_layout(mytext)

# add axes lines
vline = Span(location=0,
             dimension='height',
             line_color='black',
             line_width=1,
             line_alpha=0.3)
hline = Span(location=0,
             dimension='width',
             line_color='black',
             line_width=1,
             line_alpha=0.3)
Ejemplo n.º 6
0
p = figure(title='Dist. of 10th Grade Students at Lee High',
           x_range=Range1d(140, 275))
p.scatter(x='weight', y='height', size=8, source=source)
p.xaxis[0].axis_label = 'Weight (lbs)'
p.yaxis[0].axis_label = 'Height (in)'

labels = LabelSet(x='weight',
                  y='height',
                  text='names',
                  x_offset=5,
                  y_offset=5,
                  source=source,
                  render_mode='canvas')

citation = Label(x=70,
                 y=70,
                 x_units='screen',
                 y_units='screen',
                 text='Collected by Luke C. 2016-04-01',
                 render_mode='css',
                 border_line_color='black',
                 border_line_alpha=1.0,
                 background_fill_color='white',
                 background_fill_alpha=1.0)

p.add_layout(labels)
p.add_layout(citation)

show(p)
Ejemplo n.º 7
0
from bokeh.models import GMapOptions, Label
from bokeh.plotting import gmap, show

map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=13)

# replace with your google api key
p = gmap("GOOGLE_API_KEY", map_options)

if p.api_key == "GOOGLE_API_KEY":
    p.add_layout(Label(x=140, y=400, x_units='screen', y_units='screen',
                       text='Replace GOOGLE_API_KEY\nwith your own valid API key',
                       text_color='red'))

show(p)
Ejemplo n.º 8
0
def test_plot_add_layout_raises_error_if_plot_already_on_annotation():
    plot = figure()
    with pytest.raises(ValueError):
        plot.add_layout(Label(plot=plot))
Ejemplo n.º 9
0
    def run(self):

        if not os.path.isdir(self.result_path):
            os.makedirs(self.result_path)

        date_str = time.strftime("%Y/%m/%d") + " - " + time.strftime(
            "%H:%M:%S")

        bokeh_store_path = self.get_store_path_from_folder(
            self.result_path, 'bokeh')
        matplotlib_store_path = self.get_store_path_from_folder(
            self.result_path, 'matplotlib')

        # plot one figure for every subset-attack-metric
        for subset in self.dict_performance.keys():
            if subset is "end2end":
                continue
            for attack in self.dict_performance[subset].keys():
                for metric in self.dict_performance[subset][attack].keys():
                    text_database_info = "Dataset: " + self.name_database + ' (' + subset + ')'
                    text_method = "Method: " + self.name_algorithm
                    text_date_info = "Date: " + date_str
                    protocol_info = "Protocol: " + attack + ' - spoofing attack'
                    text_x_label = r'$T_a (ms)$'
                    text_y_label = metric + " (%)"

                    len_metric_keys = len(
                        self.dict_performance[subset][attack][metric].keys())
                    curve_color = viridis(len_metric_keys)
                    line_marker_bokeh = BOKEH_MARKERS[:len_metric_keys]
                    line_marker_plt = PLT_MARKERS[:len_metric_keys]

                    fig_bokeh = self.get_fig_bokeh(metric, protocol_info,
                                                   text_method, text_x_label,
                                                   text_y_label)
                    fig_plt, ax_plt = plt.subplots()

                    # plot one curve for every FPS rate
                    for index_fps, fps in enumerate(
                            sorted(self.dict_performance[subset][attack]
                                   [metric].keys())):
                        x_data, y_data, is_standard_evaluation, value_standard_evaluation = self.get_data(
                            attack, fps, metric, subset)
                        x_data = x_data * 1000
                        x_data = x_data.astype('int')
                        legend_curves = 'FR = ' + str(int(fps)) + ' (FPS)'

                        fig_bokeh.line(x_data,
                                       y_data,
                                       color=curve_color[index_fps],
                                       legend=legend_curves,
                                       line_width=2)
                        fig_bokeh.scatter(x_data,
                                          y_data,
                                          size=8,
                                          marker=line_marker_bokeh[index_fps],
                                          fill_color="white",
                                          fill_alpha=0.6,
                                          line_color=curve_color[index_fps],
                                          legend=legend_curves)

                        ax_plt.plot(x_data,
                                    y_data,
                                    linewidth=2,
                                    label=legend_curves,
                                    marker=line_marker_plt[index_fps],
                                    markerfacecolor="None",
                                    markersize=6)

                        axes = fig_plt.gca()
                        axes.set_xlim([min(x_data), max(x_data)])
                        axes.set_xticks(x_data)
                        # todo: axes = ax_plt.gca(); axes.set_ylim([0, 40])

                        if is_standard_evaluation:
                            labels = ax_plt.get_xticks().tolist()
                            index = np.where(
                                np.array(labels) ==
                                value_standard_evaluation)[0][0]
                            labels[index] = 'Whole video'
                            ax_plt.set_xticklabels(labels)

                    caption1 = Label(x=0,
                                     y=-15,
                                     x_units='screen',
                                     y_units='screen',
                                     text=text_database_info,
                                     render_mode='css',
                                     level="overlay",
                                     text_align="left")
                    caption2 = Label(x=0,
                                     y=-15,
                                     x_units='screen',
                                     y_units='screen',
                                     text=text_date_info,
                                     render_mode='css',
                                     level="overlay",
                                     text_align="left")

                    fig_bokeh.x_range = Range1d(start=0, end=3)

                    fig_bokeh.add_layout(caption1, 'below')
                    fig_bokeh.add_layout(caption2, 'below')

                    # Bokeh: output to static HTML file
                    fig_bokeh.legend.click_policy = "hide"

                    path = os.path.join(
                        bokeh_store_path, self.name_database + "_" + attack +
                        "_" + metric + "_figure.html")
                    output_file(path)
                    save(fig_bokeh)

                    # todo: solve problem with the version of the phantomjs package (maybe it is solved using > v2.0) to export png images using bokeh
                    # export_png(figBokeh, filename=self.database+"_"+attack+"_"+metric+"_figure2.png")

                    # matplotlib: properties setting
                    ax_plt.grid(True)
                    ax_plt.legend(loc='upper right')
                    title_complete = '\n'.join(
                        [text_method, text_database_info, protocol_info])
                    ax_plt.set_title(title_complete)
                    ax_plt.set_xlabel(text_x_label, fontsize=25)
                    ax_plt.set_ylabel(text_y_label, fontsize=20)

                    path = os.path.join(
                        matplotlib_store_path, self.name_database + "_" +
                        attack + "_" + metric + "_figure.png")
                    fig_plt.savefig(path, bbox_inches='tight')

                    plt.close('all')
Ejemplo n.º 10
0
    if yr > len(dates) - 1:
        yr = -1
    date = dates[yr]
    slider.value = yr


callback_id = None

dates = np.unique(year_all)
number_dates = np.arange(len(dates))
slider = Slider(title='Quarter',
                start=number_dates[0],
                end=number_dates[-1],
                step=1,
                value=number_dates[0])
label = Label(x=-0.9, y=55, text=str(dates[0]), text_font_size='20px')
slider.on_change('value', update_plot)
p.add_layout(label)

# Make a selection object: select
select = Select(title='Select Ward:',
                value='total',
                options=[
                    'total', 'mental_health', 'maternity', 'learning_dis',
                    'general_acute'
                ])
select.on_change('value', update_plot)


def animate_map():
    global callback_id
# getting x/y coords from the lon/lat in dataframe county
county_xs = [county["lons"] for county in counties.values()]
county_ys = [county["lats"] for county in counties.values()]

# getting the data
county_pop = df_stats['totalpopE']
county_names = df_stats['NAME']
county_poverty = df_stats['pctpoverty']
county_fsrate = df_stats['pctfoodstamps']
county_unemprate = df_stats['unemploymentrate']

# x/y and label for stadium
barclays_y = 40.6826 #long/lat for stadium
barclays_x = -73.9754
barclays_label1 = Label(x=-74.52, y=barclays_y, text='Barclays Center', border_line_color=None, background_fill_color='white', background_fill_alpha=0.7, text_font_size='9pt')
barclays_label2 = Label(x=-74.52, y=barclays_y, text='Barclays Center', border_line_color=None, background_fill_color='white', background_fill_alpha=0.7, text_font_size='9pt')
barclays_label3 = Label(x=-74.52, y=barclays_y, text='Barclays Center', border_line_color=None, background_fill_color='white', background_fill_alpha=0.7, text_font_size='9pt')

# setting up color mapping to data
pov_palette = viridis(11)
unemp_palette = viridis(14)
fs_palette = viridis(13)
pov_palette.reverse()
unemp_palette.reverse()
fs_palette.reverse()
pov_color_mapper = LinearColorMapper(palette=pov_palette, low=0, high=0.11)
unemp_color_mapper = LinearColorMapper(palette=unemp_palette, low=0, high=0.07)
fs_color_mapper = LinearColorMapper(palette=fs_palette, low=0, high=0.13)

# assigning data to dictionary in order to feed them into bokeh
Ejemplo n.º 12
0
       source=source)

p.xgrid.grid_line_color = "grey"
p.ygrid.grid_line_color = "grey"

p.y_range.start = 0
p.yaxis.axis_label = 'No. of galaxies'
p.yaxis.axis_label_text_font_size = "14pt"

p.xaxis.axis_label = 'No. of measurements'
p.xaxis.axis_label_text_font_size = "14pt"
p.xaxis.major_label_text_font = "18pt"

mytext = Label(x=1.27,
               y=N1 - 1500,
               text="%d" % (100. * N1 / Na) + "%",
               text_color='black',
               text_font_size='10pt')
p.add_layout(mytext)

mytext = Label(x=2.27,
               y=N2 - 1500,
               text="%d" % (100. * N2 / Na) + "%",
               text_color='black',
               text_font_size='11pt')
p.add_layout(mytext)

mytext = Label(x=3.27,
               y=N3 - 1500,
               text="%d" % (100. * N3 / Na) + "%",
               text_color='black',
from bokeh.plotting import figure, output_file, show
from bokeh.models import Arrow, OpenHead, NormalHead, VeeHead, Label, Plot, Range1d

output_file("arrow_styles.html")

ARROW_HEADS = [OpenHead, NormalHead, VeeHead]
HEIGHT = 35 * len(ARROW_HEADS)

p = Plot(plot_width=150, plot_height=HEIGHT,
         x_range=Range1d(0,1), y_range=Range1d(-0.5, len(ARROW_HEADS) - 0.5),
         toolbar_location=None, outline_line_color=None, min_border_left=0,
         min_border_right=0, min_border_top=0, min_border_bottom=0)

for i, style in enumerate(ARROW_HEADS):
    p.add_layout(Arrow(x_start=0.2, y_start=i, x_end=0.2, y_end=i, end=style()))
    p.add_layout(Label(x=0.2, x_offset=20, y=i, text=style.__name__, text_baseline='middle', text_align='left'))

show(p)
Ejemplo n.º 14
0
plot = figure(x_range=(0, max(d.kp)),
              y_range=(0, 200),
              output_backend='webgl',
              tools=toolbar)
plot.xaxis.axis_label = "kp"
plot.yaxis.axis_label = "speed"

plot.extra_y_ranges = {'carv': Range1d(start=0, end=50)}

plot.add_layout(LinearAxis(y_range_name='carv', axis_label='car_volumn'),
                'right')

label = Label(x=3,
              y=150,
              text=time_dict[0],
              text_font_size='80pt',
              text_alpha=0.3,
              text_color='#%02x%02x%02x' %
              (int(0 * 0.8), int(255 - 0 * 0.8), 150))

plot.add_layout(label)

# In[20]:

plot.circle('kp',
            'speed',
            source=source,
            size='car_volumn',
            legend='congection',
            fill_alpha=0.3,
            fill_color='color',
Ejemplo n.º 15
0
                                    y=np.random.random(N) * 10))

normal = Jitter(width=0.2, distribution="normal")
uniform = Jitter(width=0.2, distribution="uniform")

p = figure(x_range=(0, 4), y_range=(0, 10))
p.circle(x='x', y='y', color='firebrick', source=source, size=5, alpha=0.5)
p.circle(x='xn', y='y', color='olive', source=source, size=5, alpha=0.5)
p.circle(x='xu', y='y', color='navy', source=source, size=5, alpha=0.5)

label_data = ColumnDataSource(data=dict(
    x=[1, 2, 3], y=[10, 10, 10], t=['Original', 'Normal', 'Uniform']))
labels = Label(x='x',
               y='y',
               text='t',
               y_offset=2,
               source=label_data,
               render_mode='css',
               text_align='center')
p.add_layout(labels)

callback = CustomJS(args=dict(source=source, normal=normal, uniform=uniform),
                    code="""
    data=source.get('data')
    for (i=0; i < data['y'].length; i++) {
        data['xn'][i] = normal.compute(data['x'][i]+1)
    }
    for (i=0; i < data['y'].length; i++) {
        data['xu'][i] = uniform.compute(data['x'][i]+2)
    }
    source.trigger('change')
Ejemplo n.º 16
0
print('saved')
print("1.")
source = ColumnDataSource(data=data[years[0]])
print("2.")
plot = figure(x_range=(7, 68),
              y_range=(0.0, 28),
              title='Gapminder Data',
              plot_height=300)
plot.xaxis.ticker = SingleIntervalTicker(interval=5)
plot.xaxis.axis_label = "GDP Per Capita ($USD)"
plot.yaxis.ticker = SingleIntervalTicker(interval=1)
plot.yaxis.axis_label = "Unemployment Rate"
print("3.")
label = Label(x=1.1,
              y=18,
              text=str(years[0]),
              text_font_size='70pt',
              text_color='#eeeeee')
plot.add_layout(label)
print("4.")
print(regions_list)
print(Spectral6)
color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list)

plot.circle(
    x='gdp_pc',
    y='unemployment_rate',
    size='tech_export',
    source=source,
    fill_color={
        'field': 'region',
Ejemplo n.º 17
0
# brand values
brand_list = df2.brand.unique().tolist()
# brand_list = brand_list.sort()
brand = brand_list[0]

# apply filter to data based on year var
source = get_dataset(df2, year, brand)

# create plot from source
plot = create_figure(source)

# year label on plot
label = Label(x=840000,
              y=80000,
              text=str(df2['year'].min()),
              text_font_size='60px',
              text_color='#ff496c')

# dynamic plot title
title = Title(text='Car Resale Values by Year (Since 2012): ' + brand,
              align='left')

# adding plot labels to glyph
plot.add_layout(label)
plot.add_layout(title, 'above')

# slider tool, slider update action
year_select = Slider(start=df2['year'].min(),
                     end=df2['year'].max(),
                     value=df2['year'].min(),
Ejemplo n.º 18
0
def test_plot_add_layout_adds_label_to_plot_renderers():
    plot = figure()
    label = Label()
    plot.add_layout(label)
    assert label in plot.center
Ejemplo n.º 19
0
def plot_energy(
    ax,
    energy,
    kind,
    bfmi,
    figsize,
    textsize,
    fill_alpha,
    fill_color,
    fill_kwargs,
    plot_kwargs,
    bw,
    legend,
    backend_kwargs,
    show,
):
    """Bokeh energy plot."""
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi")),
        **backend_kwargs,
    }
    dpi = backend_kwargs.pop("dpi")

    figsize, _, _, _, line_width, _ = _scale_fig_size(figsize, textsize, 1, 1)

    fill_kwargs = {} if fill_kwargs is None else fill_kwargs
    plot_kwargs = {} if plot_kwargs is None else plot_kwargs
    plot_kwargs.setdefault("line_width", line_width)
    if kind == "hist":
        legend = False

    if ax is None:
        ax = create_axes_grid(
            1,
            figsize=figsize,
            squeeze=True,
            backend_kwargs=backend_kwargs,
        )

    _colors = [
        prop for _, prop in zip(
            range(10), cycle(mpl_rcParams["axes.prop_cycle"].by_key()
                             ["color"]))
    ]
    if (fill_color[0].startswith("C")
            and len(fill_color[0]) == 2) and (fill_color[1].startswith("C")
                                              and len(fill_color[1]) == 2):
        fill_color = tuple(
            (_colors[int(color[1:]) % 10] for color in fill_color))
    elif fill_color[0].startswith("C") and len(fill_color[0]) == 2:
        fill_color = tuple([_colors[int(fill_color[0][1:]) % 10]] +
                           list(fill_color[1:]))
    elif fill_color[1].startswith("C") and len(fill_color[1]) == 2:
        fill_color = tuple(
            list(fill_color[1:]) + [_colors[int(fill_color[0][1:]) % 10]])

    series = zip(
        fill_alpha,
        fill_color,
        ("Marginal Energy", "Energy transition"),
        (energy - energy.mean(), np.diff(energy)),
    )

    labels = []

    if kind == "kde":
        for alpha, color, label, value in series:
            fill_kwargs["fill_alpha"] = alpha
            fill_kwargs["fill_color"] = vectorized_to_hex(color)
            plot_kwargs["line_alpha"] = alpha
            plot_kwargs["line_color"] = vectorized_to_hex(color)
            _, glyph = plot_kde(
                value,
                bw=bw,
                label=label,
                fill_kwargs=fill_kwargs,
                plot_kwargs=plot_kwargs,
                ax=ax,
                legend=legend,
                backend="bokeh",
                backend_kwargs={},
                show=False,
                return_glyph=True,
            )
            labels.append((
                label,
                glyph,
            ))

    elif kind == "hist":
        hist_kwargs = plot_kwargs.copy()
        hist_kwargs.update(**fill_kwargs)

        for alpha, color, label, value in series:
            hist_kwargs["fill_alpha"] = alpha
            hist_kwargs["fill_color"] = vectorized_to_hex(color)
            hist_kwargs["line_color"] = None
            hist_kwargs["line_alpha"] = alpha
            _histplot_bokeh_op(
                value.flatten(),
                values2=None,
                rotated=False,
                ax=ax,
                hist_kwargs=hist_kwargs,
                is_circular=False,
            )

    else:
        raise ValueError(f"Plot type {kind} not recognized.")

    if bfmi:
        for idx, val in enumerate(e_bfmi(energy)):
            bfmi_info = Label(
                x=int(figsize[0] * dpi * 0.58),
                y=int(figsize[1] * dpi * 0.73) - 20 * idx,
                x_units="screen",
                y_units="screen",
                text=f"chain {idx:>2} BFMI = {val:.2f}",
                border_line_color=None,
                border_line_alpha=0.0,
                background_fill_color="white",
                background_fill_alpha=1.0,
            )

            ax.add_layout(bfmi_info)

    if legend and label is not None:
        legend = Legend(
            items=labels,
            location="center_right",
            orientation="horizontal",
        )
        ax.add_layout(legend, "above")
        ax.legend.click_policy = "hide"

    show_layout(ax, show)

    return ax
Ejemplo n.º 20
0
    6: "p.line([3, 4], [3, 2])"
}

show(p)
while len(correct_guesses) < letters and len(incorrect_guesses) < 6:
    guess = raw_input("Please guess a letter: ")
    if len(guess) != 1 or guess.isdigit():
        print("Please guess a single letter.")
    else:
        if guess in correct_guesses or guess in incorrect_guesses:
            print("You already guessed that letter!")
        elif guess in secret_word:
            space = secret_word.index(guess)
            spaces = [i for i, x in enumerate(secret_word) if x == guess]
            for space in spaces:
                correct = Label(x=space, y=0, text=guess)
                p.add_layout(correct)
                show(p)
                correct_guesses.append(guess)
        else:
            tries = len(incorrect_guesses)
            incorrect = Label(x=4, y=6 - 0.25 * tries, text=guess)
            p.add_layout(incorrect)
            incorrect_guesses.append(guess)
            eval(hanged_person[len(incorrect_guesses)])
            show(p)

if len(correct_guesses) == letters:
    print("Congratulations! You win!")
else:
    print("Too bad, you died :-( The word was %s" % (secret_word))
Ejemplo n.º 21
0
yscale = 0.75
number_of_modes = 8

for v in range(number_of_modes):
    H_v = hermite(v)
    N_v = (np.pi**0.5 * 2**v * factorial(v))**(-0.5)
    psi = N_v * H_v(q) * np.exp(-q**2 / 2)
    E_v = v + 0.5  # Use energy level as y-offset.

    y = yscale * psi + E_v
    yupper = np.where(y >= E_v, y, E_v)
    ylower = np.where(y <= E_v, y, E_v)

    p.varea(q, yupper, E_v, fill_color="coral")
    p.varea(q, ylower, E_v, fill_color="orange")
    p.line(q, y, color="red", line_width=2)

    p.add_layout(
        Label(x=-5.8, y=E_v, y_offset=-21, text=r"$$v = " + str(v) + r"$$"))
    p.add_layout(
        Label(x=3.9,
              y=E_v,
              y_offset=-25,
              text=r"$$E_" + str(v) + r" = (" + str(2 * v + 1) +
              r"/2) \hbar\omega$$"))

V = q**2 / 2
p.line(q, V, line_color="black", line_width=2, line_dash="dashed")

show(p)
Ejemplo n.º 22
0
p.background_fill_color = "black"
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
nifty = df['Nifty'].iloc[1]
ltp = Span(location=nifty,
           dimension='height',
           line_color='green',
           line_dash='dashed',
           line_width=3)
p.add_layout(ltp)
my_label = Label(x=nifty,
                 y=max_oi_change,
                 text=str(nifty),
                 border_line_color='green',
                 border_line_alpha=1.0,
                 y_offset=3,
                 x_offset=-38,
                 text_color='white',
                 text_font_size='8pt',
                 background_fill_color='green',
                 background_fill_alpha=1.0)
p.add_layout(my_label)

# Total OI Plot
p2 = figure(x_range=(minRange, maxRange),
            plot_width=750,
            plot_height=500,
            x_minor_ticks=2)
p2.vbar(x=dodge('strikePrice', -10, range=p2.x_range),
        top='CE_OI',
        source=source,
Ejemplo n.º 23
0
plot.line('x',
          'y',
          source=line_source,
          line_width=3,
          line_alpha=0.6,
          color='black')
plot.circle('x', 'y', source=point_source, size=10, color='black')

# set up static line and annotations
plot.line(x_line, y_line, line_width=5, color='blue', line_alpha=0.3)
plot.circle(x_points, y_points, size=10, color='blue', line_alpha=0.3)

mytext = Label(x=10,
               y=87,
               text='[I] = 0 (μM)',
               text_color="blue",
               text_alpha=0.5)
plot.add_layout(mytext)

# add axes lines
vline = Span(location=0,
             dimension='height',
             line_color='black',
             line_width=1,
             line_alpha=0.3)
hline = Span(location=0,
             dimension='width',
             line_color='black',
             line_width=1,
             line_alpha=0.3)
Ejemplo n.º 24
0
def plot_flight_modes_background(data_plot, flight_mode_changes, vtol_states=None):
    """ plot flight modes as filling background (with different colors) to a
    DataPlot object """
    vtol_state_height = 40
    added_box_annotation_args = {}
    p = data_plot.bokeh_plot
    if vtol_states is not None:
        added_box_annotation_args['bottom'] = vtol_state_height
        added_box_annotation_args['bottom_units'] = 'screen'
    labels_y_pos = []
    labels_x_pos = []
    labels_text = []
    labels_color = []
    labels_y_offset = data_plot.plot_height - 60
    if data_plot.has_param_change_labels:
        # make sure there's no overlap with changed parameter labels
        labels_y_offset -= 10 + 4 * 10

    for i in range(len(flight_mode_changes)-1):
        t_start, mode = flight_mode_changes[i]
        t_end, mode_next = flight_mode_changes[i + 1]
        if mode in flight_modes_table:
            mode_name, color = flight_modes_table[mode]
            annotation = BoxAnnotation(left=int(t_start), right=int(t_end),
                                       fill_alpha=0.09, line_color=None,
                                       fill_color=color,
                                       **added_box_annotation_args)
            p.add_layout(annotation)

            if flight_mode_changes[i+1][0] - t_start > 1e6: # filter fast
                                                 # switches to avoid overlap
                labels_text.append(mode_name)
                labels_x_pos.append(t_start)
                labels_y_pos.append(labels_y_offset)
                labels_color.append(color)


    # plot flight mode names as labels
    # they're only visible when the mouse is over the plot
    if len(labels_text) > 0:
        source = ColumnDataSource(data=dict(x=labels_x_pos, text=labels_text,
                                            y=labels_y_pos, textcolor=labels_color))
        labels = LabelSet(x='x', y='y', text='text',
                          y_units='screen', level='underlay',
                          source=source, render_mode='canvas',
                          text_font_size='10pt',
                          text_color='textcolor', text_alpha=0.85,
                          background_fill_color='white',
                          background_fill_alpha=0.8, angle=90/180*np.pi,
                          text_align='right', text_baseline='top')
        labels.visible = False # initially hidden
        p.add_layout(labels)

        # callback doc: https://bokeh.pydata.org/en/latest/docs/user_guide/interaction/callbacks.html
        code = """
        labels.visible = cb_obj.event_name == "mouseenter";
        """
        callback = CustomJS(args=dict(labels=labels), code=code)
        p.js_on_event(events.MouseEnter, callback)
        p.js_on_event(events.MouseLeave, callback)


    if vtol_states is not None:
        for i in range(len(vtol_states)-1):
            t_start, mode = vtol_states[i]
            t_end, mode_next = vtol_states[i + 1]
            if mode in vtol_modes_table:
                mode_name, color = vtol_modes_table[mode]
                p.add_layout(BoxAnnotation(left=int(t_start), right=int(t_end),
                                           fill_alpha=0.09, line_color=None,
                                           fill_color=color,
                                           top=vtol_state_height, top_units='screen'))
        # use screen coords so that the label always stays. It's a bit
        # unfortunate that the x position includes the x-offset of the y-axis,
        # which depends on the axis labels (e.g. 4.000e+5 creates a large offset)
        label = Label(x=83, y=12, x_units='screen', y_units='screen',
                      text='VTOL mode', text_font_size='10pt', level='glyph',
                      background_fill_color='white', background_fill_alpha=0.8)
        p.add_layout(label)
Ejemplo n.º 25
0
    def make(
            self, comp_category='deaths_new_dma_per_1M', regions=None,
            comp_type='vbar', overlay=None, title='', legend_title='Region: Start Date',
            palette_base=Viridis256, palette_flip=False, palette_shift=0, 
            multiline_labels=True, label_offsets={}, fs_labels=8, 
            legend=False, legend_location='top_right',
            x_fontsize=10, y_fontsize=10,
            fs_xticks=16, fs_yticks=16, fs_overlay=10,
            fs_legend=8, h_legend=20, w_legend=20,
            width=750, height=500, base_inc=.25,
            save_file=False, filename=None, annotations=[],
            bg_color='white', bg_alpha=1, border_color='white', border_alpha=1,
        ):
        self.df_comp = self.df[self.df[comp_category].notna()].copy(deep=True)
        
        # If regions are passed, filter the dataframe and reset attributes
        # via `_chart_setup`
        if regions:
            regions = [regions] if isinstance(regions, str) else regions
            self.df_comp = self.df_comp[self.df_comp['region_name'].isin(regions)]
        else:
            regions = list(self.regions)
        
        # Setup additional class attributes
        self.comp_category = comp_category
        self.comp_type = comp_type
        self.palette_base = palette_base
        self.base_inc = base_inc
        self.max_length = self.df.groupby('region_id')['days'].max().max().days + 1
        self.days = [i for i in range(self.max_length)]

        # Set chart attributes
        fs_labels = str(fs_labels) + 'pt'
        min_y = self.df_comp[comp_category].min()
        min_y += min_y * .01
        max_y = self.df_comp[comp_category].max()
        if max_y < 0:
            max_y -= max_y * .1
        else:
            max_y += max_y * .1

        p = figure(
            y_range=Range1d(start=min_y, end=max_y),
            plot_height=height, plot_width=width,
            min_border=0,
            toolbar_location=None,
            title=title,
        )

        # Create the Color Palette
        # An extra color is added and changes in the coloridx are limited
        # to all but the last item, to allow for shifting of palette
        # via palette_shift
        palette_base = np.array(palette_base)
        coloridx = np.round(np.linspace(0, len(palette_base) - 1, len(regions) + 1)).astype(int)
        if palette_flip:
            coloridx[:-1] = coloridx[:-1][::-1]
        if palette_shift:
            coloridx[:-1] += palette_shift
        palette = palette_base[coloridx]
        
        if comp_type == 'multiline':
            ml_data = self._multiline_source()
            ml_data['color'] = palette[:-1]
            source_ml = ColumnDataSource(ml_data)
            p.multi_line(xs='x', ys='y', line_color='color', legend_group='regions', line_width=5, source=source_ml)

            # Setup labels for each line
            if multiline_labels:
                for i in range(len(ml_data['x'])):
                    x_label = int(ml_data['x'][i][-1])
                    y_label = ml_data['y'][i][-1]
                    x_offset = -20
                    y_offset = 5
                    label_region = ml_data['regions'][i]

                    if label_region in label_offsets.keys():
                        x_offset += label_offsets[label_region]['x_offset']
                        y_offset += label_offsets[label_region]['y_offset']
    
                    label = Label(
                        x=x_label, y=y_label, 
                        x_offset=x_offset, y_offset=y_offset,
                        text_font_size=fs_labels, text_color=palette[i], text_alpha=.8,
                        text=label_region, text_font_style='bold',
                        render_mode='canvas'
                    )
                    p.add_layout(label)

        if comp_type == 'vbar':
            vbar_data = self._vbar_source()
            vbar_source = ColumnDataSource(vbar_data)
            increments = self._bar_incrementer(regions)
            
            legend_items = []
            for i, region in enumerate(regions):
                region_start = vbar_data['{}_date'.format(region)][0]
                legend_label = region + ': {}'.format(region_start)

                v = p.vbar(
                    x=dodge('x', increments[i], range=p.x_range), top=region, width=.3, 
                   source=vbar_source, color=palette[i], legend_label=legend_label,
                )
        
        p.legend.visible = legend

        if legend_title:
            p.legend.title = 'Region: Start Date'

        p.legend.location = legend_location
        p.legend.border_line_color = 'black'
        p.legend.glyph_height = h_legend
        p.legend.glyph_width = w_legend
        p.legend.label_height = h_legend
        p.legend.label_width = h_legend

        p.legend.label_text_font_size = str(fs_legend) + 'pt'
        p.legend.background_fill_alpha = 0.0
        p.legend.border_line_alpha = 0.0

        p.xaxis.axis_label = self.labels['days_' + self.start_factor]
        p.xaxis.axis_label_text_font_size = str(x_fontsize) + 'pt'
        p.xaxis.major_label_text_font_size = str(fs_xticks) + 'pt'

        p.yaxis.axis_label = self.labels[comp_category]
        p.yaxis.axis_label_text_font_size = str(y_fontsize) + 'pt'
        p.yaxis.major_label_text_font_size = str(fs_yticks) + 'pt'

        p.xaxis.major_tick_line_color = None
        p.xgrid.grid_line_color = None

        p.min_border = 20

        if overlay:
            overlay_days = []
            overlay_by_region = []
            for region_id, df_group in self.df_comp.groupby('region_id'):
                overlays = list(df_group[overlay].dropna().values)
                overlay_days.append([i for i in range(len(overlays))])
                overlay_by_region.append(overlays)
                
            data2 = {'x': overlay_days, 'y': overlay_by_region, 'color': palette[:-1]}
            source2 = ColumnDataSource(data=data2)
            start = min(olay for region in overlay_by_region for olay in region) * 0.8
            end = max(olay for region in overlay_by_region for olay in region) * 1.1
            p.extra_y_ranges = {overlay: Range1d(start=start, end=end)}
            p.multi_line(xs='x', ys='y', line_color='color', line_width=4, source=source2,
                      y_range_name=overlay, alpha=.3,
            )

            right_axis_label = self.labels[overlay]
            p.add_layout(LinearAxis(y_range_name='{}'.format(overlay), axis_label=right_axis_label, axis_label_text_font_size=str(fs_overlay) + 'pt'), 'right')

        p.xgrid.grid_line_color = None
        p.ygrid.grid_line_color = None
        p.outline_line_color = border_color

        p.background_fill_color = bg_color
        p.background_fill_alpha = bg_alpha
        p.border_fill_color = border_color
        p.border_fill_alpha = border_alpha

        for annot in annotations:
            p.add_layout(Label(**annot))

        if save_file:
            export_png(p, filename=filename)

        return p
Ejemplo n.º 26
0
color = palettes.Category20b[4]
n = fig.circle("x", "y", size=12,fill_alpha=0.8, fill_color=color[3], source=source_nodes)
fig.add_tools(HoverTool(renderers=[n], tooltips=hover_node))
# define color when (not-) selected
selected_node = Circle(fill_alpha=0.8, fill_color=color[0], line_color=None)
nonselected_node = Circle(fill_alpha=0.6, fill_color=color[3], line_color=None)
# and trigger it correctly
n.selection_glyph = selected_node
n.nonselection_glyph = nonselected_node
n.data_source.on_change('selected', update_stacked_bars)

#inidcator for data-load
source_ind = ColumnDataSource(data=dict(x=[1],y=[1],color=["green"]))
fig_indicator = figure(plot_height=100, plot_width=350, x_range=(0,8), y_range=(0,2),
                       toolbar_location=None, tools="")
label = Label(x=1.8, y=.8, text="Data is Loaded!", text_alpha=1)
fig_indicator.add_layout(label)

fig_indicator.axis.visible = False
fig_indicator.grid.visible = False
fig_indicator.outline_line_alpha = 0
fig_indicator.circle("x", "y", size=25, fill_alpha=0.6, fill_color="color", line_color=None, source=source_ind)

# add the geographical map
fig.add_tile(STAMEN_LITE)
# set up layout = row(row|column)
# UI sclaing for everthing except the widget column with the inducator plot
widgets =  column(widgetbox(slider, flow_type_botton, select_market_db, select_grid_db, width=300), fig_indicator)
main_map = row(fig, fig_bar, sizing_mode="scale_height")
layout = row(main_map, widgets, sizing_mode="scale_height")
Ejemplo n.º 27
0
def make_plot():

    pi = math.pi

    data = pd.DataFrame()
    list1=['Telemedicine','Education','Transportation','Banking','Hospitals','Domestic','Exports','Freelance']
    list2=[200,200,200,200,200,500,500,1000]
    data['country'] = list1
    data['value'] =list2

    data['angle'] = data['value']/data['value'].sum() * 2*pi
    data['color'] = ['#084594', '#2171b5', '#4292c6', '#6baed6', '#9ecae1', '#fbbb3c','#f0901a','#de5050']
    data['skill_1'] = ["Full-stack developers","IT courses-instructors","Full-stack developers","Hardware and Network system skills","Java, Android and IOS development","Web Application","Web Application",'Software development']
    data['skill_2'] = ['Mobile, Web & Cloud-based App development', 'IT-enabling of administrative services', 'Software Quality Assurance, Testing and Technical support', 'MS Office Suite', 'Linux, Windows and Virtualization (ESXi)', 'Web Design', 'Mobile Application', 'Web design and development' ]
    data['skill_3'] = ['Database administration', 'IT-enabling of accounting services', 'CISCO/Microsoft certification', 'Accessing networks/servers', 'Routing, Switching for Networking', 'Mobile Application','ERP development', 'System architecture' ]
    data['skill_4'] = ['Data analytics', 'Data entry', 'MS office', 'Java and C++', 'V-LAN for Networking', 'Hardware, Server Installation and Maintenance','QA Testing', 'Graphic design']
    data['skill_5'] = ['Problem-solving mindset and adaptability', 'Administrative skills', 'Communication and presentation skills', 'Hardware, Software and Network troubleshooting', 'Basic computer literacy', 'ERP development ','Web Design', 'HTML & JAVA programming language']

    # Add plot
    p = figure(plot_height=500, plot_width=700,
                tools="pan,zoom_in,zoom_out,save,reset", x_range = (-0.5,1))

    p.wedge(x=0.15, y=1, radius=0.35, 
            start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),
            line_color="white", fill_color='color', legend_field='country', source=data)

    #text=['FE firms', 'BE firms','freelancers']

    citation1 = Label(x=0.3, y=1.54, x_units='data', y_units='data',
                     text='Front End firms', render_mode='css',
                     border_line_color='#084594', border_line_alpha=1.0,
                     background_fill_color='#6baed6', background_fill_alpha=1.0)

    citation2 = Label(x=-0.4, y=0.95, x_units='data', y_units='data',
                     text='Back End firms', render_mode='css',
                     border_line_color='#c18a31', border_line_alpha=1.0,
                     background_fill_color='#fbbb3c', background_fill_alpha=1.0)

    citation3 = Label(x=0.35, y=0.5, x_units='data', y_units='data',
                 text='Freelance', render_mode='css',
                 border_line_color='#e65441', border_line_alpha=1.0,
                 background_fill_color='#ef6565', background_fill_alpha=1.0)

    p.add_layout(citation1)
    p.add_layout(citation2)
    p.add_layout(citation3)


    p.axis.axis_label=None
    p.axis.visible=None
    p.grid.grid_line_color = None



    # Add Tooltips
    hover = HoverTool()
    hover.tooltips = """
      <div>
        <h3>Top Five Skills</h3>
        <div>1. @skill_1</div>
        <div>2. @skill_2</div>
        <div>3. @skill_3</div>
        <div>4. @skill_4</div>
        <div>5. @skill_5</div>
      </div>
    """
    p.add_tools(hover)

    script, div = components(p)
    return script, div
Ejemplo n.º 28
0
us = p.patches("state_xs", "state_ys",
    fill_color=dict(field="trend", transform=mapper),
    source=source,
    line_color="#333344", line_width=1)

p.x_range.renderers = [us]
p.y_range.renderers = [us]

totality_x, totality_y = zip(*totality_path.points)
p.patch(totality_x, totality_y,
    fill_color="black", fill_alpha=0.7,
    line_color=None)

path = Label(
    x=-76.3, y=31.4,
    angle=-36.5, angle_units="deg",
    text="Solar eclipse path of totality",
    text_baseline="middle", text_font_size="11px", text_color="silver")
p.add_layout(path)

color_bar = ColorBar(
    color_mapper=mapper,
    location="bottom_left", orientation="horizontal",
    title="Popularity of \"solar eclipse\" search term",
    title_text_font_size="16px", title_text_font_style="bold",
    title_text_color="lightgrey", major_label_text_color="lightgrey",
    background_fill_alpha=0.0)
p.add_layout(color_bar)

notes = Label(
    x=0, y=0, x_units="screen", y_units="screen",
Ejemplo n.º 29
0
p.add_tools(
    HoverTool(tooltips=[
        ("Strain", "@info"),
        ("Deaths", "@deaths{(0,0)}"),
        ("Population", "@pop{(0,0)}"),
    ]))
# MEAN LINE SPAN
span = Span(location=np.nanmean(data['Deaths']),
            dimension='width',
            line_color='firebrick',
            line_width=3,
            line_alpha=0.43)
p.add_layout(span)
my_label = Label(x=5,
                 y=np.nanmean(data['Deaths']) + 10,
                 text='MEAN LINE',
                 text_color='firebrick',
                 text_alpha=0.43,
                 text_font_style='bold')
p.add_layout(my_label)

source = ColumnDataSource(
    data={
        'x': data['Season'],
        'info': data['Strain'],
        'deaths': data['Deaths'],
        'pop': data['Pop']
    })
p.line(x="x",
       y='deaths',
       source=source,
       line_width=4,
def cant_pressure_plot(layers, net, min_length_cant_pressure, min_length_net_pressure, min_length_elev, min_length, z,
                       deflection, scale_factor, cant, multi_x, multi_y, multiplier, zero_point):
    axis_size = max([max(net[0]), -1 * min(net[0]), max(cant[0]), -1*min(cant[0])])
    p = figure(
        x_range=[-axis_size - 1500, axis_size*4.0],
        y_range=[net[1][-1] - 1, net[1][0] + 4],
        title="Lateral Pressure Diagram",
        plot_width=900,
        plot_height=1200
    )
    p.xaxis.bounds = (0, 0)
    p.yaxis.bounds = (0, 0)

    new_cant = [[], []]
    for i in range(len(cant[0])):
        if cant[0][i] != 0:
            new_cant[0].append(cant[0][i])
            new_cant[1].append(cant[1][i])
    cant = new_cant

    p.line(net[0], net[1], line_width=2, color='black')
    p.line(cant[0], cant[1], line_width=1, color='gray')
    p.line([0, 0], [net[1][0], net[1][-1]], color='black')
    p.line([float(min_length_net_pressure), float(min_length_cant_pressure)],
           [float(min_length_elev+z), float(min_length_elev)], line_width=2, color="black")
    p.line([0, float(min_length_cant_pressure)], [float(min_length_elev), float(min_length_elev)],
           line_width=2, color="black")

    p.add_layout(Label(x=1.25*axis_size, y=float(min_length_elev+z),
                       text=str(round(min_length_net_pressure, 2)), text_font_size='12pt'))
    p.add_layout(Label(x=2.25*axis_size, y=float(min_length_elev),
                       text=str(round(min_length_cant_pressure, 2)), text_font_size='12pt'))
    p.add_layout(Label(x=-axis_size, y=float(net[1][0] + 2), text="Lmin = " + str(round(min_length, 2)) + "'",
                       text_font_size='12pt'))
    p.add_layout(Label(x=3.25 * axis_size, y=net[1][0] + 2, text="Deflection", text_font_size='14pt'))
    p.add_layout(Label(x=1.25 * axis_size, y=net[1][0] + 2, text="Net Pressure", text_font_size='14pt'))
    p.add_layout(Label(x=2.25 * axis_size, y=net[1][0] + 2, text="Cant Pressure", text_font_size='14pt'))
    p.add_layout(Arrow(end=NormalHead(size=5),
                       x_start=-0.75 * axis_size, y_start=zero_point, x_end=-0.75 * axis_size, y_end=zero_point - 0.5))
    p.add_layout(Label(x=-0.80 * axis_size, y=zero_point, text="x=0'"))

    x, y = 0, 0
    for k in range(len(net[0])):
        i = net[0][k]
        j = net[1][k]
        if j == y and i != x:
            pressure_label = Label(x=1.25*axis_size, y=j-0.5, text=str(i), text_font_size='12pt')
        else:
            pressure_label = Label(x=1.25*axis_size, y=j, text=str(i), text_font_size='12pt')
        x, y = i, j
        p.add_layout(pressure_label)
    x, y = 0, 0
    for k in range(len(cant[0])):
        i = cant[0][k]
        j = cant[1][k]
        if j == y and i != x:
            pressure_label = Label(x=2.25*axis_size, y=j-0.5, text=str(i), text_font_size='12pt')
        else:
            pressure_label = Label(x=2.25*axis_size, y=j, text=str(i), text_font_size='12pt')
        x, y = i, j
        p.add_layout(pressure_label)

    for i in range(len(net[1])):
        p.line([-axis_size-1000, 4.0*axis_size], [net[1][i], net[1][i]],
               color='dimgray', alpha=0.7)
        work_point_label = Label(x=-axis_size-1000, y=net[1][i], text=str(net[1][i]), text_font_size='12pt')
        p.add_layout(work_point_label)
        for j in range(len(deflection[0])):
            if deflection[0][j][1] == net[1][i] and deflection[0][j][1] != deflection[0][j-1][1]:
                p.add_layout(Label(x=3.25*axis_size, y=net[1][i], text=str(round(deflection[0][j][0], 3))+'"',
                                   text_font_size='12pt'))
    if multi_x:
        p.line([round(float(multi_x[0]), 2), round(float(multi_x[1]), 2)],
               [round(float(multi_y[0]), 2), round(float(multi_y[1]), 2)], line_width=2, color="black")
        p.line([0, round(float(multi_x[1]), 2)],
               [round(float(multi_y[1]), 2), round(float(multi_y[1]), 2)], line_width=2, color="black")
        p.add_layout(Label(x=-axis_size, y=net[1][0] + 1, text="Mult @ " + str(net[1][0] - multi_y[1]) + "' long = " +
                                                            str(round(multiplier, 2)), text_font_size='12pt'))
        p.add_layout(Label(x=1.25 * axis_size, y=float(multi_y[0]), text=str(round(multi_x[0], 2)),
                           text_font_size='12pt'))
        p.add_layout(Label(x=2.25 * axis_size, y=float(multi_y[1]), text=str(round(multi_x[1], 2)),
                           text_font_size='12pt'))
    deflection_x = []
    deflection_y = []
    for i in range(len(deflection[0])):
        deflection_x.append(deflection[0][i][0])
        deflection_y.append(deflection[0][i][1])

    deflection_shape = [-1 * scale_factor * x for x in deflection_x]
    p.line(deflection_shape, deflection_y, color='green', line_width=1)
    deflection_label = Label(x=-axis_size, y=net[1][0] + 3, text='Max Deflection = ' + str(deflection[1]) +
                                                                 '" at Elev. ' + str(deflection[2]) + "'.",
                             text_font_size='12pt')
    p.add_layout(deflection_label)

    return p