Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from bokeh.plotting import figure, output_file, show, VBox
from bokeh.sampledata.olympics2014 import data
data = { d['abbr']: d['medals'] for d in data['data'] if d['medals']['total'] > 0}
# pull out just the data we care about
countries = sorted(
data.keys(),
key=lambda x: data[x]['total'], reverse=True
)
gold = np.array([data[abbr]['gold'] for abbr in countries], dtype=np.float)
silver = np.array([data[abbr]['silver'] for abbr in countries], dtype=np.float)
bronze = np.array([data[abbr]['bronze'] for abbr in countries], dtype=np.float)
# EXERCISE: output static HTML file
output_file('olympics.html')
# create a figure()
p1 = figure(title="Olympic Medals by Country (stacked)", tools="",
x_range=countries, y_range=[0, max(gold+silver+bronze)],
background_fill='#59636C', plot_width=800
)
# use the `rect` renderer to display stacked bars of the medal results. Note
# that we set y_range explicitly on the first renderer
p1.rect(x=countries, y=bronze/2, width=0.8, height=bronze, color="#CD7F32", alpha=0.6)
p1.rect(x=countries, y=bronze+silver/2, width=0.8, height=silver, color="silver", alpha=0.6)
# EXERCISE: add a `rect` renderer to stack the gold medal results
p1.rect(x=countries, y=bronze+silver+gold/2, width=0.8, height=gold, color="gold", alpha=0.6)
# EXERCISE: use grid(), axis(), etc. to style the plot. Some suggestions:
def bokeh_plot(u, t, legends, I, w, t_range, filename):
"""
Make plots for u vs t using the Bokeh library.
u and t are lists (several experiments can be compared).
legens contain legend strings for the various u,t pairs.
"""
if not isinstance(u, (list,tuple)):
u = [u] # wrap in list
if not isinstance(t, (list,tuple)):
t = [t] # wrap in list
if not isinstance(legends, (list,tuple)):
legends = [legends] # wrap in list
import bokeh.plotting as plt
plt.output_file(filename, mode='cdn', title='Comparison')
# Assume that all t arrays have the same range
t_fine = np.linspace(0, t[0][-1], 1001) # fine mesh for u_e
tools = 'pan,wheel_zoom,box_zoom,reset,'\
'save,box_select,lasso_select'
u_range = [-1.2*I, 1.2*I]
font_size = '8pt'
p = [] # list of plot objects
# Make the first figure
p_ = plt.figure(
width=300, plot_height=250, title=legends[0],
x_axis_label='t', y_axis_label='u',
x_range=t_range, y_range=u_range, tools=tools,
title_text_font_size=font_size)
p_.xaxis.axis_label_text_font_size=font_size
p_.yaxis.axis_label_text_font_size=font_size
p_.line(t[0], u[0], line_color='blue')
df = summarize_grant(group_grant_df, dedupe_id=args.index, grant_type=grant_type).fillna('')
x = 'year'
y = 'n_grants'
val = 'amount'
f = figure(
width=args.width,
height=args.height,
title=affiliation_dict[args.index].title(),
y_axis_type="log",
x_axis_label="year",
x_range=[1970, 2020],
y_range=[np.min(df[y])-5, np.max(df[y])*2],
y_axis_label="Number of grants",
tools = "save"
)
output_file(args.output)
if len(df) == 0:
print("no grants found for this dedupe index...")
else:
fig = scatter_with_hover(df, x, y, fig=f, marker='o', cols=[x, y, val])
show(fig)
def main():
nodes = pd.read_table('../data/KDFW/nodes.txt', comment='#', header=None)
nodes.columns = ['x', 'y', 'ind', 'name', 'type', 'to', 'from']
nodes.reset_index('ind', inplace=True)
nodes.dropna(inplace=True)
nodes[['x', 'y']] = nodes[['x', 'y']].astype(float).astype(int)
nodes['color'] = 'teal'
links = pd.read_table('../data/KDFW/links.txt', comment='#', header=None)
links.dropna(inplace=True)
links[[0, 1, 2]] = links[[0, 1, 2]].astype(int)
# initialize plot
plt.output_file("KDFW_Map_Viewer.html")
tools = "pan,wheel_zoom,box_zoom,reset,hover,previewsave"
plt.figure(title='', tools=tools, x_range=[-1000, 1000], y_range=[-500, 1500], plot_width=1200, plot_height=1200)
plt.hold()
lx, ly = [], []
for i in range(len(links)):
n1 = nodes.loc[links.iloc[i, 1], :]
n2 = nodes.loc[links.iloc[i, 2], :]
lx.append([n1.x, n2.x])
ly.append([n1.y, n2.y])
source = plt.ColumnDataSource(data=nodes)
plt.multi_line(lx, ly, line_width=1.0, color='darkgrey')
plt.scatter('x', 'y', color='color', source=source, fill_alpha=0.5, radius=5)
a = nodes.to_dict('list')
plt.text(a['x'], a['y'], text=a['ind'], angle=0, text_font_size='8pt')
def graph_bgp(label_dict, redundancy_counts, x_ticks):
""" graph bgp
the main graphing function used to graph the given dataset
we will be graphing this two ways - full and downsampled
for computers that cannot handle the full graph, please use the downsampled
data set in order to see the graph without hassle """
# define output html file
output_file("bgpgraph.html")
# define the figure initial parameters
p = figure(
title="INTERNET'S REDUNDANCY", # title
toolbar_location="above", # toolbar location
sizing_mode='stretch_both', # sizing parameters of the graph
output_backend="webgl", # allows us to utilize webgl to reduce load
)
# draw circles with size 1, color navy, and semi transparent for each datapoint
p.circle(x_ticks, redundancy_counts, size=1, color="navy", alpha=0.5)
# x axis label
p.xaxis.axis_label = 'IPv4 Routes'
# y axis label
def visualize_hidden_activations(model, example_fname, out="activations.html"):
bokeh.plotting.output_file(out, title="Hidden activations - {}".format(model.name))
figures = []
n = 300 # TODO: make configurable
vecs = common.vectors_from_txtfile(example_fname, model.codec, limit=n)
for n_gibbs in [0, 5, 1000]:
if n_gibbs > 0:
vecs = model.repeated_gibbs(vecs, n_gibbs)
# TODO: Visualize hidden probabilities to avoid sampling noise? Should at least offer option
hiddens = model._sample_hiddens(vecs)
y, x = np.nonzero(hiddens)
max_y, max_x = hiddens.shape
hidden_counts = np.sum(hiddens, axis=0)
n_dead = (hidden_counts == 0).sum()
n_immortal = (hidden_counts == n).sum()
p = bokeh.plotting.figure(title="After {} rounds of Gibbs sampling. Dead = {}. Immortal = {}".format(n_gibbs, n_dead, n_immortal),
x_axis_location="above", x_range=(0,hiddens.shape[1]), y_range=(0,hiddens.shape[0])
)
def save_plot(plot, title, suffix, output):
if output:
filename = '{}-{}.html'.format(output, suffix)
print('Saving plot to {}'.format(filename))
bokeh.plotting.output_file(filename, title=title, mode='inline')
bokeh.plotting.save(plot)
else:
bokeh.plotting.show(plot)
def update_graphs(project_code, html_path):
pd.set_option('display.width', 1800)
html_path = op.join(html_path, "{0}.html".format(project_code))
qc_path = op.dirname(op.abspath(__file__))
commands_dir = op.dirname(qc_path)
root_dir = op.dirname(commands_dir)
log_dir = op.join(root_dir, "logs")
csv_path = op.join(log_dir, project_code + ".csv")
csv = pd.read_csv(csv_path, delimiter=";")
csv.timeStamp = pd.to_datetime(csv.timeStamp)
output_file(html_path, mode="inline")
topics = {"q_": "QC",
"l_": "LINKS",
"g_": "GROUPS",
"v_": "VIEWS",
"d_": "2D",
"s_": "STYLES",
"e_": "ELEMENTS",
"m_": "PROJECT_SQM",
}
graphs = graph(csv, project_code, topics)
save(column(graphs), validate=False)
print(colorful.bold_green(f" {html_path} updated successfully."))
factors = ["foo 123", "bar:0.2", "baz-10"]
x = ["foo 123", "foo 123", "foo 123", "bar:0.2", "bar:0.2", "bar:0.2", "baz-10", "baz-10", "baz-10"]
y = ["foo 123", "bar:0.2", "baz-10", "foo 123", "bar:0.2", "baz-10", "foo 123", "bar:0.2", "baz-10"]
colors = [
"#0B486B", "#79BD9A", "#CFF09E",
"#79BD9A", "#0B486B", "#79BD9A",
"#CFF09E", "#79BD9A", "#0B486B"
]
hm = figure(title="Categorical Heatmap", tools="hover", toolbar_location=None,
x_range=factors, y_range=factors)
hm.rect(x, y, color=colors, width=1, height=1)
output_file("categorical.html", title="categorical.py example")
show(row(hm, dot, sizing_mode="scale_width")) # open a browser