Here are the examples of the python api bokeh.models.Range1d taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
76 Examples
3
View Source File : xbokeh.py
License : MIT License
Project Creator : ahuang11
License : MIT License
Project Creator : ahuang11
def _initialize_limits(self, p):
if self.xlim is not None:
p.x_range = models.Range1d(self.xlim[0], self.xlim[-1])
if self.ylim is not None:
p.y_range = models.Range1d(self.ylim[0], self.ylim[-1])
@staticmethod
3
View Source File : line.py
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
def patches(x, y, diff):
y = diff.set_index(x)[y]
range = y.abs().max() * 1.1
green = y.clip(lower=0).append(pd.Series([0, 0], index=[y.index[len(y) - 1], y.index[0]]))
red = y.clip(upper=0).append(pd.Series([0, 0], index=[y.index[len(y) - 1], y.index[0]]))
return green, red, Range1d(start=-range, end=range)
def add_tsid_line(f, x, y, source, color='black', line_dash='solid'):
3
View Source File : line.py
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
def add_cum_line(f, y, source, color='black', line_dash='solid'):
y_c = source[y].sort_values(ascending=False).reset_index(drop=True)
f.line(x=y_c.index, y=y_c, line_color=color, line_dash=line_dash)
f.x_range = Range1d(start=y_c.index.max(), end=y_c.index.min())
df = y_c.to_frame('y')
df['x'] = df.index
return df
def cumulative_plot(nx, ny, y, source, other=None, ylo=None, yhi=None, output_backend=DEFAULT_BACKEND):
3
View Source File : line.py
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
def histogram_plot(nx, ny, x, source, xlo=None, xhi=None, nsub=5, output_backend=DEFAULT_BACKEND):
if not present(source, x): return None
xlo, xhi = source[x].min() if xlo is None else xlo, source[x].max() if xhi is None else xhi
bins = pd.interval_range(start=xlo, end=xhi, periods=nsub * (xhi - xlo), closed='left')
c = [palettes.Inferno[int(xhi - xlo + 1)][int(b.left - xlo)] for b in bins]
hrz_categorized = pd.cut(source[x], bins)
counts = hrz_categorized.groupby(hrz_categorized).count()
f = figure(output_backend=output_backend, plot_width=nx, plot_height=ny, x_range=Range1d(start=xlo, end=xhi),
x_axis_label=x)
f.quad(left=counts.index.categories.left, right=counts.index.categories.right, top=counts, bottom=0,
color=c, fill_alpha=0.2)
f.toolbar_location = None
f.yaxis.visible = False
return f
def add_route(f, source, color='black', line_dash='solid'):
3
View Source File : utils.py
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
def make_range(column, lo=None, hi=None):
column = column.dropna()
mn, mx = column.min() if lo is None else lo, column.max() if hi is None else hi
delta = mx - mn
return Range1d(start=mn - 0.1 * delta, end=mx + 0.1 * delta)
def evenly_spaced_hues(n, saturation=1, value=1, stagger=1):
3
View Source File : plotting.py
License : BSD 3-Clause "New" or "Revised" License
Project Creator : BuildACell
License : BSD 3-Clause "New" or "Revised" License
Project Creator : BuildACell
def render_network_bokeh(CRN,layout="force", layoutfunc = None, plot_reactions = True, plot_species = True, plot_edges = True, plot_arrows = True,
iterations=2000,rseed=30,posscale=1,export=False,species_glyph_size = 12, reaction_glyph_size = 8, export_name = None, **keywords):
DG, DGspec, DGrxn = generate_networkx_graph(CRN,**keywords) #this creates the networkx objects
plot = Plot(plot_width=500, plot_height=500, x_range=Range1d(-500, 500), y_range=Range1d(-500, 500)) #this generates a
show_im = False
images = None
if("imagedict" in keywords and keywords["imagedict"] is not None):
show_im = True
if(export):
plot.output_backend = "svg"
graphPlot(DG,DGspec,DGrxn,plot,layout=layout,posscale=posscale,iterations=iterations,rseed=rseed,show_species_images=show_im,
layoutfunc=layoutfunc, plot_reactions = plot_reactions, plot_species = plot_species, plot_edges = plot_edges, plot_arrows = plot_arrows,
species_glyph_size = species_glyph_size, reaction_glyph_size = reaction_glyph_size)
if(export):
if export_name is None:
raise ValueError("To export you must supply export_name keyword.")
export_svgs(plot,filename=export_name+".svg")
return plot
3
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getSuspFigure(df):
vars = ['speedkmh', 'sus_travel_lf', 'sus_travel_lr',
'sus_travel_rf', 'sus_travel_rr']
tools = ['time', 'dist']+vars
return getSimpleFigure(df, vars, tools,
{"sus_travel": Range1d(start=-10, end=120)})
def getBrakeTempFigure(df):
3
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getBrakeTempFigure(df):
vars = ['brake_temp_lf','brake_temp_lr',
'brake_temp_rf', 'brake_temp_rr',
'throttle','brake']
tools = ['time', 'dist', 'speed']+vars
return getSimpleFigure(df, vars+['tc', 'abs'], tools,
{"pedals": Range1d(start=-20, end=700), "tcabs": Range1d(start=-1, end=20)},
{"pedals":['throttle','brake'], "tcabs":['tc', 'abs']})
def getWheelSpeedFigure(df):
3
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getWheelSpeedFigure(df):
vars = ['wheel_speed_lf','wheel_speed_lr',
'wheel_speed_rf', 'wheel_speed_rr',
'throttle','brake']
tools = ['time','dist','speed']+vars
return getSimpleFigure(df, vars+['tc', 'abs'], tools,
{"pedals": Range1d(start=-20, end=400), "tcabs": Range1d(start=-1, end=20)},
{"pedals":['throttle','brake'], "tcabs":['tc', 'abs']})
def getTyreTairFigure(df):
3
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getTyreTairFigure(df):
vars = ['tyre_tair_lf','tyre_tair_lr',
'tyre_tair_rf', 'tyre_tair_rr',
'throttle','brake']
tools = ['time', 'dist', 'speed']+vars
return getSimpleFigure(df, vars+['tc', 'abs'], tools,
{"pedals": Range1d(start=-20, end=400), "tcabs": Range1d(start=-1, end=20)},
{"pedals":['throttle','brake'], "tcabs":['tc', 'abs']})
def getTyrePreassureFigure(df):
3
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getTyrePreassureFigure(df):
vars = ['speedkmh', 'tyre_press_lf','tyre_press_lr',
'tyre_press_rf', 'tyre_press_rr']
tools = ['time', 'dist']+vars
return getSimpleFigure(df, vars, tools,
{"tyre_press": Range1d(start=26, end=32)})
def getOversteerFigure(df):
3
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getOversteerFigure(df):
vars = ['speedkmh','oversteer','understeer']#,'steering_corr','neutral_steering']
tools = ['time','dist']+vars
p0 = getSimpleFigure(df, vars+['tc', 'throttle','brake'], tools,
{"pedals": Range1d(start=-10, end=500), "tc": Range1d(start=-1, end=50), "oversteer": Range1d(start=-15, end=25)},
{"pedals":['throttle','brake'], "tc":['tc','g_lat'], "oversteer":['steering_corr','neutral_steering','oversteer','understeer']})
vars = ['g_lat', 'g_lon', 'g_sum','steering_corr','neutral_steering', 'oversteer', 'understeer']
tools = ['time','dist']+vars
p1 = getSimpleFigure(df, vars, tools,
{"oversteer": Range1d(start=-15, end=35)},
{"oversteer":['steering_corr','neutral_steering',
'oversteer','understeer']},
x_range = p0.x_range)
return gridplot([p0, p1], ncols=1, sizing_mode='scale_width')
def getLapDelta():
3
View Source File : test_json_encoder.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_model(self):
m = Range1d(start=10, end=20)
assert self.encoder.default(m) == m.ref
assert isinstance(self.encoder.default(m), dict)
def test_hasprops(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_basic(self):
r = Range1d()
check_properties_existence(r, [
"callback",
"start",
"end",
"reset_start",
"reset_end",
"bounds",
"min_interval",
"max_interval"],
)
def test_init_with_timedelta(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_init_with_timedelta(self):
range1d = Range1d(start=-dt.timedelta(seconds=5), end=dt.timedelta(seconds=3))
assert range1d.start == -dt.timedelta(seconds=5)
assert range1d.end == dt.timedelta(seconds=3)
assert range1d.bounds is None
def test_init_with_datetime(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_init_with_datetime(self):
range1d = Range1d(start=dt.datetime(2016, 4, 28, 2, 20, 50), end=dt.datetime(2017, 4, 28, 2, 20, 50))
assert range1d.start == dt.datetime(2016, 4, 28, 2, 20, 50)
assert range1d.end == dt.datetime(2017, 4, 28, 2, 20, 50)
assert range1d.bounds is None
def test_init_with_float(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_init_with_float(self):
range1d = Range1d(start=-1.0, end=3.0)
assert range1d.start == -1.0
assert range1d.end == 3.0
assert range1d.bounds is None
def test_init_with_int(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_init_with_int(self):
range1d = Range1d(start=-1, end=3)
assert range1d.start == -1
assert range1d.end == 3
assert range1d.bounds is None
def test_init_with_positional_arguments(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_init_with_positional_arguments(self):
range1d = Range1d(1, 2)
assert range1d.start == 1
assert range1d.end == 2
assert range1d.bounds is None
def test_init_with_keyword_arguments(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_init_with_keyword_arguments(self):
range1d = Range1d(start=1, end=2)
assert range1d.start == 1
assert range1d.end == 2
assert range1d.bounds is None
def test_cannot_initialize_with_both_keyword_and_positional_arguments(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_cannot_initialize_with_both_keyword_and_positional_arguments(self):
with pytest.raises(ValueError):
Range1d(1, 2, start=1, end=2)
def test_cannot_initialize_with_three_positional_arguments(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_cannot_initialize_with_three_positional_arguments(self):
with pytest.raises(ValueError):
Range1d(1, 2, 3)
def test_with_max_bound_smaller_than_min_bounded_raises_valueerror(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_with_max_bound_smaller_than_min_bounded_raises_valueerror(self):
with pytest.raises(ValueError):
Range1d(1, 2, bounds=(1, 0))
with pytest.raises(ValueError):
Range1d(1, 2, bounds=[1, 0])
def test_bounds_with_text_rejected_as_the_correct_value_error(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_bounds_with_text_rejected_as_the_correct_value_error(self):
with pytest.raises(ValueError) as e:
Range1d(1, 2, bounds="21") # The string is indexable, so this may not fail properly
assert e.value.args[0].startswith('expected an element of either')
def test_bounds_with_three_item_tuple_raises_valueerror(self):
3
View Source File : test_ranges.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_init_with_bad_bounds(self):
with pytest.raises(ValueError):
DataRange1d(1, 2, bounds=(1, 0))
with pytest.raises(ValueError):
DataRange1d(1, 2, bounds=[1, 0])
with pytest.raises(ValueError):
Range1d(1, 2, bounds="21")
class Test_FactorRange(object):
0
View Source File : calendar.py
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
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()
start = dt.date(start.year, 1, 1)
finish = dt.date(finish.year + 1, 1, 1) - dt.timedelta(days=1)
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
@staticmethod
0
View Source File : draw.py
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
def circuit_from(bqm):
G = bqm.to_networkx_graph()
plot = Plot(
plot_width=600, plot_height=400, x_range=Range1d(-0.1, 1.1), y_range=Range1d(-0.1, 1.1)
)
plot.title.text = "Multiplication as a BQM"
plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
graph_renderer = from_networkx(G, circuit_layout)
circle_size = 25
graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="#F5F7FB")
graph_renderer.node_renderer.selection_glyph = Circle(size=circle_size, fill_color="#EEA64E")
graph_renderer.node_renderer.hover_glyph = Circle(size=circle_size, fill_color="#FFE86C")
edge_size = 2
graph_renderer.edge_renderer.glyph = MultiLine(
line_color="#CCCCCC", line_alpha=0.8, line_width=edge_size
)
graph_renderer.edge_renderer.selection_glyph = MultiLine(
line_color="#EEA64E", line_width=edge_size
)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="#FFE86C", line_width=edge_size)
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph_renderer)
plot.background_fill_color = "#202239"
add_labels(plot)
show(Row(plot))
def frequency_of(results):
0
View Source File : draw.py
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
def draw(S, position=None, with_labels=False):
"""Plot the given signed social network.
Args:
S: The network
position (dict, optional):
The position for the nodes. If no position is provided, a layout will be calculated. If the nodes have
'color' attributes, a Kamanda-Kawai layout will be used to group nodes of the same color together.
Otherwise, a circular layout will be used.
Returns:
A dictionary of positions keyed by node.
Examples:
>>> import dwave_structural_imbalance_demo as sbdemo
>>> gssn = sbdemo.GlobalSignedSocialNetwork()
>>> nld_before = gssn.get_node_link_data('Syria', 2013)
>>> nld_after = gssn.solve_structural_imbalance('Syria', 2013)
# draw Global graph before solving; save node layout for reuse
>>> position = sbdemo.draw('syria.png', nld_before)
# draw the Global graph; reusing the above layout, and calculating a new grouped layout
>>> sbdemo.draw('syria_imbalance.png', nld_after, position)
>>> sbdemo.draw('syria_imbalance_grouped', nld_after)
"""
# we need a consistent ordering of the edges
edgelist = S.edges()
nodelist = S.nodes()
def layout_wrapper(S):
pos = position
if pos is None:
try:
# group bipartition if nodes are colored
dist = defaultdict(dict)
for u, v in product(nodelist, repeat=2):
if u == v: # node has no distance from itself
dist[u][v] = 0
elif (
nodelist[u]["color"] == nodelist[v]["color"]
): # make same color nodes closer together
dist[u][v] = 1
else: # make different color nodes further apart
dist[u][v] = 2
pos = nx.kamada_kawai_layout(S, dist)
except KeyError:
# default to circular layout if nodes aren't colored
pos = nx.circular_layout(S)
return pos
# call layout wrapper once with all nodes to store position for calls with partial graph
position = layout_wrapper(S)
plot = Plot(
plot_width=600, plot_height=400, x_range=Range1d(-1.2, 1.2), y_range=Range1d(-1.2, 1.2)
)
tools = [WheelZoomTool(), ZoomInTool(), ZoomOutTool(), PanTool()]
plot.add_tools(*tools)
plot.toolbar.active_scroll = tools[0]
def get_graph_renderer(S, line_dash):
# we need a consistent ordering of the edges
edgelist = S.edges()
nodelist = S.nodes()
# get the colors assigned to each edge based on friendly/hostile
sign_edge_color = ["#87DACD" if S[u][v]["sign"] == 1 else "#FC9291" for u, v in edgelist]
# get the colors assigned to each node by coloring
try:
coloring_node_color = [
"#4378F8" if nodelist[v]["color"] else "#FFE897" for v in nodelist
]
except KeyError:
coloring_node_color = ["#FFFFFF" for __ in nodelist]
graph_renderer = from_networkx(S, layout_wrapper)
circle_size = 10
graph_renderer.node_renderer.data_source.add(coloring_node_color, "color")
graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="color")
edge_size = 2
graph_renderer.edge_renderer.data_source.add(sign_edge_color, "color")
try:
graph_renderer.edge_renderer.data_source.add(
[S[u][v]["event_year"] for u, v in edgelist], "event_year"
)
graph_renderer.edge_renderer.data_source.add(
[S[u][v]["event_description"] for u, v in edgelist], "event_description"
)
plot.add_tools(
HoverTool(
tooltips=[("Year", "@event_year"), ("Description", "@event_description")],
line_policy="interp",
)
)
except KeyError:
pass
graph_renderer.edge_renderer.glyph = MultiLine(line_color="color", line_dash=line_dash)
graph_renderer.inspection_policy = EdgesAndLinkedNodes()
return graph_renderer
try:
S_dash = S.edge_subgraph(((u, v) for u, v in edgelist if S[u][v]["frustrated"]))
S_solid = S.edge_subgraph(((u, v) for u, v in edgelist if not S[u][v]["frustrated"]))
plot.renderers.append(get_graph_renderer(S_dash, "dashed"))
plot.renderers.append(get_graph_renderer(S_solid, "solid"))
except KeyError:
plot.renderers.append(get_graph_renderer(S, "solid"))
plot.background_fill_color = "#202239"
positions = layout_wrapper(S)
if with_labels:
data = {"xpos": [], "ypos": [], "label": []}
for label, pos in positions.items():
data["label"].append(label)
data["xpos"].append(pos[0])
data["ypos"].append(pos[1])
labels = LabelSet(
x="xpos",
y="ypos",
text="label",
level="glyph",
source=ColumnDataSource(data),
x_offset=-5,
y_offset=10,
text_color="#F5F7FB",
text_font_size="12pt",
)
plot.add_layout(labels)
show(Row(plot))
return positions
0
View Source File : bokeh_plot.py
License : GNU General Public License v3.0
Project Creator : barricklab
License : GNU General Public License v3.0
Project Creator : barricklab
def get_bokeh(df, linear = False):
#df = df.fillna("")
X=0
Y=0
TOOLTIPS=' < font size="3"> < b>@Feature < /b> — @Type @pi_permatch_int < /font> < br> @Description'
hover = HoverTool(names=["features"])
plotSize=.35
plotDimen=800
x_range = Range1d(-plotSize, plotSize, bounds=(-.5, .5), min_interval=.1)
y_range = Range1d(-plotSize, plotSize, bounds=(-.5, .5), min_interval=.1)
toolbar = None
p = figure(plot_height=plotDimen,plot_width=plotDimen, title="",
toolbar_location=toolbar, toolbar_sticky=False, match_aspect=True,
sizing_mode='scale_width', tools=['save',hover,'pan'], tooltips=TOOLTIPS,
#x_range=(-plotSize, plotSize), y_range=(-plotSize, plotSize))
x_range=x_range, y_range=y_range)
p.toolbar.logo = None
p.add_tools(WheelZoomTool(zoom_on_axis=False))
p.toolbar.active_scroll = p.select_one(WheelZoomTool)
#backbone line
p.circle(x=X, y=Y, radius=baseRadius, line_color="#000000", fill_color=None, line_width=2.5)
df = calc_level(df)
if linear:
line_length = baseRadius / 5
p.line([0,0], [baseRadius - line_length, baseRadius + line_length],
line_width = 4, level="overlay", line_color = "black")
df['pi_permatch_int']=df['pi_permatch'].astype('int')
df['pi_permatch_int'] = df['pi_permatch_int'].astype(str) + "%"
df.loc[df['db'] == "Rfam", 'pi_permatch_int'] = "" #removes percent from infernal hits
df['rstart']=((df["qstart"]/df["qlen"])*2*pi)
df['rend'] =((df["qend"]/df["qlen"])*2*pi)
df['rstart'] = np.where(df['rstart'] < 0, df['rstart'] + (2*pi), df['rstart'])
df['rend'] = np.where(df['rend'] < 0, df['rend'] + (2*pi), df['rend'])
df['rend'] = np.where(df['rend'] < df['rstart'], df['rend'] + (2*pi), df['rend'])
df['Type'] = df['Type'].str.replace('rep_origin','origin of replication')
#DDE0BD
#C97064
#C9E4CA
fullColorDf=pd.read_csv(rsc.get_resource("data", "colors.csv"),index_col=0)
fragColorDf=fullColorDf.copy()
fragColorDf[['fill_color','line_color']]=fragColorDf[['line_color','fill_color']]
fragColorDf["fill_color"]="#ffffff"
full=df[df["fragment"]==False]
full=full.merge(fullColorDf,how = "left",on=["Type"])
full['legend'] = full['Type']
full=full.fillna({"color":"grey","fill_color":"#808080","line_color":"#000000"})
frag=df[df["fragment"]==True]
frag=frag.merge(fragColorDf,how = "left",on=["Type"])
frag=frag.fillna({"color":"grey","fill_color":"#ffffff","line_color":"#808080"})
df=full.append(frag).reset_index(drop=True)#.set_index('Feature')
# add orientation column
orient = pd.read_csv(rsc.get_resource("data", "feature_orientation.csv"),header=None, names = ["Type","has_orientation"])
orient['Type'] = orient['Type']
orient['has_orientation'] = orient['has_orientation'].map({"T":True})
df = df.merge(orient, on="Type", how = "left")
df['Type'] = df['Type'].str.replace("_"," ")
df['has_orientation'] = df['has_orientation'].fillna(value=False)
df[['x','y',"Lx1","Ly1","annoLineColor","lineX","lineY","theta","text_align"]]=df.apply(calc_glyphs,axis=1)
df['legend'] = df['Type']
#allowedTypes = ['CDS',"promoter","origin of replication","swissprot"]
allowedTypes = fullColorDf['Type']
mask = ~df['legend'].isin(allowedTypes)
df.loc[mask, 'legend'] = 'misc feature'
#plot annotations
source = ColumnDataSource(df)
p.patches('x', 'y', fill_color='fill_color', line_color='line_color',
name="features", line_width=2.5, source=source, legend_group = "legend")
p.multi_line(xs="lineX", ys="lineY", line_color="annoLineColor", line_width=3,
level="overlay",line_cap='round',alpha=.5, source=source)
#`text_align` cannot read from `source` -- have to do this workaround
right=ColumnDataSource(df[df['text_align']=='right'])
left=ColumnDataSource(df[df['text_align']=='left'])
bCenter=ColumnDataSource(df[df['text_align']=='b_center'])
tCenter=ColumnDataSource(df[df['text_align']=='t_center'])
text_level = 'overlay'
p.text(x="Lx1", y="Ly1",name="2",x_offset=3,y_offset=8, text_align="left",
text='Feature', level=text_level, source=right)
p.text(x="Lx1", y="Ly1",name="2",x_offset=-5,y_offset=8, text_align="right",
text='Feature', level=text_level, source=left)
p.text(x="Lx1", y="Ly1",name="2",x_offset=0,y_offset=15, text_align="center",
text='Feature', level=text_level, source=bCenter)
p.text(x="Lx1", y="Ly1",name="2",x_offset=0,y_offset=0, text_align="center",
text='Feature', level=text_level, source=tCenter)
#calculate chunk size(s) for drawing lines
plasLen = df.iloc[0]['qlen']
ticks = calc_num_markers(plasLen)
ticks_cds = ColumnDataSource(ticks)
p.multi_line(xs="lineX", ys="lineY", line_color="black", line_width=2,
level="underlay", line_cap='round', alpha = .5, source = ticks_cds)
right=ColumnDataSource(ticks[ticks['text_align']=='right'])
left=ColumnDataSource(ticks[ticks['text_align']=='left'])
bCenter=ColumnDataSource(ticks[ticks['text_align']=='b_center'])
tCenter=ColumnDataSource(ticks[ticks['text_align']=='t_center'])
p.text(x="Lx1", y="Ly1",name="2",x_offset=3,y_offset=6, text_align="left",
text='bp', alpha = .5, text_font_size = 'size',level=text_level, source=right)
p.text(x="Lx1", y="Ly1",name="2",x_offset=-5,y_offset=6, text_align="right",
text='bp', alpha = .5, text_font_size = 'size',level=text_level, source=left)
p.text(x="Lx1", y="Ly1",name="2",x_offset=0,y_offset=15, text_align="center",
text='bp', alpha = .5, text_font_size = 'size',level=text_level, source=bCenter)
p.text(x="Lx1", y="Ly1",name="2",x_offset=0,y_offset=-3, text_align="center",
text='bp', alpha = .5, text_font_size = 'size', level=text_level, source=tCenter)
p.add_layout(Label(x=0, y=0,name="2",x_offset=0,y_offset=-8, text_align="center",
text=f"{plasLen} bp", text_color = "#7b7b7b", text_font_size = '16px', level=text_level))
p.axis.axis_label=None
p.axis.visible=False
p.grid.grid_line_color = "#EFEFEF"
p.outline_line_color = "#DDDDDD"
p.legend.location = 'bottom_left'
p.legend.border_line_color = "#EFEFEF"
p.legend.visible = True
#st.write(df)
return p
0
View Source File : plotting.py
License : BSD 3-Clause "New" or "Revised" License
Project Creator : BuildACell
License : BSD 3-Clause "New" or "Revised" License
Project Creator : BuildACell
def graphPlot(DG,DGspecies,DGreactions,plot,layout="force",positions=None,plot_species = True, plot_reactions = True, plot_edges = True, plot_arrows = True,\
species_glyph_size = 12, reaction_glyph_size = 8, posscale = 1.0,layoutfunc=None,iterations=2000,rseed=30,show_species_images=False):
"""given a directed graph, plot it!
Inputs:
DG: a directed graph of type DiGraph
DGspecies: a directed graph which only contains the species nodes
DGreactions: a directed graph which only contains the reaction nodes
plot: a bokeh plot object
layout: graph layout function.
'force' uses fa2 to push nodes apart
'circle' plots the nodes and reactions in two overlapping circles, with the reactions on the inside of the circle
'custom' allows user input "layoutfunc". Internally, layoutfunc is passed the three inputs (DG, DGspecies, DGreactions)
and should output a position dictionary with node { < node number>:(x,y)}
positions: a dictionary of node names and x,y positions. this gets passed into the layout function
posscale: multiply the scaling of the plot. This only affects the arrows because the arrows are a hack :("""
random.seed(rseed)
if(not PLOT_NETWORK):
warn("network plotting disabled because some libraries are not found")
return
if(layout == "force"):
# below are parameters for the force directed graph visualization
forceatlas2 = ForceAtlas2(
# Behavior alternatives
outboundAttractionDistribution=True, # Dissuade hubs
linLogMode=False, # NOT IMPLEMENTED
# Prevent overlap (NOT IMPLEMENTED)
adjustSizes=False,
edgeWeightInfluence=1.0,
# Performance
jitterTolerance=1.0, # Tolerance
barnesHutOptimize=True,
barnesHutTheta=1.2,
multiThreaded=False, # NOT IMPLEMENTED
# Tuning
scalingRatio=2.4*posscale,
strongGravityMode=False,
gravity=1.0,
# Log
verbose=False)
positions = forceatlas2.forceatlas2_networkx_layout(
DG, pos=positions, iterations=iterations)
elif(layout == "circle"):
positions = nx.circular_layout(DGspecies, scale=50*posscale)
positions.update(nx.circular_layout(DGreactions, scale=35*posscale))
elif(layout == "custom"):
positions = layoutfunc(DG, DGspecies, DGreactions)
reaction_renderer = from_networkx(DGreactions, positions, center=(0, 0))
species_renderer = from_networkx(DGspecies, positions, center=(0, 0))
edges_renderer = from_networkx(DG, positions, center=(0, 0))
#Set xbounds and ybounds:
xbounds = [0, 0]
ybounds = [0, 0]
for n in positions:
xbounds[0] = min([xbounds[0], positions[n][0]])
xbounds[1] = max([xbounds[1], positions[n][0]])
ybounds[0] = min([ybounds[0], positions[n][1]])
ybounds[1] = max([ybounds[1], positions[n][1]])
max_glyph = max([reaction_glyph_size, species_glyph_size])
xbounds[0] -= max_glyph
xbounds[1] += max_glyph
ybounds[0] -= max_glyph
ybounds[1] += max_glyph
# edges
edges_renderer.node_renderer.glyph = Circle(
size=species_glyph_size, line_alpha=0, fill_alpha=0, fill_color="color")
edges_renderer.edge_renderer.glyph = MultiLine(
line_alpha=0.2, line_width=4, line_join="round", line_color="color")
edges_renderer.edge_renderer.selection_glyph = MultiLine(
line_color=Spectral4[2], line_width=5, line_join="round")
edges_renderer.edge_renderer.hover_glyph = MultiLine(
line_color=Spectral4[1], line_width=5, line_join="round")
if plot_arrows:
xbounds_a, ybounds_a = makeArrows2(
edges_renderer, DG, positions, headsize=5) # make the arrows!
xbounds[0] = min([xbounds[0], xbounds_a[0]])
xbounds[1] = max([xbounds[1], xbounds_a[1]])
ybounds[0] = min([ybounds[0], ybounds_a[0]])
ybounds[1] = max([ybounds[1], ybounds_a[1]])
# we want to find the middle of the graph and plot a square that is 1:1 aspect ratio
# find the midpoint of the graph
xmid = statistics.mean(xbounds)
ymid = statistics.mean(ybounds)
# now, subtract the middle from the edges
xmiddlized = [a-xmid for a in xbounds]
ymiddlized = [a-ymid for a in ybounds]
# now, find the biggest dimension
absdim = max([abs(a) for a in xmiddlized+ymiddlized])
xlim = [xmid-absdim*1.05, xmid + absdim*1.05]
ylim = [ymid-absdim*1.05, ymid + absdim*1.05]
# now set it on the plot!
plot.x_range = Range1d(xlim[0], xlim[1])
plot.y_range = Range1d(ylim[0], ylim[1])
# reactions
reaction_renderer.node_renderer.glyph = Square(
size=reaction_glyph_size, fill_color="color")
reaction_renderer.node_renderer.selection_glyph = Square(
size=reaction_glyph_size, fill_color=Spectral4[2])
reaction_renderer.node_renderer.hover_glyph = Square(
size=reaction_glyph_size, fill_color=Spectral4[1])
# nodes
species_renderer.node_renderer.glyph = Circle(size=12, fill_color="color")
species_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
species_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])
#this part adds the interactive elements that make it so that the lines are highlighted
#when you mouse over and click
edge_hover_tool = HoverTool(tooltips= None,renderers=[edges_renderer])
if( not show_species_images):
species_hover_tool = HoverTool(tooltips=[("name", "@species"), ("type", "@type")],\
renderers=[species_renderer],attachment="right")
else:
species_hover_tool = HoverTool(tooltips=' < div> < div> < img src="data:image/png;base64,@image" style="float: left; margin: 0px 0px 0px 0px;"> < /img> < /div> < /div>',\
renderers=[species_renderer],attachment="right")
rxn_hover_tool = HoverTool(tooltips=[("reaction", "@species"), ("type", "@type"),("k_f","@k"),("k_r","@k_r")],\
renderers=[reaction_renderer],attachment="right")
plot.add_tools(edge_hover_tool,species_hover_tool,rxn_hover_tool, TapTool(), BoxSelectTool(),PanTool(),WheelZoomTool())
edges_renderer.selection_policy = NodesAndLinkedEdges()
edges_renderer.inspection_policy = EdgesAndLinkedNodes()
if plot_edges:
plot.renderers.append(edges_renderer)
if plot_reactions:
plot.renderers.append(reaction_renderer)
if plot_species:
plot.renderers.append(species_renderer)
def generate_networkx_graph(CRN,useweights=False,use_pretty_print=False,pp_show_material=True,
0
View Source File : visual_midi.py
License : MIT License
Project Creator : dubreuia
License : MIT License
Project Creator : dubreuia
def plot(self, pm: PrettyMIDI):
"""
Plots the pretty midi object as a plot object.
:param pm: the PrettyMIDI instance to plot
:return: the bokeh plot layout
"""
preset = self._preset
# Calculates the QPM from the MIDI file, might raise exception if confused
qpm = self._get_qpm(pm)
# Initialize the tools, those are present on the right hand side
plot = bokeh.plotting.figure(
tools="reset,hover,save,wheel_zoom,pan",
toolbar_location=preset.toolbar_location)
# Setup the hover and the data dict for bokeh,
# each property must match a property in the data dict
plot.select(dict(type=bokeh.models.HoverTool)).tooltips = ({
"program": "@program",
"pitch": "@top",
"velocity": "@velocity",
"duration": "@duration",
"start_time": "@left",
"end_time": "@right"})
data = dict(
program=[],
top=[],
bottom=[],
left=[],
right=[],
duration=[],
velocity=[],
color=[])
# Puts the notes in the dict for bokeh and saves first
# and last note time, bigger and smaller pitch
pitch_min = None
pitch_max = None
first_note_start = None
last_note_end = None
index_instrument = 0
for instrument in pm.instruments:
for note in instrument.notes:
pitch_min = min(pitch_min or self._MAX_PITCH, note.pitch)
pitch_max = max(pitch_max or self._MIN_PITCH, note.pitch)
color = self._get_color(index_instrument, note)
note_start = note.start
note_end = note.start + (note.end - note.start)
data["program"].append(instrument.program)
data["top"].append(note.pitch)
if self._show_velocity:
data["bottom"].append(note.pitch + (note.velocity / 127))
else:
data["bottom"].append(note.pitch + 1)
data["left"].append(note_start)
data["right"].append(note_end)
data["duration"].append(note_end - note_start)
data["velocity"].append(note.velocity)
data["color"].append(color)
first_note_start = min(first_note_start or sys.maxsize, note_start)
last_note_end = max(last_note_end or 0, note_end)
index_instrument = index_instrument + 1
# Shows an empty plot even if there are no notes
if first_note_start is None or last_note_end is None or pitch_min is None or pitch_max is None:
pitch_min = self._MIN_PITCH
pitch_max = pitch_min + 5
first_note_start = 0
last_note_end = 0
# Gets the pitch range (min, max) from either the provided arguments
# or min and max values from the notes
if self._plot_pitch_range_start is not None:
pitch_min = self._plot_pitch_range_start
else:
pitch_min = min(self._MAX_PITCH, pitch_min)
if self._plot_pitch_range_stop is not None:
pitch_max = self._plot_pitch_range_stop
else:
pitch_max = max(self._MIN_PITCH, pitch_max)
pitch_range = pitch_max + 1 - pitch_min
# Draws the rectangles on the plot from the data
source = ColumnDataSource(data=data)
plot.quad(left="left",
right="right",
top="top",
bottom="bottom",
line_alpha=1,
line_color="black",
color="color",
source=source)
# Draws the y grid by hand, because the grid has label on the ticks, but
# for a plot like this, the labels needs to fit in between the ticks.
# Also useful to change the background of the grid each line
for pitch in range(pitch_min, pitch_max + 1):
# Draws the background box and contours, on the underlay layer, so
# that the rectangles and over the box annotations
fill_alpha = (0.15 if pitch % 2 == 0 else 0.00)
box = BoxAnnotation(bottom=pitch,
top=pitch + 1,
fill_color="gray",
fill_alpha=fill_alpha,
line_color="black",
line_alpha=0.3,
line_width=1,
level="underlay")
plot.add_layout(box)
label = Label(
x=preset.label_y_axis_offset_x,
y=pitch + preset.label_y_axis_offset_y,
x_units="screen",
text=str(pitch),
render_mode="css",
text_font_size=preset.label_text_font_size,
text_font_style=preset.label_text_font_style)
plot.add_layout(label)
# Gets the time signature from pretty midi, or 4/4 if none
if self._midi_time_signature:
numerator, denominator = self._midi_time_signature.split("/")
time_signature = TimeSignature(int(numerator), int(denominator), 0)
else:
if pm.time_signature_changes:
if len(pm.time_signature_changes) > 1:
raise Exception("Multiple time signatures are not supported")
time_signature = pm.time_signature_changes[0]
else:
time_signature = TimeSignature(4, 4, 0)
# Gets seconds per bar and seconds per beat
if len(pm.get_beats()) >= 2:
seconds_per_beat = pm.get_beats()[1] - pm.get_beats()[0]
else:
seconds_per_beat = 0.5
if len(pm.get_downbeats()) >= 2:
seconds_per_bar = pm.get_downbeats()[1] - pm.get_downbeats()[0]
else:
seconds_per_bar = 2.0
# Defines the end time of the plot in seconds
if self._plot_bar_range_stop is not None:
plot_end_time = self._plot_bar_range_stop * seconds_per_bar
else:
# Calculates the plot start and end time, the start time can start after
# notes or truncate notes if the plot is too long (we left truncate the
# plot with the bounds)
# The plot start and plot end are a multiple of seconds per bar (closest
# smaller value for the start time, closest higher value for the end time)
plot_end_time = int((last_note_end) / seconds_per_bar) * seconds_per_bar
# If the last note end is exactly on a multiple of seconds per bar,
# we don't start a new one
is_on_bar = math.isclose(last_note_end % seconds_per_bar, seconds_per_bar)
is_on_bar_exact = math.isclose(last_note_end % seconds_per_bar, 0.0)
if not is_on_bar and not is_on_bar_exact:
plot_end_time += seconds_per_bar
# Defines the start time of the plot in seconds
if self._plot_bar_range_start is not None:
plot_start_time = self._plot_bar_range_start * seconds_per_bar
else:
start_time = int(first_note_start / seconds_per_bar) * seconds_per_bar
plot_max_length_time = self._plot_max_length_bar * seconds_per_bar
plot_start_time = max(plot_end_time - plot_max_length_time, start_time)
# Draws the vertical bar grid, with a different background color
# for each bar
if preset.show_bar:
bar_count = 0
for bar_time in pm.get_downbeats():
fill_alpha_index = bar_count % len(self._bar_fill_alphas)
fill_alpha = self._bar_fill_alphas[fill_alpha_index]
box = BoxAnnotation(left=bar_time,
right=bar_time + seconds_per_bar,
fill_color="gray",
fill_alpha=fill_alpha,
line_color="black",
line_width=2,
line_alpha=0.5,
level="underlay")
plot.add_layout(box)
bar_count += 1
# Draws the vertical beat grid, those are only grid lines
if preset.show_beat:
for beat_time in pm.get_beats():
box = BoxAnnotation(left=beat_time,
right=beat_time + seconds_per_beat,
fill_color=None,
line_color="black",
line_width=1,
line_alpha=0.4,
level="underlay")
plot.add_layout(box)
# Configure x axis
plot.xaxis.bounds = (plot_start_time, plot_end_time)
plot.xaxis.axis_label = "time (SEC)"
plot.xaxis.axis_label_text_font_size = preset.axis_label_text_font_size
plot.xaxis.ticker = bokeh.models.SingleIntervalTicker(interval=1)
plot.xaxis.major_tick_line_alpha = 0.9
plot.xaxis.major_tick_line_width = 1
plot.xaxis.major_tick_out = preset.axis_x_major_tick_out
plot.xaxis.minor_tick_line_alpha = 0
plot.xaxis.major_label_text_font_size = preset.label_text_font_size
plot.xaxis.major_label_text_font_style = preset.label_text_font_style
# Configure y axis
plot.yaxis.bounds = (pitch_min, pitch_max + 1)
plot.yaxis.axis_label = "pitch (MIDI)"
plot.yaxis.axis_label_text_font_size = preset.axis_label_text_font_size
plot.yaxis.ticker = bokeh.models.SingleIntervalTicker(interval=1)
plot.yaxis.major_label_text_alpha = 0
plot.yaxis.major_tick_line_alpha = 0.9
plot.yaxis.major_tick_line_width = 1
plot.yaxis.major_tick_out = preset.axis_y_major_tick_out
plot.yaxis.minor_tick_line_alpha = 0
plot.yaxis.axis_label_standoff = preset.axis_y_label_standoff
plot.outline_line_width = 1
plot.outline_line_alpha = 1
plot.outline_line_color = "black"
# The x grid is deactivated because is draw by hand (see x grid code)
plot.xgrid.grid_line_color = None
# The y grid is deactivated because is draw by hand (see y grid code)
plot.ygrid.grid_line_color = None
# Configure the plot size and range
if self._plot_title is None:
plot_title_text = "Visual MIDI (%s QPM, %s/%s)" % (
str(int(qpm)), time_signature.numerator, time_signature.denominator)
else:
plot_title_text = self._plot_title
plot.title = Title(text=plot_title_text,
text_font_size=preset.title_text_font_size)
plot.plot_width = preset.plot_width
if preset.row_height:
plot.plot_height = pitch_range * preset.row_height
else:
plot.plot_height = preset.plot_height
plot.x_range = Range1d(plot_start_time, plot_end_time)
plot.y_range = Range1d(pitch_min, pitch_max + 1)
plot.min_border_right = 50
if self._live_reload and preset.stop_live_reload_button:
callback = CustomJS(code="clearInterval(liveReloadInterval)")
button = Button(label="stop live reload")
button.js_on_click(callback)
layout = column(button, plot)
else:
layout = column(plot)
return layout
def save(self, pm: PrettyMIDI, filepath: str):
0
View Source File : detfl_monod.py
License : Apache License 2.0
Project Creator : EPFL-LCSB
License : Apache License 2.0
Project Creator : EPFL-LCSB
def plot_growth(p,t,time_data):
plot_var(p,t,time_data, 'X', color='black')
p.yaxis.axis_label = "Cell concentration $[g.L^{-1}]$"
p.y_range.start = 0.9 * time_data.loc['X'].min()
p.y_range.end = 1.09 * time_data.loc['X'].max()
# Setting the second y axis range name and range
p.extra_y_ranges = {"mu": Range1d()}
# Adding the second axis to the plot.
p.add_layout(LinearAxis(y_range_name="mu",
axis_label='growth rate $[h^{-1}]$'), 'right')
plot_var(p,t,time_data, 'mu', color='gray', y_range_name='mu')
return p
def plot_dynamics(model, time_data):
0
View Source File : plotting.py
License : Apache License 2.0
Project Creator : EPFL-LCSB
License : Apache License 2.0
Project Creator : EPFL-LCSB
def make_growth_plot(model,time_data):
t = time_data.loc['t']
y1 = time_data.loc['X']
y2 = time_data.loc['mu']
p = bp.figure(width=1000)
p.title.text = 'Growth, Cell concentration over time'
p.line(t,y1, color='black', line_width=LINE_WIDTH)
p.y_range.start = -0.05 * y1.min()
p.y_range.end = 1.05 * y1.max()
# Setting the second y axis range name and range
p.extra_y_ranges = {"mu": Range1d(start=-0.05*y2.min(), end = 1.05*y2.max())}
# Adding the second axis to the plot.
p.add_layout(LinearAxis(y_range_name="mu",
axis_label='growth rate $[h^{-1}]$'), 'right')
p.line(t,y2, color='grey', line_width=LINE_WIDTH,
line_dash = 'dashed', y_range_name='mu')
p.xaxis.major_label_text_font_size = AXIS_FONT_SIZE
p.yaxis.major_label_text_font_size = AXIS_FONT_SIZE
# p.legend.label_text_font_size = LEGEND_FONT_SIZE
return p
def get_y(the_var, time_data):
0
View Source File : tsne.py
License : MIT License
Project Creator : evidence-surveillance
License : MIT License
Project Creator : evidence-surveillance
def test_bokeh(matrices):
p = figure(plot_width=550, plot_height=550)
xlim = (-69.551894338989271, 64.381507070922851)
ylim = (-70.038440855407714, 70.644477995300306)
p.axis.visible = False
p.border_fill_color = None
p.outline_line_color = None
p.grid.visible = None
p.toolbar.logo = None
p.toolbar_location = None
p.x_range = Range1d(start=xlim[0],end =xlim[1])
p.y_range = Range1d(start=ylim[0],end =ylim[1])
# p.image_url(url=['color_scatter.png'], x=0, y=0, w=None, h=None, anchor="center")
p.image_url(url=['static/images/tsne'+LATEST_DATE+'_sml.png'], x=xlim[0]-2.0, y=ylim[1], w=ylim[1]-ylim[0]-2.7, h=(xlim[1]-xlim[0])+6.7, anchor="top_left")
for i, matrix in enumerate(matrices):
if len(matrix['score']) > 0:
p.scatter(matrix['vectors'][:, 0], matrix['vectors'][:, 1],
fill_color='#fc6e2d', fill_alpha=0.8,
line_color=None, size=2)
else:
p.scatter(matrix['vectors'][:, 0], matrix['vectors'][:, 1],
fill_color='#5f4af9', fill_alpha=0.8,
line_color=None, size=2.5)
# export_png(p, filename='color_scatter.png')
# output_file("color_scatter.html", title="color_scatter.py example")
comp = components(p)
return comp[0]+comp[1]
# return file_html(p, CDN)
# save(p)
if __name__ == "__main__":
0
View Source File : viz.py
License : MIT License
Project Creator : fancompute
License : MIT License
Project Creator : fancompute
def _plot_twinx_bokeh(plot, _):
"""Hook to plot data on a secondary (twin) axis on a Holoviews Plot with Bokeh backend.
Args:
plot: Holoviews plot object to hook for twinx
See Also:
The code was copied from a comment in https://github.com/holoviz/holoviews/issues/396.
- http://holoviews.org/user_guide/Customizing_Plots.html#plot-hooks
- https://docs.bokeh.org/en/latest/docs/user_guide/plotting.html#twin-axes
"""
fig: Figure = plot.state
glyph_first: GlyphRenderer = fig.renderers[0] # will be the original plot
glyph_last: GlyphRenderer = fig.renderers[-1] # will be the new plot
right_axis_name = "twiny"
# Create both axes if right axis does not exist
if right_axis_name not in fig.extra_y_ranges.keys():
# Recreate primary axis (left)
y_first_name = glyph_first.glyph.y
y_first_min = glyph_first.data_source.data[y_first_name].min()
y_first_max = glyph_first.data_source.data[y_first_name].max()
y_first_offset = (y_first_max - y_first_min) * 0.1
fig.y_range = Range1d(
start=y_first_min - y_first_offset,
end=y_first_max + y_first_offset
)
fig.y_range.name = glyph_first.y_range_name
# Create secondary axis (right)
y_last_name = glyph_last.glyph.y
y_last_min = glyph_last.data_source.data[y_last_name].min()
y_last_max = glyph_last.data_source.data[y_last_name].max()
y_last_offset = (y_last_max - y_last_min) * 0.1
fig.extra_y_ranges = {right_axis_name: Range1d(
start=y_last_min - y_last_offset,
end=y_last_max + y_last_offset
)}
fig.add_layout(LinearAxis(y_range_name=right_axis_name, axis_label=glyph_last.glyph.y), "right")
# Set right axis for the last glyph added to the figure
glyph_last.y_range_name = right_axis_name
def get_extent_2d(shape, spacing: Optional[float] = None):
0
View Source File : plotting.py
License : BSD 3-Clause "New" or "Revised" License
Project Creator : FeatureLabs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : FeatureLabs
def _modify_plot(plot, figargs):
'''Add text and modify figure attributes. This is an internal
function which allows for figure attributes to be passed into
interactive functions.
Args:
plot (bokeh.figure): The figure to modify
figargs (dict[assorted]): A dictionary of width, height,
title, x_axis, y_axis, x_range and y_range.
'''
if figargs['width'] is not None:
plot.width = figargs['width']
if figargs['height'] is not None:
plot.height = figargs['height']
if figargs['title'] is not None:
plot.title.text = figargs['title']
if figargs['x_axis'] is not None:
plot.xaxis.axis_label = figargs['x_axis']
if figargs['y_axis'] is not None:
plot.yaxis.axis_label = figargs['y_axis']
if figargs['x_range'] is not None:
plot.x_range = Range1d(figargs['x_range'][0], figargs['x_range'][1])
if figargs['y_range'] is not None:
plot.y_range = Range1d(figargs['y_range'][0], figargs['y_range'][1])
return plot
def show(plot, png=False, static=False, hover=True,
0
View Source File : plotting.py
License : BSD 3-Clause "New" or "Revised" License
Project Creator : FeatureLabs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : FeatureLabs
def dendrogram(D, figargs=None):
'''Creates a dendrogram plot.
This plot can show full structure of a given dendrogram.
Args:
D (henchman.selection.Dendrogram): An initialized dendrogram object
Examples:
>>> from henchman.selection import Dendrogram
>>> from henchman.plotting import show
>>> import henchman.plotting as hplot
>>> D = Dendrogram(X)
>>> plot = hplot.dendrogram(D)
>>> show(plot)
'''
if figargs is None:
return lambda figargs: dendrogram(D, figargs=figargs)
G = nx.Graph()
vertices_source = ColumnDataSource(
pd.DataFrame({'index': D.columns.keys(),
'desc': list(D.columns.values())}))
edges_source = ColumnDataSource(
pd.DataFrame(D.edges[0]).rename(
columns={1: 'end', 0: 'start'}))
step_source = ColumnDataSource(
pd.DataFrame({'step': [0],
'thresh': [D.threshlist[0]],
'components': [len(D.graphs[0])]}))
G.add_nodes_from([str(x) for x in vertices_source.data['index']])
G.add_edges_from(zip(
[str(x) for x in edges_source.data['start']],
[str(x) for x in edges_source.data['end']]))
graph_renderer = from_networkx(G, nx.circular_layout,
scale=1, center=(0, 0))
graph_renderer.node_renderer.data_source = vertices_source
graph_renderer.node_renderer.view = CDSView(source=vertices_source)
graph_renderer.edge_renderer.data_source = edges_source
graph_renderer.edge_renderer.view = CDSView(source=edges_source)
plot = Plot(plot_width=400, plot_height=400,
x_range=Range1d(-1.1, 1.1),
y_range=Range1d(-1.1, 1.1))
plot.title.text = "Feature Connectivity"
graph_renderer.node_renderer.glyph = Circle(
size=5, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(
size=15, fill_color=Spectral4[2])
graph_renderer.edge_renderer.data_source = edges_source
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
line_alpha=0.6,
line_width=.5)
graph_renderer.edge_renderer.selection_glyph = MultiLine(
line_color=Spectral4[2],
line_width=3)
graph_renderer.node_renderer.hover_glyph = Circle(
size=5,
fill_color=Spectral4[1])
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph_renderer)
plot.add_tools(
HoverTool(tooltips=[("feature", "@desc"),
("index", "@index"), ]),
TapTool(),
BoxZoomTool(),
SaveTool(),
ResetTool())
plot = _modify_plot(plot, figargs)
if figargs['static']:
return plot
def modify_doc(doc, D, figargs):
data_table = DataTable(source=step_source,
columns=[TableColumn(field='step',
title='Step'),
TableColumn(field='thresh',
title='Thresh'),
TableColumn(field='components',
title='Components')],
height=50, width=400)
def callback(attr, old, new):
try:
edges = D.edges[slider.value]
edges_source.data = ColumnDataSource(
pd.DataFrame(edges).rename(columns={1: 'end',
0: 'start'})).data
step_source.data = ColumnDataSource(
{'step': [slider.value],
'thresh': [D.threshlist[slider.value]],
'components': [len(D.graphs[slider.value])]}).data
except Exception as e:
print(e)
slider = Slider(start=0,
end=(len(D.edges) - 1),
value=0,
step=1,
title="Step")
slider.on_change('value', callback)
doc.add_root(column(slider, data_table, plot))
return lambda doc: modify_doc(doc, D, figargs)
def f1(X, y, model, n_precs=1000, n_splits=1, figargs=None):
0
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getTrackMap(target, reference=None, mode='speed', view='lapsdelta'):
if reference is None:
df_, df_r = target, None
else:
df_, df_r = acctelemetry.lapdelta(reference, target)
ds = ColumnDataSource(df_)
p0 = figure(plot_height=400, plot_width=800,
tools="crosshair,pan,reset,save,wheel_zoom")
colors = itertools.cycle(palette)
col0, col1 = next(colors), next(colors)
# create the velo vs dist plot
r0 = p0.line(x='dist_lap', y='speedkmh', source=ds, color=col0, line_width=2)
# overwrite the (non)selection glyphs with the base line style
# the style for the hover will be set below
nonselected_ = Line(line_alpha=1, line_color=col0, line_width=2)
r0.selection_glyph = nonselected_
r0.nonselection_glyph = nonselected_
if reference is not None:
# create the dt vs dist plot with extra y axis, set the (non)selection glyphs
lim = max(df_.dt.abs())
lim += lim*.2
p0.extra_y_ranges = {"dt": Range1d(start=-lim, end=lim)}
p0.add_layout(LinearAxis(
y_range_name='dt',
axis_label='dt [s]'), 'right')
r1 = p0.line(x='dist_lap', y='dt', source=ds, y_range_name='dt', color=col1, line_width=2)
r1.selection_glyph = Line(line_alpha=1, line_color='red', line_width=5)
r1.nonselection_glyph = Line(line_alpha=1, line_color=col1, line_width=2)
# create reference velo vs dist plot
p0.line(df_r.dist_lap, df_r.speedkmh, color=next(colors), line_width=2)
# create an invisible renderer for velo vs dist
# this is used to trigger the hover, thus the size is large
c0 = p0.circle(x='dist_lap', y='speedkmh', source=ds, size=10, fill_alpha=0.0, alpha=0.0)
c0.selection_glyph = Circle(fill_color='red', fill_alpha=1., line_color=None)
c0.nonselection_glyph = Circle(fill_alpha=0, line_color=None)
# create figure for track map
p1 = figure(plot_height=400, plot_width=800, tools="crosshair,pan,reset,save,wheel_zoom")
# create map of the track
c1 = getLapFigure(p1, df_, ds, mode, hasref=(reference is not None))
# add some lap tangents to guide the eye when comparing map and refmap
if reference is not None and mode not in ['absolut', 'gainloss']:
x0 = df_.x.values
y0 = df_.y.values
h = df_.heading.values
x1 = x0 + 30*np.cos(h+np.pi/2)
y1 = y0 + 30*np.sin(h+np.pi/2)
p1.segment(x0=x0, y0=y0, x1=x1, y1=y1, color="#F4A582", line_width=1)
# calculate points for the reference map drawn 'outside' of the other track map
getLapFigure(p1, df_, ds , mode, ref=True)
# Toooltips that show some information for each point, triggered via slider.onchange JS
tools = ['time','dist','speedkmh']
if reference is not None:
tools.append('speedkmh_r')
if mode not in ['absolut', 'gainloss', 'pedals', 'speed']:
tools.extend([mode, '%s_r'%mode])
elif mode in ['pedals']:
tools.extend(['throttle', 'throttle_r', 'brake', 'brake_r'])
tools.append('dt')
elif mode == 'pedals':
tools.extend(['throttle', 'brake'])
elif mode != 'speed':
tools.append(mode)
hover0 = createHoverTool(tools)
# a small hack to show only one tooltip (hover selects multiple points)
# TODO: doesn't work anymore with recent bokeh
# hover0.tooltips[-1] = (hover0.tooltips[-1][0], hover0.tooltips[-1][1]+"""
# < style>
# .bk-tooltip>div:not(:first-child) {display:none;}
# < /style>""")
hover0.renderers = [r0]
hover0.mode = 'vline'
hover0.line_policy='interp'
# selection change via button and slider. Tooltips 'hover0' will be rendered in 'p0' using rederer 'r0'
slider = getLapSlider(ds, p0, r0, hover0, view=view)
btns = getLapControls(ds, slider)
# Hovertools, that emit a selection change by modifying the slider value
callback = CustomJS(args=dict(slider=slider), code=
"""
let val = cb_data['index'].indices[0]
if (val!=0 && !isNaN(val))
slider.value = cb_data['index'].indices[0];
""")
p0.add_tools(HoverTool(tooltips=None, renderers=[c0],
callback=callback,
line_policy='interp', mode='vline'))
p1.add_tools(HoverTool(tooltips=None, renderers=[c1],
callback=callback,
line_policy='interp', mode='mouse', point_policy='snap_to_data'))
p0.add_tools(hover0)
# p1.add_tools(hover1)
return column(btns, slider, p0, p1, sizing_mode='scale_width')
def getTrackMapPanel(df):
0
View Source File : mw_plot_bokeh.py
License : MIT License
Project Creator : henrysky
License : MIT License
Project Creator : henrysky
def __init__(self, mode='face-on', center=(0, 0) * u.kpc, radius=90750 * u.lyr, unit=u.kpc, coord='galactic',
annotation=True, rot90=0, grayscale=False, r0=8.125):
super().__init__(grayscale=grayscale,
annotation=annotation,
rot90=rot90,
coord=coord,
mode=mode,
r0=r0,
center=center,
radius=radius,
unit=unit,
figsize=None,
dpi=None)
# prepossessing procedure
self._unit_english = self._unit.short_names[0]
if self._center.unit is not None and self._radius.unit is not None:
self._center = self._center.to(self._unit)
self._radius = self._radius.to(self._unit)
self.images_read()
self.s = 1.0
TOOLS = "pan, wheel_zoom, box_zoom, reset, save, box_select"
self.bokeh_fig = figure(title="", tools=TOOLS,
x_range=Range1d(self._ext[0], self._ext[1],
bounds=[min(self._ext[0], self._ext[1]), max(self._ext[0], self._ext[1])]),
y_range=Range1d(self._ext[2], self._ext[3],
bounds=[min(self._ext[2], self._ext[3]), max(self._ext[2], self._ext[3])]),
width=1000, height=1000)
if requests.head(self._gh_img_url, allow_redirects=True).status_code == -9999: # connection successful
# disabled currently because rotation and grayscale wont work
self.bokeh_fig.image_url(url=[self._gh_img_url],
x=self._ext[0], y=self._ext[2],
w=abs(self._ext[1]-self._ext[0]), h=abs(self._ext[3]-self._ext[2]), anchor="bottom_left")
else:
self._img = to_bokeh_img(self._img)
self.bokeh_fig.image_rgba(image=[self._img], x=self._ext[0], y=self._ext[2],
dw=abs(self._ext[1]-self._ext[0]), dh=abs(self._ext[3]-self._ext[2]))
self.bokeh_fig.xaxis.axis_label = f'{self._coord_english} ({self._unit_english})'
self.bokeh_fig.yaxis.axis_label = f'{self._coord_english} ({self._unit_english})'
def scatter(self, x, y, *args, **kwargs):
0
View Source File : mw_plot_bokeh.py
License : MIT License
Project Creator : henrysky
License : MIT License
Project Creator : henrysky
def __init__(self, center=(0, 0) * u.deg, radius=(180, 90) * u.deg, grayscale=False):
super().__init__(grayscale=grayscale,
projection='equirectangular',
center=center,
radius=radius,
figsize=None,
dpi=None)
self._unit = u.degree
self.s = 1.
#preprocessing
if self._center.unit is not None and self._radius.unit is not None:
self._center = self._center.to(self._unit)
self._radius = self._radius.to(self._unit)
if (self._center[0] + self._radius[0]).value > 180 or (self._center[0] - self._radius[0]).value < -180:
raise ValueError("The border of the width will be outside the range of -180 to 180 which is not allowed\n")
if (self._center[1] + self._radius[1]).value > 90 or (self._center[1] - self._radius[1]).value < -90:
raise ValueError("The border of the height will be outside the range of -90 to 90 which is not allowed")
if self._radius[0] < = 0 or self._radius[0] < = 0:
raise ValueError("Radius cannot be negative or 0")
self.images_read()
self.s = 1.0
TOOLS = "pan, wheel_zoom, box_zoom, reset, save, box_select"
self.bokeh_fig = figure(title="", tools=TOOLS,
x_range=Range1d(self._ext[0], self._ext[1],
bounds=[min(self._ext[0], self._ext[1]), max(self._ext[0], self._ext[1])]),
y_range=Range1d(self._ext[2], self._ext[3],
bounds=[min(self._ext[2], self._ext[3]), max(self._ext[2], self._ext[3])]),
width=1000, height=500)
if requests.head(self._gh_img_url, allow_redirects=True).status_code == -9999: # connection successful
# disabled currently because rotation and grayscale wont work
self.bokeh_fig.image_url(url=[self._gh_img_url],
x=self._ext[0], y=self._ext[2],
w=abs(self._ext[1]-self._ext[0]), h=abs(self._ext[3]-self._ext[2]), anchor="bottom_left")
else:
self._img = to_bokeh_img(self._img)
self.bokeh_fig.image_rgba(image=[self._img], x=self._ext[0], y=self._ext[2],
dw=abs(self._ext[1]-self._ext[0]), dh=abs(self._ext[3]-self._ext[2]))
self.bokeh_fig.xaxis.axis_label = 'Galactic Longitude (Degree)'
self.bokeh_fig.yaxis.axis_label = 'Galactic Latitude (Degree)'
def scatter(self, ra, dec, *args, **kwargs):
0
View Source File : clustree.py
License : MIT License
Project Creator : ivirshup
License : MIT License
Project Creator : ivirshup
def get_ranges(pos):
"""
Return appropriate range of x and y from position dict.
Usage:
>>> pos = nx.nx_agraph.graphviz_layout(g, prog="dot")
>>> plot = Plot(plot_width=1000, plot_height=600, **get_ranges(pos))
"""
all_pos = np.array(list(zip(*pos.values())))
max_x, max_y = all_pos.max(axis=1)
min_x, min_y = all_pos.min(axis=1)
x_margin = max((max_x - min_x) / 10, 0.5)
y_margin = max((max_y - min_y) / 10, 0.5)
return {
"x_range": Range1d(min_x - x_margin, max_x + x_margin),
"y_range": Range1d(min_y - y_margin, max_y + y_margin),
}
# Hacky, probably worth re-implementing
def set_edge_alpha(g):
0
View Source File : exercise.py
License : MIT License
Project Creator : karlicoss
License : MIT License
Project Creator : karlicoss
def _plot_manual_exercise(df):
pallete = palletes[max(palletes)] # get last
# todo one axis for count, one for seconds? although not really gonna work for
# maybe on separate plots?
has_err = df['error'].notna()
errs = df[has_err].copy()
errs['reps'] = 1 # meh
some_dt = df['dt'].dropna().iloc[-1]
errs['dt'].fillna(some_dt, inplace=True)
# not sure? some errs have reps.. errs['reps'].fillna(-5) # meh
df = df[~has_err]
# TODO would be nice to reuse stuff to display errors as a table
# FIXME handle none carefully here, otherwise they aren't displayed
plots = []
# todo hmm, reuse group hints somehow? not sure..
# TODO helper groupby to check for None (to make sure they are handled)
groups = list(df.groupby('kind'))
# sort by the most recent
groups = list(sorted(groups, key=lambda kind_d: max(unlocalize(kind_d[1]['dt'])), reverse=True))
kinds = [kind for kind, _ in groups]
# make colors stable
colors = {kind: c for kind, c in zip(kinds, cycle(pallete))}
colors['errors'] = 'red'
x_range = None
for k, edf in chain(
[('errors', errs)],
groups,
):
color = colors[k]
# TODO add some x jitter to declutter?
# need to preserve the order though? I guess need to group
p = date_figure(df, height=150, x_range=x_range)
p.scatter(x='dt', y='reps' , source=CDS(edf), legend_label='reps' , color=color)
from bokeh.models import LinearAxis, Range1d
maxy = np.nanmax(edf['volume'] * 1.1) # TODO meh
if not np.isnan(maxy): # I guess doesn't have volume?
p.extra_y_ranges = {'volume': Range1d(start=0.0, end=maxy)}
# add the second axis to the plot.
p.add_layout(LinearAxis(y_range_name='volume'), 'right')
p.scatter(x='dt', y='volume', source=CDS(edf), legend_label='volume', color='black', size=2, y_range_name='volume')
p.title.text = k
p.y_range.start = 0
if x_range is None:
x_range = p.x_range
plots.append(p)
# TODO not sure if I want sliding averages?
return column(plots)
def _plot_strength_volume(df) -> RollingResult:
0
View Source File : sleep.py
License : MIT License
Project Creator : karlicoss
License : MIT License
Project Creator : karlicoss
def _plot_sleep(df):
df = _sleep_df(df)
# TODO https://github.com/bokeh/bokeh/blob/master/examples/app/sliders.py
# todo naming: plot vs figure vs graph?
r = rolling(x='date', y='avg_hr', df=df, color='blue', legend_label='HR')
[g, g7, g30] = r
g7 .glyph.line_width = 2
g30.glyph.line_color = 'lightblue'
g30.glyph.line_width = 2
p = r.figure
p.extra_y_ranges = {'resp': Range1d(start=10, end=25)}
# Add the second axis to the plot.
p.add_layout(LinearAxis(y_range_name='resp'), 'right')
rolling(
df=df,
x='date', y='respiratory_rate_avg',
color='orange',
legend_label='Respiration',
avgs=['7D'],
y_range_name='resp',
context=r,
)
# TODO hmm, it appends error twice? not sure about it...
add_daysoff(p)
return r
# todo always set output_file("xx.html")? so the latest html is always dumped?
# todo what's the benefit of having date index at all?
# todo think of better naming
def plot_sleep_hrv(df):
0
View Source File : _plotting.py
License : GNU Affero General Public License v3.0
Project Creator : kernc
License : GNU Affero General Public License v3.0
Project Creator : kernc
def plot(*, results: pd.Series,
df: pd.DataFrame,
indicators: List[_Indicator],
filename='', plot_width=None,
plot_equity=True, plot_return=False, plot_pl=True,
plot_volume=True, plot_drawdown=False,
smooth_equity=False, relative_equity=True,
superimpose=True, resample=True,
reverse_indicators=True,
show_legend=True, open_browser=True):
"""
Like much of GUI code everywhere, this is a mess.
"""
# We need to reset global Bokeh state, otherwise subsequent runs of
# plot() contain some previous run's cruft data (was noticed when
# TestPlot.test_file_size() test was failing).
if not filename and not IS_JUPYTER_NOTEBOOK:
filename = _windos_safe_filename(str(results._strategy))
_bokeh_reset(filename)
COLORS = [BEAR_COLOR, BULL_COLOR]
BAR_WIDTH = .8
assert df.index.equals(results['_equity_curve'].index)
equity_data = results['_equity_curve'].copy(deep=False)
trades = results['_trades']
plot_volume = plot_volume and not df.Volume.isnull().all()
plot_equity = plot_equity and not trades.empty
plot_return = plot_return and not trades.empty
plot_pl = plot_pl and not trades.empty
is_datetime_index = isinstance(df.index, pd.DatetimeIndex)
from .lib import OHLCV_AGG
# ohlc df may contain many columns. We're only interested in, and pass on to Bokeh, these
df = df[list(OHLCV_AGG.keys())].copy(deep=False)
# Limit data to max_candles
if is_datetime_index:
df, indicators, equity_data, trades = _maybe_resample_data(
resample, df, indicators, equity_data, trades)
df.index.name = None # Provides source name @index
df['datetime'] = df.index # Save original, maybe datetime index
df = df.reset_index(drop=True)
equity_data = equity_data.reset_index(drop=True)
index = df.index
new_bokeh_figure = partial(
_figure,
x_axis_type='linear',
width=plot_width,
height=400,
tools="xpan,xwheel_zoom,box_zoom,undo,redo,reset,save",
active_drag='xpan',
active_scroll='xwheel_zoom')
pad = (index[-1] - index[0]) / 20
fig_ohlc = new_bokeh_figure(
x_range=Range1d(index[0], index[-1],
min_interval=10,
bounds=(index[0] - pad,
index[-1] + pad)) if index.size > 1 else None)
figs_above_ohlc, figs_below_ohlc = [], []
source = ColumnDataSource(df)
source.add((df.Close >= df.Open).values.astype(np.uint8).astype(str), 'inc')
trade_source = ColumnDataSource(dict(
index=trades['ExitBar'],
datetime=trades['ExitTime'],
exit_price=trades['ExitPrice'],
size=trades['Size'],
returns_positive=(trades['ReturnPct'] > 0).astype(int).astype(str),
))
inc_cmap = factor_cmap('inc', COLORS, ['0', '1'])
cmap = factor_cmap('returns_positive', COLORS, ['0', '1'])
colors_darker = [lightness(BEAR_COLOR, .35),
lightness(BULL_COLOR, .35)]
trades_cmap = factor_cmap('returns_positive', colors_darker, ['0', '1'])
if is_datetime_index:
fig_ohlc.xaxis.formatter = CustomJSTickFormatter(
args=dict(axis=fig_ohlc.xaxis[0],
formatter=DatetimeTickFormatter(days=['%d %b', '%a %d'],
months=['%m/%Y', "%b'%y"]),
source=source),
code='''
this.labels = this.labels || formatter.doFormat(ticks
.map(i => source.data.datetime[i])
.filter(t => t !== undefined));
return this.labels[index] || "";
''')
NBSP = '\N{NBSP}' * 4
ohlc_extreme_values = df[['High', 'Low']].copy(deep=False)
ohlc_tooltips = [
('x, y', NBSP.join(('$index',
'$y{0,0.0[0000]}'))),
('OHLC', NBSP.join(('@Open{0,0.0[0000]}',
'@High{0,0.0[0000]}',
'@Low{0,0.0[0000]}',
'@Close{0,0.0[0000]}'))),
('Volume', '@Volume{0,0}')]
def new_indicator_figure(**kwargs):
kwargs.setdefault('height', 90)
fig = new_bokeh_figure(x_range=fig_ohlc.x_range,
active_scroll='xwheel_zoom',
active_drag='xpan',
**kwargs)
fig.xaxis.visible = False
fig.yaxis.minor_tick_line_color = None
return fig
def set_tooltips(fig, tooltips=(), vline=True, renderers=()):
tooltips = list(tooltips)
renderers = list(renderers)
if is_datetime_index:
formatters = {'@datetime': 'datetime'}
tooltips = [("Date", "@datetime{%c}")] + tooltips
else:
formatters = {}
tooltips = [("#", "@index")] + tooltips
fig.add_tools(HoverTool(
point_policy='follow_mouse',
renderers=renderers, formatters=formatters,
tooltips=tooltips, mode='vline' if vline else 'mouse'))
def _plot_equity_section(is_return=False):
"""Equity section"""
# Max DD Dur. line
equity = equity_data['Equity'].copy()
dd_end = equity_data['DrawdownDuration'].idxmax()
if np.isnan(dd_end):
dd_start = dd_end = equity.index[0]
else:
dd_start = equity[:dd_end].idxmax()
# If DD not extending into the future, get exact point of intersection with equity
if dd_end != equity.index[-1]:
dd_end = np.interp(equity[dd_start],
(equity[dd_end - 1], equity[dd_end]),
(dd_end - 1, dd_end))
if smooth_equity:
interest_points = pd.Index([
# Beginning and end
equity.index[0], equity.index[-1],
# Peak equity and peak DD
equity.idxmax(), equity_data['DrawdownPct'].idxmax(),
# Include max dd end points. Otherwise the MaxDD line looks amiss.
dd_start, int(dd_end), min(int(dd_end + 1), equity.size - 1),
])
select = pd.Index(trades['ExitBar']).union(interest_points)
select = select.unique().dropna()
equity = equity.iloc[select].reindex(equity.index)
equity.interpolate(inplace=True)
assert equity.index.equals(equity_data.index)
if relative_equity:
equity /= equity.iloc[0]
if is_return:
equity -= equity.iloc[0]
yaxis_label = 'Return' if is_return else 'Equity'
source_key = 'eq_return' if is_return else 'equity'
source.add(equity, source_key)
fig = new_indicator_figure(
y_axis_label=yaxis_label,
**({} if plot_drawdown else dict(height=110)))
# High-watermark drawdown dents
fig.patch('index', 'equity_dd',
source=ColumnDataSource(dict(
index=np.r_[index, index[::-1]],
equity_dd=np.r_[equity, equity.cummax()[::-1]]
)),
fill_color='#ffffea', line_color='#ffcb66')
# Equity line
r = fig.line('index', source_key, source=source, line_width=1.5, line_alpha=1)
if relative_equity:
tooltip_format = f'@{source_key}{{+0,0.[000]%}}'
tick_format = '0,0.[00]%'
legend_format = '{:,.0f}%'
else:
tooltip_format = f'@{source_key}{{$ 0,0}}'
tick_format = '$ 0.0 a'
legend_format = '${:,.0f}'
set_tooltips(fig, [(yaxis_label, tooltip_format)], renderers=[r])
fig.yaxis.formatter = NumeralTickFormatter(format=tick_format)
# Peaks
argmax = equity.idxmax()
fig.scatter(argmax, equity[argmax],
legend_label='Peak ({})'.format(
legend_format.format(equity[argmax] * (100 if relative_equity else 1))),
color='cyan', size=8)
fig.scatter(index[-1], equity.values[-1],
legend_label='Final ({})'.format(
legend_format.format(equity.iloc[-1] * (100 if relative_equity else 1))),
color='blue', size=8)
if not plot_drawdown:
drawdown = equity_data['DrawdownPct']
argmax = drawdown.idxmax()
fig.scatter(argmax, equity[argmax],
legend_label='Max Drawdown (-{:.1f}%)'.format(100 * drawdown[argmax]),
color='red', size=8)
dd_timedelta_label = df['datetime'].iloc[int(round(dd_end))] - df['datetime'].iloc[dd_start]
fig.line([dd_start, dd_end], equity.iloc[dd_start],
line_color='red', line_width=2,
legend_label=f'Max Dd Dur. ({dd_timedelta_label})'
.replace(' 00:00:00', '')
.replace('(0 days ', '('))
figs_above_ohlc.append(fig)
def _plot_drawdown_section():
"""Drawdown section"""
fig = new_indicator_figure(y_axis_label="Drawdown")
drawdown = equity_data['DrawdownPct']
argmax = drawdown.idxmax()
source.add(drawdown, 'drawdown')
r = fig.line('index', 'drawdown', source=source, line_width=1.3)
fig.scatter(argmax, drawdown[argmax],
legend_label='Peak (-{:.1f}%)'.format(100 * drawdown[argmax]),
color='red', size=8)
set_tooltips(fig, [('Drawdown', '@drawdown{-0.[0]%}')], renderers=[r])
fig.yaxis.formatter = NumeralTickFormatter(format="-0.[0]%")
return fig
def _plot_pl_section():
"""Profit/Loss markers section"""
fig = new_indicator_figure(y_axis_label="Profit / Loss")
fig.add_layout(Span(location=0, dimension='width', line_color='#666666',
line_dash='dashed', line_width=1))
returns_long = np.where(trades['Size'] > 0, trades['ReturnPct'], np.nan)
returns_short = np.where(trades['Size'] < 0, trades['ReturnPct'], np.nan)
size = trades['Size'].abs()
size = np.interp(size, (size.min(), size.max()), (8, 20))
trade_source.add(returns_long, 'returns_long')
trade_source.add(returns_short, 'returns_short')
trade_source.add(size, 'marker_size')
if 'count' in trades:
trade_source.add(trades['count'], 'count')
r1 = fig.scatter('index', 'returns_long', source=trade_source, fill_color=cmap,
marker='triangle', line_color='black', size='marker_size')
r2 = fig.scatter('index', 'returns_short', source=trade_source, fill_color=cmap,
marker='inverted_triangle', line_color='black', size='marker_size')
tooltips = [("Size", "@size{0,0}")]
if 'count' in trades:
tooltips.append(("Count", "@count{0,0}"))
set_tooltips(fig, tooltips + [("P/L", "@returns_long{+0.[000]%}")],
vline=False, renderers=[r1])
set_tooltips(fig, tooltips + [("P/L", "@returns_short{+0.[000]%}")],
vline=False, renderers=[r2])
fig.yaxis.formatter = NumeralTickFormatter(format="0.[00]%")
return fig
def _plot_volume_section():
"""Volume section"""
fig = new_indicator_figure(y_axis_label="Volume")
fig.xaxis.formatter = fig_ohlc.xaxis[0].formatter
fig.xaxis.visible = True
fig_ohlc.xaxis.visible = False # Show only Volume's xaxis
r = fig.vbar('index', BAR_WIDTH, 'Volume', source=source, color=inc_cmap)
set_tooltips(fig, [('Volume', '@Volume{0.00 a}')], renderers=[r])
fig.yaxis.formatter = NumeralTickFormatter(format="0 a")
return fig
def _plot_superimposed_ohlc():
"""Superimposed, downsampled vbars"""
time_resolution = pd.DatetimeIndex(df['datetime']).resolution
resample_rule = (superimpose if isinstance(superimpose, str) else
dict(day='M',
hour='D',
minute='H',
second='T',
millisecond='S').get(time_resolution))
if not resample_rule:
warnings.warn(
f"'Can't superimpose OHLC data with rule '{resample_rule}'"
f"(index datetime resolution: '{time_resolution}'). Skipping.",
stacklevel=4)
return
df2 = (df.assign(_width=1).set_index('datetime')
.resample(resample_rule, label='left')
.agg(dict(OHLCV_AGG, _width='count')))
# Check if resampling was downsampling; error on upsampling
orig_freq = _data_period(df['datetime'])
resample_freq = _data_period(df2.index)
if resample_freq < orig_freq:
raise ValueError('Invalid value for `superimpose`: Upsampling not supported.')
if resample_freq == orig_freq:
warnings.warn('Superimposed OHLC plot matches the original plot. Skipping.',
stacklevel=4)
return
df2.index = df2['_width'].cumsum().shift(1).fillna(0)
df2.index += df2['_width'] / 2 - .5
df2['_width'] -= .1 # Candles don't touch
df2['inc'] = (df2.Close >= df2.Open).astype(int).astype(str)
df2.index.name = None
source2 = ColumnDataSource(df2)
fig_ohlc.segment('index', 'High', 'index', 'Low', source=source2, color='#bbbbbb')
colors_lighter = [lightness(BEAR_COLOR, .92),
lightness(BULL_COLOR, .92)]
fig_ohlc.vbar('index', '_width', 'Open', 'Close', source=source2, line_color=None,
fill_color=factor_cmap('inc', colors_lighter, ['0', '1']))
def _plot_ohlc():
"""Main OHLC bars"""
fig_ohlc.segment('index', 'High', 'index', 'Low', source=source, color="black")
r = fig_ohlc.vbar('index', BAR_WIDTH, 'Open', 'Close', source=source,
line_color="black", fill_color=inc_cmap)
return r
def _plot_ohlc_trades():
"""Trade entry / exit markers on OHLC plot"""
trade_source.add(trades[['EntryBar', 'ExitBar']].values.tolist(), 'position_lines_xs')
trade_source.add(trades[['EntryPrice', 'ExitPrice']].values.tolist(), 'position_lines_ys')
fig_ohlc.multi_line(xs='position_lines_xs', ys='position_lines_ys',
source=trade_source, line_color=trades_cmap,
legend_label=f'Trades ({len(trades)})',
line_width=8, line_alpha=1, line_dash='dotted')
def _plot_indicators():
"""Strategy indicators"""
def _too_many_dims(value):
assert value.ndim >= 2
if value.ndim > 2:
warnings.warn(f"Can't plot indicators with >2D ('{value.name}')",
stacklevel=5)
return True
return False
class LegendStr(str):
# The legend string is such a string that only matches
# itself if it's the exact same object. This ensures
# legend items are listed separately even when they have the
# same string contents. Otherwise, Bokeh would always consider
# equal strings as one and the same legend item.
def __eq__(self, other):
return self is other
ohlc_colors = colorgen()
indicator_figs = []
for i, value in enumerate(indicators):
value = np.atleast_2d(value)
# Use .get()! A user might have assigned a Strategy.data-evolved
# _Array without Strategy.I()
if not value._opts.get('plot') or _too_many_dims(value):
continue
is_overlay = value._opts['overlay']
is_scatter = value._opts['scatter']
if is_overlay:
fig = fig_ohlc
else:
fig = new_indicator_figure()
indicator_figs.append(fig)
tooltips = []
colors = value._opts['color']
colors = colors and cycle(_as_list(colors)) or (
cycle([next(ohlc_colors)]) if is_overlay else colorgen())
legend_label = LegendStr(value.name)
for j, arr in enumerate(value, 1):
color = next(colors)
source_name = f'{legend_label}_{i}_{j}'
if arr.dtype == bool:
arr = arr.astype(int)
source.add(arr, source_name)
tooltips.append(f'@{{{source_name}}}{{0,0.0[0000]}}')
if is_overlay:
ohlc_extreme_values[source_name] = arr
if is_scatter:
fig.scatter(
'index', source_name, source=source,
legend_label=legend_label, color=color,
line_color='black', fill_alpha=.8,
marker='circle', radius=BAR_WIDTH / 2 * 1.5)
else:
fig.line(
'index', source_name, source=source,
legend_label=legend_label, line_color=color,
line_width=1.3)
else:
if is_scatter:
r = fig.scatter(
'index', source_name, source=source,
legend_label=LegendStr(legend_label), color=color,
marker='circle', radius=BAR_WIDTH / 2 * .9)
else:
r = fig.line(
'index', source_name, source=source,
legend_label=LegendStr(legend_label), line_color=color,
line_width=1.3)
# Add dashed centerline just because
mean = float(pd.Series(arr).mean())
if not np.isnan(mean) and (abs(mean) < .1 or
round(abs(mean), 1) == .5 or
round(abs(mean), -1) in (50, 100, 200)):
fig.add_layout(Span(location=float(mean), dimension='width',
line_color='#666666', line_dash='dashed',
line_width=.5))
if is_overlay:
ohlc_tooltips.append((legend_label, NBSP.join(tooltips)))
else:
set_tooltips(fig, [(legend_label, NBSP.join(tooltips))], vline=True, renderers=[r])
# If the sole indicator line on this figure,
# have the legend only contain text without the glyph
if len(value) == 1:
fig.legend.glyph_width = 0
return indicator_figs
# Construct figure ...
if plot_equity:
_plot_equity_section()
if plot_return:
_plot_equity_section(is_return=True)
if plot_drawdown:
figs_above_ohlc.append(_plot_drawdown_section())
if plot_pl:
figs_above_ohlc.append(_plot_pl_section())
if plot_volume:
fig_volume = _plot_volume_section()
figs_below_ohlc.append(fig_volume)
if superimpose and is_datetime_index:
_plot_superimposed_ohlc()
ohlc_bars = _plot_ohlc()
_plot_ohlc_trades()
indicator_figs = _plot_indicators()
if reverse_indicators:
indicator_figs = indicator_figs[::-1]
figs_below_ohlc.extend(indicator_figs)
set_tooltips(fig_ohlc, ohlc_tooltips, vline=True, renderers=[ohlc_bars])
source.add(ohlc_extreme_values.min(1), 'ohlc_low')
source.add(ohlc_extreme_values.max(1), 'ohlc_high')
custom_js_args = dict(ohlc_range=fig_ohlc.y_range,
source=source)
if plot_volume:
custom_js_args.update(volume_range=fig_volume.y_range)
fig_ohlc.x_range.js_on_change('end', CustomJS(args=custom_js_args,
code=_AUTOSCALE_JS_CALLBACK))
plots = figs_above_ohlc + [fig_ohlc] + figs_below_ohlc
linked_crosshair = CrosshairTool(dimensions='both')
for f in plots:
if f.legend:
f.legend.visible = show_legend
f.legend.location = 'top_left'
f.legend.border_line_width = 1
f.legend.border_line_color = '#333333'
f.legend.padding = 5
f.legend.spacing = 0
f.legend.margin = 0
f.legend.label_text_font_size = '8pt'
f.legend.click_policy = "hide"
f.min_border_left = 0
f.min_border_top = 3
f.min_border_bottom = 6
f.min_border_right = 10
f.outline_line_color = '#666666'
f.add_tools(linked_crosshair)
wheelzoom_tool = next(wz for wz in f.tools if isinstance(wz, WheelZoomTool))
wheelzoom_tool.maintain_focus = False
kwargs = {}
if plot_width is None:
kwargs['sizing_mode'] = 'stretch_width'
fig = gridplot(
plots,
ncols=1,
toolbar_location='right',
toolbar_options=dict(logo=None),
merge_tools=True,
**kwargs
)
show(fig, browser=None if open_browser else 'none')
return fig
def plot_heatmaps(heatmap: pd.Series, agg: Union[Callable, str], ncols: int,
0
View Source File : limb_darkening_fit.py
License : MIT License
Project Creator : kevin218
License : MIT License
Project Creator : kevin218
def plot_tabs(self, show=False, **kwargs):
"""Plot the LDCs in a tabbed figure
Parameters
----------
fig: matplotlib.pyplot.figure, bokeh.plotting.figure (optional)
An existing figure to plot on
show: bool
Show the figure
"""
# Change names to reflect ld profile
old_names = self.results['name']
for n, row in enumerate(self.results):
self.results[n]['name'] = row['profile']
# Draw a figure for each wavelength bin
tabs = []
for wav in np.unique(self.results['wave_eff']):
# Plot it
TOOLS = 'box_zoom, box_select, crosshair, reset, hover'
fig = bkp.figure(tools=TOOLS, x_range=Range1d(0, 1), y_range=Range1d(0, 1),
plot_width=800, plot_height=400)
self.plot(wave_eff=wav, fig=fig)
# Plot formatting
fig.legend.location = 'bottom_right'
fig.xaxis.axis_label = 'mu'
fig.yaxis.axis_label = 'Intensity'
tabs.append(Panel(child=fig, title=str(wav)))
# Make the final tabbed figure
final = Tabs(tabs=tabs)
# Put the names back
self.results['name'] = old_names
if show:
bkp.show(final)
else:
return final
def plot(self, fig=None, show=False, **kwargs):
0
View Source File : limb_darkening_fit.py
License : MIT License
Project Creator : kevin218
License : MIT License
Project Creator : kevin218
def plot(self, fig=None, show=False, **kwargs):
"""Plot the LDCs
Parameters
----------
fig: matplotlib.pyplot.figure, bokeh.plotting.figure (optional)
An existing figure to plot on
show: bool
Show the figure
"""
# Separate plotting kwargs from parameter kwargs
pwargs = {i: j for i, j in kwargs.items() if i in self.results.columns}
kwargs = {i: j for i, j in kwargs.items() if i not in pwargs.keys()}
# Filter the table by given kwargs
table = utils.filter_table(self.results, **pwargs)
for row in table:
# Set color and label for plot
color = row['color']
label = row['name']
# Generate smooth curve
ldfunc = row['ldfunc']
mu_vals = np.linspace(0, 1, 1000)
ld_vals = ldfunc(mu_vals, *row['coeffs'])
# Generate smooth errors
dn_err, up_err = self.bootstrap_errors(mu_vals, ldfunc,
row['coeffs'],
row['errors'])
# Matplotlib fig by default
if fig is None:
fig = bkp.figure()
# Add fits to matplotlib
if isinstance(fig, matplotlib.figure.Figure):
# Make axes
ax = fig.add_subplot(111)
# Plot the fitted points
ax.errorbar(row['raw_mu'], row['raw_ld'], c='k',
ls='None', marker='o', markeredgecolor='k',
markerfacecolor='None')
# Plot the mu cutoff
ax.axvline(row['mu_min'], color='0.5', ls=':')
# Draw the curve and error
ax.plot(mu_vals, ld_vals, color=color, label=label, **kwargs)
ax.fill_between(mu_vals, dn_err, up_err, color=color,
alpha=0.1)
ax.set_ylim(0, 1)
ax.set_xlim(0, 1)
# Or to bokeh!
else:
# Set the plot elements
fig.x_range = Range1d(0, 1)
fig.y_range = Range1d(0, 1)
fig.xaxis.axis_label = 'mu'
fig.yaxis.axis_label = 'Normalized Intensity'
fig.legend.location = "bottom_right"
# Plot the fitted points
fig.circle(row['raw_mu'], row['raw_ld'], fill_color='black')
# Plot the mu cutoff
fig.line([row['mu_min']]*2, [0, 1], legend='cutoff',
line_color='#6b6ecf', line_dash='dotted')
# Draw the curve and error
fig.line(mu_vals, ld_vals, line_color=color, legend=label,
**kwargs)
vals = np.append(mu_vals, mu_vals[::-1])
evals = np.append(dn_err, up_err[::-1])
fig.patch(vals, evals, color=color, fill_alpha=0.2,
line_alpha=0)
if show:
if isinstance(fig, matplotlib.figure.Figure):
plt.xlabel(r'$\mu$')
plt.ylabel(r'$I(\mu)/I(\mu = 1)$')
plt.legend(loc=0, frameon=False)
plt.show()
else:
bkp.show(fig)
else:
return fig
0
View Source File : compare_tab.py
License : Apache License 2.0
Project Creator : nancyyanyu
License : Apache License 2.0
Project Creator : nancyyanyu
def compare_plot():
stats = PreText(text='', width=500)
corr = PreText(text='', width=500)
def _ma(series,n):
return series.rolling(window=n).mean()
# connect to Cassandra database
def make_dataset(start='2014-01-01'):
df=pd.DataFrame()
for comp in symbol_list:
database=CassandraStorage(comp)
database.session.row_factory = pandas_factory
database.session.default_fetch_size = None
query="SELECT * FROM {} WHERE time>'{}' ALLOW FILTERING;".format(database.symbol+'_historical',start)
rslt = database.session.execute(query, timeout=None)
df_comp = rslt._current_rows
df_comp['ma5']=_ma(df_comp.adjusted_close,5)
df_comp['ma10']=_ma(df_comp.adjusted_close,10)
df_comp['ma30']=_ma(df_comp.adjusted_close,30)
df=df.append(df_comp)
return df
df_all=make_dataset(start='2014-01-01')
df_init=df_all[df_all.symbol==symbol_list[0]]
source=ColumnDataSource(data= df_init.to_dict('list'))
# hover setting
TOOLTIPS = [
("time", "@time{%F}"),
("adjusted close", "$@adjusted_close"),
("close", "$@close"),
("open", "$@open"),
("high", "$@high"),
("low", "$@low"),
("volume","@volume")]
formatters={
'time' : 'datetime'}
hover = HoverTool(tooltips=TOOLTIPS,formatters=formatters,mode='vline')
# create plot
p = figure(title='{} (Click on legend entries to hide the corresponding lines)'.format(symbol_list[0]),
plot_height=300,
tools="crosshair,save,undo,xpan,xwheel_zoom,ybox_zoom,reset",
active_scroll='xwheel_zoom',
x_axis_type="datetime",
y_axis_location="left")
p.add_tools(hover)
palte=all_palettes['Set2'][8]
p.line('time', 'adjusted_close', alpha=1.0, line_width=2, color=palte[3], legend='Adjusted Close',source=source)
p.line('time', 'ma5', line_width=1, color=palte[0], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA5',source=source)
p.line('time', 'ma10', line_width=1, color=palte[1], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA10',source=source)
p.line('time', 'ma30', line_width=1, color=palte[2], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA30',source=source)
p.y_range = Range1d(min(source.data['adjusted_close'])*0.3, max(source.data['adjusted_close'])*1.05)
p.extra_y_ranges = {"volumes": Range1d(start=min(source.data['volume'])/2,
end=max(source.data['volume'])*2)}
p.add_layout(LinearAxis(y_range_name="volumes"), 'right')
p.vbar('time', width=3,top='volume', color=choice(all_palettes['Set2'][8]),alpha=0.5, y_range_name="volumes",source=source)
p.legend.location = "top_left"
p.legend.click_policy="hide"
def callback(attr,old,new):
symbol1, symbol2=compare_select1.value, compare_select2.value
df_init1=df_all[df_all.symbol==symbol1]
df_init2=df_all[df_all.symbol==symbol2]
source.data.update( df_init1.to_dict('list'))
p.title.text =symbol1+' (Click on legend entries to hide the corresponding lines)'
p.y_range.start=min(source.data['adjusted_close'])*0.3
p.y_range.end=max(source.data['adjusted_close'])*1.05
p.extra_y_ranges['volumes'].start=min(source.data['volume'])/2.
p.extra_y_ranges['volumes'].end=max(source.data['volume'])*2.
source2.data.update( df_init2.to_dict('list'))
p2.title.text =symbol2+' (Click on legend entries to hide the corresponding lines)'
p2.y_range.start=min(source2.data['adjusted_close'])*0.3
p2.y_range.end=max(source2.data['adjusted_close'])*1.05
p2.extra_y_ranges['volumes'].start=min(source2.data['volume'])/2.
p2.extra_y_ranges['volumes'].end=max(source2.data['volume'])*2.
update_stat(symbol1,symbol2)
def update_stat(symbol1,symbol2):
des=pd.DataFrame()
des[symbol1]=df_all[df_all.symbol==symbol1]['adjusted_close']
des[symbol2]=df_all[df_all.symbol==symbol2]['adjusted_close']
des[symbol1+'_return']=des[symbol1].pct_change()
des[symbol2+'_return']=des[symbol2].pct_change()
stats.text = "Statistics \n"+str(des.describe())
correlation=des[[symbol1+'_return',symbol2+'_return']].corr()
corr.text="Correlation \n"+str(correlation)
update_stat(symbol_list[0],symbol_list[1])
compare_select1=Select(value=symbol_list[0],options=symbol_list)
compare_select1.on_change('value', callback)
"""
Tab2-plot2:
"""
df_init2=df_all[df_all.symbol==symbol_list[1]]
source2=ColumnDataSource(data= df_init2.to_dict('list'))
# create plot
# hover setting
p2 = figure(title='{} (Click on legend entries to hide the corresponding lines)'.format(symbol_list[1]),plot_height=300,
tools="crosshair,save,undo,xpan,xwheel_zoom,ybox_zoom,reset",
active_scroll='xwheel_zoom',
x_axis_type="datetime",
y_axis_location="left")
p2.add_tools(hover)
p2.line('time', 'adjusted_close', alpha=1.0, line_width=2, color=palte[4], legend='Adjusted Close',source=source2)
p2.line('time', 'ma5', line_width=1, color=palte[5], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA5',source=source2)
p2.line('time', 'ma10', line_width=1, color=palte[6], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA10',source=source2)
p2.line('time', 'ma30', line_width=1, color=palte[7], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA30',source=source2)
p2.y_range = Range1d(min(source2.data['adjusted_close'])*0.3, max(source2.data['adjusted_close'])*1.05)
p2.extra_y_ranges = {"volumes": Range1d(start=min(source2.data['volume'])/2,
end=max(source2.data['volume'])*2)}
p2.add_layout(LinearAxis(y_range_name="volumes"), 'right')
p2.vbar('time', width=3,top='volume', color=choice(all_palettes['Set2'][8]),alpha=0.5, y_range_name="volumes",source=source2)
p2.legend.location = "top_left"
p2.legend.click_policy="hide"
compare_select2=Select(value=symbol_list[1],options=symbol_list)
compare_select2.on_change('value', callback)
widget=column(compare_select1,compare_select2)
return p,p2,widget,stats,corr
0
View Source File : single_tab.py
License : Apache License 2.0
Project Creator : nancyyanyu
License : Apache License 2.0
Project Creator : nancyyanyu
def candlestick():
if '^GSPC' in symbol_list:
symbol_list.remove('^GSPC')
stock_select=Select(value=symbol_list[0],options=symbol_list)
summaryText = Div(text="",width=400)
financialText=Div(text="",width=180)
def update_summary(symbol):
company,buzzsummary,officerString,institution_df=read_company(symbol)
summaryText.text =""" < b> < p style="color:blue;">Overview: < /p> < /b>
< b>Company: < /b> {} < br>
< b>Address: < /b> {} < br>
< b>City: < /b> {} < br>
< b>State: < /b> {} < br>
< b>Website: < /b> < a href="{}">{} < /a> < br>
< b>Industry: < /b> {} < br>
< b>Sector: < /b> {} < br>
< b>Company Officers: < /b> {} < br>
< b>Summary: < /b> {} < br>""".format(company['price']['longName'],
company['summaryProfile']['address1'],
company['summaryProfile']['city'],
company['summaryProfile']['state'],
company['summaryProfile']['website'],
company['summaryProfile']['website'],
company['summaryProfile']['industry'],
company['summaryProfile']['sector'],
officerString,
buzzsummary)
financialText.text=""" < b> < p style="color:blue;">Financial: < /p> < /b>
< b>Recommendation: {} < /b> < br>
< b>Enterprise Value: < /b> {} < br>
< b>Profit Margins: < /b> {} < br>
< b>Beta: < /b> {} < br>
< b>EBITDA: < /b> {} < br>
< b>Total Debt: < /b> {} < br>
< b>Total Revenue: < /b> {} < br>
< b>DebtToEquity: < /b> {} < br>
< b>Revenue Growth: < /b> {} < br>
< b>Current Ratio: < /b> {} < br>
< b>ROE: < /b> {} < br>
< b>ROA: < /b> {} < br>
< b>Gross Profits: < /b> {} < br>
< b>Quick Ratio: < /b> {} < br>
< b>Free Cashflow: < /b> {} < br>
""".format(company['financialData']['recommendationKey'].upper(),
company['defaultKeyStatistics']['enterpriseValue']['fmt'],
company['defaultKeyStatistics']['profitMargins']['fmt'],
company['defaultKeyStatistics']['beta']['fmt'],
company['financialData']['ebitda']['fmt'],
company['financialData']['totalDebt']['fmt'],
company['financialData']['totalRevenue']['fmt'],
company['financialData']['debtToEquity']['fmt'],
company['financialData']['revenueGrowth']['fmt'],
company['financialData']['currentRatio']['fmt'],
company['financialData']['returnOnAssets']['fmt'],
company['financialData']['returnOnEquity']['fmt'],
company['financialData']['grossProfits']['fmt'],
company['financialData']['quickRatio']['fmt'],
company['financialData']['freeCashflow']['fmt'])
update_summary(stock_select.value)
# connect to Cassandra database
database=CassandraStorage(symbol_list[0])
database.session.row_factory = pandas_factory
database.session.default_fetch_size = None
query="SELECT * FROM {} WHERE time>'2015-01-01' ALLOW FILTERING;".format('{}_historical'.format(symbol_list[0]))
rslt = database.session.execute(query, timeout=None)
df = rslt._current_rows
# create color list
color=df.close>df.open
color=color.replace(True,'green')
color=color.replace(False,'red')
# set data source
source = ColumnDataSource(data=dict(close=list(df.close.values),
adjusted_close=list(df.adjusted_close.values),
open=list(df.open.values),
high=list(df.high.values),
low=list(df.low.values),
volume=list(df.volume.values),
time=list(df.time.dt.date.values),
color=list(color.values)))
# hover setting
TOOLTIPS = [
("time", "@time{%F}"),
("adjusted close", "$@adjusted_close"),
("close", "$@close"),
("open", "$@open"),
("high", "$@high"),
("low", "$@low"),
("volume","@volume")]
formatters={
'time' : 'datetime'}
hover = HoverTool(tooltips=TOOLTIPS,formatters=formatters,mode='vline')
# create figure
p = figure(title='{} Candlestick'.format(stock_select.value),plot_height=400,
tools="crosshair,save,undo,xpan,xwheel_zoom,xbox_zoom,reset",
active_scroll='xwheel_zoom',
x_axis_type="datetime")
p.add_tools(hover)
p.line('time', 'close', alpha=0.2, line_width=1, color='navy', source=source)
p.segment('time', 'high', 'time', 'low', line_width=1,color="black", source=source)
p.segment('time', 'open', 'time', 'close', line_width=3, color='color', source=source)
p.y_range = Range1d(min(source.data['close'])*0.3, max(source.data['close'])*1.05)
p.extra_y_ranges = {"volumes": Range1d(start=min(source.data['volume'])/2,
end=max(source.data['volume'])*2)}
p.add_layout(LinearAxis(y_range_name="volumes"), 'right')
p.vbar('time', width=3,top='volume', color=choice(all_palettes['Set2'][8]),alpha=0.5, y_range_name="volumes",source=source)
p.xaxis.axis_label = 'Time'
# set data source
_,_,_,institution_df=read_company(symbol_list[0])
source_ins = ColumnDataSource(data=dict(organization=list(institution_df.organization.values),
pctHeld=list(institution_df.pctHeld.values),
position=list(institution_df.position.values),
color=Set3[12][:len(institution_df)]))
s1=figure(x_range=source_ins.data['organization'],plot_height=300,plot_width=700,title='Institution Ownership')
s1.vbar(x='organization', top='position', width=0.8, color='color', source=source_ins)
s1.xaxis.major_label_orientation = pi/7
labels = LabelSet(x='organization', y='position', text='pctHeld', level='glyph',
x_offset=-15, y_offset=-10, source=source_ins, render_mode='canvas',text_font_size="8pt")
s1.add_layout(labels)
# callback funtion for Select tool 'stock_select'
def callback(attr,old,new):
symbol=stock_select.value
_,_,_,institution=read_company(symbol)
if symbol=='S&P500':
symbol='^GSPC'
database=CassandraStorage(symbol)
database.session.row_factory = pandas_factory
database.session.default_fetch_size = None
if symbol=='^GSPC':
symbol='GSPC'
query="SELECT * FROM {} WHERE time>'2015-01-01' ALLOW FILTERING;".format(symbol+'_historical')
rslt = database.session.execute(query, timeout=None)
df = rslt._current_rows
color=df.close>df.open
color=color.replace(True,'green')
color=color.replace(False,'red')
# update source data
source.data=dict(close=list(df.close.values),
adjusted_close=list(df.adjusted_close.values),
open=list(df.open.values),
high=list(df.high.values),
low=list(df.low.values),
volume=list(df.volume.values),
time=list(df.time.dt.date.values),
color=list(color.values))
source_ins.data=dict(organization=list(institution.organization.values),
pctHeld=list(institution.pctHeld.values),
position=list(institution.position.values),
color=Set3[12][:len(institution)])
p.title.text=symbol+' Candlestick'
p.y_range.start=min(source.data['close'])*0.3
p.y_range.end=max(source.data['close'])*1.05
p.extra_y_ranges['volumes'].start=min(source.data['volume'])/2.
p.extra_y_ranges['volumes'].end=max(source.data['volume'])*2.
s1.x_range.factors=source_ins.data['organization']
update_summary(symbol)
stock_select.on_change('value', callback)
return p,stock_select,summaryText,financialText,s1
def stream_price():
0
View Source File : single_tab.py
License : Apache License 2.0
Project Creator : nancyyanyu
License : Apache License 2.0
Project Creator : nancyyanyu
def stream_price():
# connect to s&p500's database
plot_symbol='^GSPC'
database=CassandraStorage(plot_symbol)
database.session.row_factory = pandas_factory
database.session.default_fetch_size = None
# if datetime.datetime.now(timezone('US/Eastern')).time() < datetime.time(9,30):
# query_time=str(datetime.datetime.now().date())
last_trading_day= datetime.datetime.now(timezone(timeZone)).date()
query="SELECT * FROM {} WHERE time>='{}' ALLOW FILTERING;".format(plot_symbol[1:]+'_tick',last_trading_day)
rslt = database.session.execute(query, timeout=None)
df = rslt._current_rows
# wrangle timezone (Cassandra will change datetime to UTC time)
trans_time=pd.DatetimeIndex(pd.to_datetime(df.time,unit='ms')).tz_localize('GMT').tz_convert('US/Pacific').to_pydatetime()
trans_time=[i.replace(tzinfo=None) for i in trans_time]
source= ColumnDataSource()
# hover setting
TOOLTIPS = [
("time", "@time{%F %T}"),
("close", "$@close"),
("volume","@volume")]
formatters={
'time' : 'datetime'}
hover = HoverTool(tooltips=TOOLTIPS,formatters=formatters,mode='vline')
# create plot
p = figure(title='S&P500 Realtime Price',
plot_height=200,
tools="crosshair,save,undo,xpan,xwheel_zoom,ybox_zoom,reset",
x_axis_type="datetime",
y_axis_location="left")
p.add_tools(hover)
p.x_range.follow = "end"
p.x_range.follow_interval = 1000000
p.x_range.range_padding = 0
# during trading
if len(df)>0 \
and datetime.datetime.now(timezone(timeZone)).time() < datetime.time(16,0,0) \
and datetime.datetime.now(timezone(timeZone)).time()>datetime.time(9,30,0):
# init source data to those already stored in Cassandra dataase - '{}_tick', so that streaming plot will not start over after refreshing
source= ColumnDataSource(dict(time=list(trans_time),
close=list(df.close.values),
volume=list(df.volume.values)))
p.y_range = Range1d(min(source.data['close'])/1.005, max(source.data['close'])*1.005)
p.extra_y_ranges = {"volumes": Range1d(start=min(source.data['volume'])*0.5,
end=max(source.data['volume'])*2)}
# no trading history or not during trading hour
else:
source= ColumnDataSource(dict(time=[],
close=[],
volume=[]))
p.y_range = Range1d(0,1e4)
p.extra_y_ranges = {"volumes": Range1d(start=0,
end=1e10)}
p.line(x='time', y='close', alpha=0.2, line_width=3, color='blue', source=source)
p.add_layout(LinearAxis(y_range_name="volumes"), 'right')
p.vbar('time', width=3,top='volume', color=choice(all_palettes['Set2'][8]),alpha=0.5, y_range_name="volumes",source=source)
# get update data from a json file overwritter every ~18 seconds
def _create_prices():
with open(path+'cache/data.json','r') as f:
dict_data = json.load(f)
return float(dict_data['close']),dict_data['volume'],dict_data['time']
# update function for stream plot
def update():
close,volume,time=_create_prices()
new_data = dict(
time=[datetime.datetime.strptime(time[:19], "%Y-%m-%d %H:%M:%S")],
close=[close],
volume=[volume]
)
#print(new_data)
source.stream(new_data)
#print ('update source data',str(time))
return p,update
0
View Source File : interact.py
License : MIT License
Project Creator : nasa
License : MIT License
Project Creator : nasa
def make_lightcurve_figure_elements(lc, lc_source):
"""Make the lightcurve figure elements.
Parameters
----------
lc : LightCurve
Lightcurve to be shown.
lc_source : bokeh.plotting.ColumnDataSource
Bokeh object that enables the visualization.
Returns
----------
fig : `bokeh.plotting.figure` instance
step_renderer : GlyphRenderer
vertical_line : Span
"""
if lc.mission == 'K2':
title = "Lightcurve for {} (K2 C{})".format(
lc.label, lc.campaign)
elif lc.mission == 'Kepler':
title = "Lightcurve for {} (Kepler Q{})".format(
lc.label, lc.quarter)
elif lc.mission == 'TESS':
title = "Lightcurve for {} (TESS Sec. {})".format(
lc.label, lc.sector)
else:
title = "Lightcurve for target {}".format(lc.label)
fig = figure(title=title, plot_height=340, plot_width=600,
tools="pan,wheel_zoom,box_zoom,tap,reset",
toolbar_location="below",
border_fill_color="whitesmoke")
fig.title.offset = -10
fig.yaxis.axis_label = 'Flux (e/s)'
fig.xaxis.axis_label = 'Time (days)'
try:
if (lc.mission == 'K2') or (lc.mission == 'Kepler'):
fig.xaxis.axis_label = 'Time - 2454833 (days)'
elif lc.mission == 'TESS':
fig.xaxis.axis_label = 'Time - 2457000 (days)'
except AttributeError: # no mission keyword available
pass
ylims = get_lightcurve_y_limits(lc_source)
fig.y_range = Range1d(start=ylims[0], end=ylims[1])
# Add step lines, circles, and hover-over tooltips
fig.step('time', 'flux', line_width=1, color='gray',
source=lc_source, nonselection_line_color='gray',
nonselection_line_alpha=1.0)
circ = fig.circle('time', 'flux', source=lc_source, fill_alpha=0.3, size=8,
line_color=None, selection_color="firebrick",
nonselection_fill_alpha=0.0,
nonselection_fill_color="grey",
nonselection_line_color=None,
nonselection_line_alpha=0.0,
fill_color=None, hover_fill_color="firebrick",
hover_alpha=0.9, hover_line_color="white")
tooltips = [("Cadence", "@cadence"),
("Time ({})".format(lc.time_format.upper()),
"@time{0,0.000}"),
("Time (ISO)", "@time_iso"),
("Flux", "@flux"),
("Quality Code", "@quality_code"),
("Quality Flag", "@quality")]
fig.add_tools(HoverTool(tooltips=tooltips, renderers=[circ],
mode='mouse', point_policy="snap_to_data"))
# Vertical line to indicate the cadence
vertical_line = Span(location=lc.time[0], dimension='height',
line_color='firebrick', line_width=4, line_alpha=0.5)
fig.add_layout(vertical_line)
return fig, vertical_line
def add_gaia_figure_elements(tpf, fig, magnitude_limit=18):
See More Examples