Python bokeh.plotting.show() Examples
The following are 30
code examples of bokeh.plotting.show().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
bokeh.plotting
, or try the search function
.
Example #1
Source File: plots.py From autogluon with Apache License 2.0 | 6 votes |
def plot_performance_vs_trials(results, output_directory, save_file="PerformanceVsTrials.png", plot_title=""): try: import matplotlib.pyplot as plt matplotlib_imported = True except ImportError: matplotlib_imported = False if not matplotlib_imported: warnings.warn('AutoGluon summary plots cannot be created because matplotlib is not installed. Please do: "pip install matplotlib"') return None ordered_trials = sorted(list(results['trial_info'].keys())) ordered_val_perfs = [results['trial_info'][trial_id][results['reward_attr']] for trial_id in ordered_trials] x = range(1, len(ordered_trials)+1) y = [] for i in x: y.append(max([ordered_val_perfs[j] for j in range(i)])) # best validation performance in trials up until ith one (assuming higher = better) fig, ax = plt.subplots() ax.plot(x, y) ax.set(xlabel='Completed Trials', ylabel='Best Performance', title = plot_title) if output_directory is not None: outputfile = os.path.join(output_directory, save_file) fig.savefig(outputfile) print("Plot of HPO performance saved to file: %s" % outputfile) plt.show()
Example #2
Source File: viz2.py From scipy2015-blaze-bokeh with MIT License | 6 votes |
def timeseries(): # Get data df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv') df['datetime'] = pd.to_datetime(df['datetime']) df = df[['anomaly','datetime']] df['moving_average'] = pd.rolling_mean(df['anomaly'], 12) df = df.fillna(0) # List all the tools that you want in your plot separated by comas, all in one string. TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave" # New figure t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS) # Data processing # The hover tools doesn't render datetime appropriately. We'll need a string. # We just want dates, remove time f = lambda x: str(x)[:7] df["datetime_s"]=df[["datetime"]].applymap(f) source = ColumnDataSource(df) # Create plot t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source) t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva") # Style xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"])) t.xaxis[0].formatter = xformatter t.xaxis.major_label_orientation = math.pi/4 t.yaxis.axis_label = 'Anomaly(ºC)' t.legend.orientation = "bottom_right" t.grid.grid_line_alpha=0.2 t.toolbar_location=None # Style hover tool hover = t.select(dict(type=HoverTool)) hover.tooltips = """ <div> <span style="font-size: 15px;">Anomaly</span> <span style="font-size: 17px; color: red;">@anomaly</span> </div> <div> <span style="font-size: 15px;">Month</span> <span style="font-size: 10px; color: grey;">@datetime_s</span> </div> """ hover.renderers = t.select("mva") # Show plot #show(t) return t # Add title
Example #3
Source File: plot.py From umap with BSD 3-Clause "New" or "Revised" License | 6 votes |
def show(plot_to_show): """Display a plot, either interactive or static. Parameters ---------- plot_to_show: Output of a plotting command (matplotlib axis or bokeh figure) The plot to show Returns ------- None """ if isinstance(plot_to_show, plt.Axes): show_static() elif isinstance(plot_to_show, bpl.Figure): show_interactive(plot_to_show) else: raise ValueError( "The type of ``plot_to_show`` was not valid, or not understood." )
Example #4
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 5 votes |
def jitterCurve(phmi_breakPtsNeg,landmarks_coordi,PHMI_coordi,plot_x): #LandmarkMap_dic,PHMI_dic output_file("PHmi_01.html") source=ColumnDataSource(data=dict( x=landmarks_coordi[0].tolist(), y=landmarks_coordi[1].tolist(), desc=[str(i) for i in list(range(landmarks_coordi[0].shape[0]))], )) TOOLTIPS=[ ("index", "$index"), ("(x,y)", "($x, $y)"), ("desc", "@desc"), ] p=figure(plot_width=1800, plot_height=320, tooltips=TOOLTIPS,title="partition") p.circle('y','x', size=5, source=source) p.line(PHMI_coordi[1],PHMI_coordi[0],line_color="coral", line_dash="dotdash", line_width=2) colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen') colors=colors*5 ScalePhmi=math.pow(10,1) i=0 for val,idx in zip(phmi_breakPtsNeg, plot_x): p.line(idx,np.array(val)*ScalePhmi,line_color=colors[i]) i+=1 show(p) #04-network show between PHMI and landmarks 网络分析 #extract landmarks corresponding to the AVs' position along a route
Example #5
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 5 votes |
def singleBoxplot(array): import plotly.express as px import pandas as pd df=pd.DataFrame(array,columns=["value"]) fig = px.box(df, y="value",points="all") # fig.show() #show in Jupyter import plotly plotly.offline.plot (fig) #works in spyder #03-split curve into continuous parts based on the jumping position 使用1维卷积的方法,在曲线跳变点切分曲线
Example #6
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 5 votes |
def colorMeshShow(histogram2dDic_part,patternDic_part,Phmi_part,condi): use_svg_display() xiArray=np.array([histogram2dDic_part[key]["xi"].tolist() for key in histogram2dDic_part.keys()]) yiArray=np.array([histogram2dDic_part[key]["yi"].tolist() for key in histogram2dDic_part.keys()]) ziArray=np.array([histogram2dDic_part[key]["ziMasked"].tolist() for key in histogram2dDic_part.keys()]) xArray=np.array([patternDic_part[key]["x"].tolist() for key in patternDic_part.keys()]) yArray=np.array([patternDic_part[key]["y"].tolist() for key in patternDic_part.keys()]) zArray=np.array([patternDic_part[key]["z"] for key in patternDic_part.keys()]) # print(xiArray) width=int(round(math.sqrt(len(xArray)),2)) # print("+"*50) # print(width) fig, axs = plt.subplots(width, width, figsize=(10, 10),constrained_layout=True) for ax, xi, yi, zi, x, y,z,titleV,key in zip(axs.flat, xiArray,yiArray,ziArray,xArray, yArray,zArray,Phmi_part,condi): ax.pcolormesh(xi, yi, zi, edgecolors='black') scat = ax.scatter(x, y, c="r", s=15) #c=z fig.colorbar(scat) ax.margins(0.05) ax.set_title("PHmi_%d:%f"%(key,titleV)) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) plt.show()
Example #7
Source File: showMatLabFig._spatioTemporal.py From python-urbanPlanning with MIT License | 5 votes |
def colorMeshShow(histogram2dDic_part,patternDic_part,Phmi_part,condi): use_svg_display() xiArray=np.array([histogram2dDic_part[key]["xi"].tolist() for key in histogram2dDic_part.keys()]) yiArray=np.array([histogram2dDic_part[key]["yi"].tolist() for key in histogram2dDic_part.keys()]) ziArray=np.array([histogram2dDic_part[key]["ziMasked"].tolist() for key in histogram2dDic_part.keys()]) xArray=np.array([patternDic_part[key]["x"].tolist() for key in patternDic_part.keys()]) yArray=np.array([patternDic_part[key]["y"].tolist() for key in patternDic_part.keys()]) zArray=np.array([patternDic_part[key]["z"] for key in patternDic_part.keys()]) # print(xiArray) width=int(round(math.sqrt(len(xArray)),2)) # print("+"*50) # print(width) fig, axs = plt.subplots(width, width, figsize=(10, 10),constrained_layout=True) for ax, xi, yi, zi, x, y,z,titleV,key in zip(axs.flat, xiArray,yiArray,ziArray,xArray, yArray,zArray,Phmi_part,condi): ax.pcolormesh(xi, yi, zi, edgecolors='black') scat = ax.scatter(x, y, c="r", s=15) #c=z fig.colorbar(scat) ax.margins(0.05) ax.set_title("PHmi_%d:%f"%(key,titleV)) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) plt.show() #07相关性分析 #classification PHMI with percentile
Example #8
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 5 votes |
def readMatLabFig_LandmarkMap(LandmarkMap_fn): LandmarkMap=loadmat(LandmarkMap_fn, squeeze_me=True, struct_as_record=False) y=loadmat(LandmarkMap_fn) print(sorted(LandmarkMap.keys())) LandmarkMap_dic={} #提取.fig值 for object_idx in range(LandmarkMap['hgS_070000'].children.children.shape[0]): # print(object_idx) try: X=LandmarkMap['hgS_070000'].children.children[object_idx].properties.XData #good Y=LandmarkMap['hgS_070000'].children.children[object_idx].properties.YData LandmarkMap_dic[object_idx]=(X,Y) except: pass # print(LandmarkMap_dic) fig= plt.figure(figsize=(130,20)) colors=['#7f7f7f','#d62728','#1f77b4','','',''] markers=['.','+','o','','',''] dotSizes=[200,3000,3000,0,0,0] linewidths=[2,10,10,0,0,0] i=0 for key in LandmarkMap_dic.keys(): plt.scatter(LandmarkMap_dic[key][1],LandmarkMap_dic[key][0], s=dotSizes[i],marker=markers[i], color=colors[i],linewidth=linewidths[i]) i+=1 plt.tick_params(axis='both',labelsize=80) plt.show() return LandmarkMap_dic #02-read PHMI values for evaluation of AVs' on-board lidar navigation 读取PHMI值 #the PHMI value less than pow(10,-5) is scaled to show clearly------on; the PHMI value larger than pow(10,-5) is scaled to show clearly------on #数据类型A
Example #9
Source File: showMatLabFig._spatioTemporal.py From python-urbanPlanning with MIT License | 5 votes |
def location_landmarks_network(targetPts_idx,locations,landmarks): LMs=np.stack((landmarks[0], landmarks[1]), axis=-1) LCs=np.stack((locations[0], locations[1]), axis=-1) ptsMerge=np.vstack((LMs,LCs)) print("LMs shape:%s, LCs shaoe:%s, ptsMerge shape:%s"%(LMs.shape, LCs.shape,ptsMerge.shape)) targetPts_idx_adj={} for key in targetPts_idx.keys(): targetPts_idx_adj[key+LMs.shape[0]]=targetPts_idx[key] edges=[[(key,i) for i in targetPts_idx_adj[key]] for key in targetPts_idx_adj.keys()] edges=flatten_lst(edges) G=nx.Graph() G.position={} # G.targetPtsNum={} i=0 for pts in ptsMerge: G.add_node(i) G.position[i]=(pts[1],pts[0]) # G.targetPtsNum[LM]=(len(targetPts[key])) i+=1 G.add_edges_from(edges) plt.figure(figsize=(130,20)) nx.draw(G,G.position,linewidths=1,edge_color='gray') plt.show() return G #网络交互图表
Example #10
Source File: plot_history.py From tick with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_bokeh_history(solvers, x, y, x_arrays, y_arrays, mins, legends, log_scale, show): import bokeh.plotting as bk min_x, max_x, min_y, max_y = mins if log_scale: # Bokeh has a weird behaviour when using logscale with 0 entries... # We use the difference between smallest value of second small # to set the range of y all_ys = np.hstack(y_arrays) y_range_min = np.min(all_ys[all_ys != 0]) if y_range_min < 0: raise ValueError("Cannot plot negative values on a log scale") fig = bk.Figure(plot_height=300, y_axis_type="log", y_range=[y_range_min, max_y]) else: fig = bk.Figure(plot_height=300, x_range=[min_x, max_x], y_range=[min_y, max_y]) for i, (solver, x_array, y_array, legend) in enumerate( zip(solvers, x_arrays, y_arrays, legends)): color = get_plot_color(i) fig.line(x_array, y_array, line_width=3, legend=legend, color=color) fig.xaxis.axis_label = x fig.yaxis.axis_label = y fig.xaxis.axis_label_text_font_size = "12pt" fig.yaxis.axis_label_text_font_size = "12pt" if show: bk.show(fig) return None else: return fig
Example #11
Source File: showMatLabFig._spatioTemporal.py From python-urbanPlanning with MIT License | 5 votes |
def singleBoxplot(array): import plotly.express as px import pandas as pd df=pd.DataFrame(array,columns=["value"]) fig = px.box(df, y="value",points="all") # fig.show() #show in Jupyter import plotly plotly.offline.plot (fig) #works in spyder #04-split curve into continuous parts based on the jumping position 使用1维卷积的方法,在曲线跳变点切分曲线
Example #12
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 5 votes |
def singleBoxplot(array): import plotly.express as px import pandas as pd df=pd.DataFrame(array,columns=["value"]) fig = px.box(df, y="value",points="all") # fig.show() #show in Jupyter import plotly plotly.offline.plot (fig) #works in spyder #03-split curve into continuous parts based on the jumping position 使用1维卷积的方法,在曲线跳变点切分曲线
Example #13
Source File: showMatLabFig._spatioTemporal.py From python-urbanPlanning with MIT License | 5 votes |
def readMatLabFig_LandmarkMap(LandmarkMap_fn): LandmarkMap=loadmat(LandmarkMap_fn, squeeze_me=True, struct_as_record=False) y=loadmat(LandmarkMap_fn) print(sorted(LandmarkMap.keys())) LandmarkMap_dic={} #提取.fig值 for object_idx in range(LandmarkMap['hgS_070000'].children.children.shape[0]): # print(object_idx) try: X=LandmarkMap['hgS_070000'].children.children[object_idx].properties.XData #good Y=LandmarkMap['hgS_070000'].children.children[object_idx].properties.YData LandmarkMap_dic[object_idx]=(X,Y) except: pass # print(LandmarkMap_dic) fig= plt.figure(figsize=(130,20)) colors=['#7f7f7f','#d62728','#1f77b4','','',''] markers=['.','+','o','','',''] dotSizes=[200,3000,3000,0,0,0] linewidths=[2,10,10,0,0,0] i=0 for key in LandmarkMap_dic.keys(): plt.scatter(LandmarkMap_dic[key][1],LandmarkMap_dic[key][0], s=dotSizes[i],marker=markers[i], color=colors[i],linewidth=linewidths[i]) i+=1 plt.tick_params(axis='both',labelsize=80) plt.show() return LandmarkMap_dic #03-read PHMI values for evaluation of AVs' on-board lidar navigation 读取PHMI值 #the PHMI value less than pow(10,-5) is scaled to show clearly------on; the PHMI value larger than pow(10,-5) is scaled to show clearly------on #数据类型A
Example #14
Source File: ABuMarketDrawing.py From abu with GNU General Public License v3.0 | 5 votes |
def plot_simple_two_stock(two_stcok_dict): """ 将两个金融时间序列收盘价格缩放到一个价格水平后,可视化价格变动 :param two_stcok_dict: 字典形式,key将做为lable进行可视化使用,元素为金融时间序列 """ if not isinstance(two_stcok_dict, dict) or len(two_stcok_dict) != 2: print('two_stcok_dict type must dict! or len(two_stcok_dict) != 2') return label_arr = [s_name for s_name in two_stcok_dict.keys()] x, y = ABuScalerUtil.scaler_xy(two_stcok_dict[label_arr[0]].close, two_stcok_dict[label_arr[1]].close) plt.plot(x, label=label_arr[0]) plt.plot(y, label=label_arr[1]) plt.legend(loc=2) plt.show()
Example #15
Source File: ABuMarketDrawing.py From abu with GNU General Public License v3.0 | 5 votes |
def plot_simple_multi_stock(multi_kl_pd): """ 将多个金融时间序列收盘价格缩放到一个价格水平后,可视化价格变动 :param multi_kl_pd: 可迭代的序列,元素为金融时间序列 """ rg_ret = ABuScalerUtil.scaler_matrix([kl_pd.close for kl_pd in multi_kl_pd]) for i, kl_pd in enumerate(multi_kl_pd): plt.plot(kl_pd.index, rg_ret[i]) plt.show()
Example #16
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 5 votes |
def jitterCurve(phmi_breakPtsNeg,landmarks_coordi,PHMI_coordi,plot_x): #LandmarkMap_dic,PHMI_dic output_file("PHmi_01.html") source=ColumnDataSource(data=dict( x=landmarks_coordi[0].tolist(), y=landmarks_coordi[1].tolist(), desc=[str(i) for i in list(range(landmarks_coordi[0].shape[0]))], )) TOOLTIPS=[ ("index", "$index"), ("(x,y)", "($x, $y)"), ("desc", "@desc"), ] p=figure(plot_width=1800, plot_height=320, tooltips=TOOLTIPS,title="partition") p.circle('y','x', size=5, source=source) p.line(PHMI_coordi[1],PHMI_coordi[0],line_color="coral", line_dash="dotdash", line_width=2) colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen') colors=colors*5 ScalePhmi=math.pow(10,1) i=0 for val,idx in zip(phmi_breakPtsNeg, plot_x): p.line(idx,np.array(val)*ScalePhmi,line_color=colors[i]) i+=1 show(p) #04-network show between PHMI and landmarks 网络分析 #extract landmarks corresponding to the AVs' position along a route
Example #17
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 5 votes |
def colorMeshShow(histogram2dDic_part,patternDic_part,Phmi_part,condi): use_svg_display() xiArray=np.array([histogram2dDic_part[key]["xi"].tolist() for key in histogram2dDic_part.keys()]) yiArray=np.array([histogram2dDic_part[key]["yi"].tolist() for key in histogram2dDic_part.keys()]) ziArray=np.array([histogram2dDic_part[key]["ziMasked"].tolist() for key in histogram2dDic_part.keys()]) xArray=np.array([patternDic_part[key]["x"].tolist() for key in patternDic_part.keys()]) yArray=np.array([patternDic_part[key]["y"].tolist() for key in patternDic_part.keys()]) zArray=np.array([patternDic_part[key]["z"] for key in patternDic_part.keys()]) # print(xiArray) width=int(round(math.sqrt(len(xArray)),2)) # print("+"*50) # print(width) fig, axs = plt.subplots(width, width, figsize=(10, 10),constrained_layout=True) for ax, xi, yi, zi, x, y,z,titleV,key in zip(axs.flat, xiArray,yiArray,ziArray,xArray, yArray,zArray,Phmi_part,condi): ax.pcolormesh(xi, yi, zi, edgecolors='black') scat = ax.scatter(x, y, c="r", s=15) #c=z fig.colorbar(scat) ax.margins(0.05) ax.set_title("PHmi_%d:%f"%(key,titleV)) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) plt.show()
Example #18
Source File: viz.py From scipy2015-blaze-bokeh with MIT License | 5 votes |
def timeseries(): # Get data df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv') df['datetime'] = pd.to_datetime(df['datetime']) df = df[['anomaly','datetime']] df['moving_average'] = pd.rolling_mean(df['anomaly'], 12) df = df.fillna(0) # List all the tools that you want in your plot separated by comas, all in one string. TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave" # New figure t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS) # Data processing # The hover tools doesn't render datetime appropriately. We'll need a string. # We just want dates, remove time f = lambda x: str(x)[:7] df["datetime_s"]=df[["datetime"]].applymap(f) source = ColumnDataSource(df) # Create plot t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source) t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva") # Style xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"])) t.xaxis[0].formatter = xformatter t.xaxis.major_label_orientation = math.pi/4 t.yaxis.axis_label = 'Anomaly(ºC)' t.legend.orientation = "bottom_right" t.grid.grid_line_alpha=0.2 t.toolbar_location=None # Style hover tool hover = t.select(dict(type=HoverTool)) hover.tooltips = """ <div> <span style="font-size: 15px;">Anomaly</span> <span style="font-size: 17px; color: red;">@anomaly</span> </div> <div> <span style="font-size: 15px;">Month</span> <span style="font-size: 10px; color: grey;">@datetime_s</span> </div> """ hover.renderers = t.select("mva") # Show plot #show(t) return t
Example #19
Source File: plot.py From arlpy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _show(f): if _figures is None: if _static_images: _show_static_images(f) else: _process_canvas([]) _bplt.show(f) _process_canvas([f]) else: _figures[-1].append(f)
Example #20
Source File: plot.py From arlpy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __exit__(self, *args): global _figures, _figsize if len(_figures) > 1 or len(_figures[0]) > 0: f = _bplt.gridplot(_figures, merge_tools=False) if _static_images: _show_static_images(f) else: _process_canvas([]) _bplt.show(f) _process_canvas([item for sublist in _figures for item in sublist]) _figures = None _figsize = self.ofigsize
Example #21
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 5 votes |
def location_landmarks_network(targetPts_idx,locations,landmarks): LMs=np.stack((landmarks[0], landmarks[1]), axis=-1) LCs=np.stack((locations[0], locations[1]), axis=-1) ptsMerge=np.vstack((LMs,LCs)) print("LMs shape:%s, LCs shaoe:%s, ptsMerge shape:%s"%(LMs.shape, LCs.shape,ptsMerge.shape)) targetPts_idx_adj={} for key in targetPts_idx.keys(): targetPts_idx_adj[key+LMs.shape[0]]=targetPts_idx[key] edges=[[(key,i) for i in targetPts_idx_adj[key]] for key in targetPts_idx_adj.keys()] edges=flatten_lst(edges) G=nx.Graph() G.position={} # G.targetPtsNum={} i=0 for pts in ptsMerge: G.add_node(i) G.position[i]=(pts[1],pts[0]) # G.targetPtsNum[LM]=(len(targetPts[key])) i+=1 G.add_edges_from(edges) plt.figure(figsize=(130,20)) nx.draw(G,G.position,linewidths=1,edge_color='gray') plt.show() return G #网络交互图表
Example #22
Source File: __init__.py From arviz with Apache License 2.0 | 5 votes |
def show_layout(ax, show=True, force_layout=False): """Create a layout and call bokeh show.""" if show is None: show = rcParams["plot.bokeh.show"] if show: import bokeh.plotting as bkp layout = create_layout(ax, force_layout=force_layout) bkp.show(layout)
Example #23
Source File: utils.py From dynamo-release with BSD 3-Clause "New" or "Revised" License | 5 votes |
def despline(ax=None): import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax # Hide the right and top spines ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) # Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position("left") ax.xaxis.set_ticks_position("bottom")
Example #24
Source File: some_activities.py From choochoo with GNU General Public License v2.0 | 5 votes |
def some_activities(constraint): f''' # Some Activities: {constraint} This displays thumbnails of routes that match the query over statistics. For example, Active Distance > 40 & Active Distance < 60 will show all activities with a distance between 40 and 60 km. ''' ''' $contents ''' ''' ## Build Maps Loop over activities, retrieve data, and construct maps. ''' s = session('-v2') maps = [map_thumbnail(100, 120, data) for data in (activity_statistics(s, SPHERICAL_MERCATOR_X, SPHERICAL_MERCATOR_Y, ACTIVE_DISTANCE, TOTAL_CLIMB, activity_journal=aj) for aj in constrained_sources(s, constraint)) if len(data[SPHERICAL_MERCATOR_X].dropna()) > 10] print(f'Found {len(maps)} activities') ''' ## Display Maps ''' output_notebook() show(htile(maps, 8))
Example #25
Source File: cost_over_time.py From CAVE with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_jupyter(self): output_notebook() show(self.plot())
Example #26
Source File: ABuMarketDrawing.py From abu with GNU General Public License v3.0 | 5 votes |
def _do_plot_candle_html(date, p_open, high, low, close, symbol, save): """ bk绘制可交互的k线图 :param date: 融时间序列交易日时间,pd.DataFrame.index对象 :param p_open: 金融时间序列开盘价格序列,np.array对象 :param high: 金融时间序列最高价格序列,np.array对象 :param low: 金融时间序列最低价格序列,np.array对象 :param close: 金融时间序列收盘价格序列,np.array对象 :param symbol: symbol str对象 :param save: 是否保存可视化结果在本地 """ mids = (p_open + close) / 2 spans = abs(close - p_open) inc = close > p_open dec = p_open > close w = 24 * 60 * 60 * 1000 t_o_o_l_s = "pan,wheel_zoom,box_zoom,reset,save" p = bp.figure(x_axis_type="datetime", tools=t_o_o_l_s, plot_width=1280, title=symbol) p.xaxis.major_label_orientation = pi / 4 p.grid.grid_line_alpha = 0.3 p.segment(date.to_datetime(), high, date.to_datetime(), low, color="black") # noinspection PyUnresolvedReferences p.rect(date.to_datetime()[inc], mids[inc], w, spans[inc], fill_color=__colorup__, line_color=__colorup__) # noinspection PyUnresolvedReferences p.rect(date.to_datetime()[dec], mids[dec], w, spans[dec], fill_color=__colordown__, line_color=__colordown__) bp.show(p) if save: save_dir = os.path.join(K_SAVE_CACHE_HTML_ROOT, ABuDateUtil.current_str_date()) html_name = os.path.join(save_dir, symbol + ".html") ABuFileUtil.ensure_dir(html_name) bp.output_file(html_name, title=symbol)
Example #27
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 4 votes |
def con_1_dim(data,loc_x): kernel_conv=[-1,2,-1] #卷积核,类似2维提取图像的边缘 result_conv=npConv(data,kernel_conv,'same') plt.figure(figsize=(130, 20)) # print(result_conv) z=np.abs(stats.zscore(result_conv)) z_=stats.zscore(result_conv) # print(z) #print(len(z)) threshold=1 breakPts=np.where(z > threshold) breakPts_=np.where(z_ < -threshold) con_breakPtsNeg=lindexsplit(result_conv.tolist(), breakPts_[0].tolist()) phmi_breakPtsNeg=lindexsplit(data, breakPts_[0].tolist()) phmi_breakIdx=lindexsplit(list(range(len(data))), breakPts_[0].tolist()) x=lindexsplit(loc_x.tolist(),breakPts_[0].tolist()) plt.scatter(loc_x, [abs(v) for v in result_conv],s=1) #[abs(v) for v in discretizeIdx] for idx in range(len(phmi_breakPtsNeg)-1): phmi_breakPtsNeg[idx+1].insert(0,phmi_breakPtsNeg[idx][-1]) phmi_breakPtsNeg.insert(0,phmi_breakPtsNeg[0]) for idx in range(len(phmi_breakIdx)-1): phmi_breakIdx[idx+1].insert(0,phmi_breakIdx[idx][-1]) phmi_breakIdx.insert(0,phmi_breakIdx[0]) for idx in range(len(x)-1): x[idx+1].insert(0,x[idx][-1]) x.insert(0,x[0]) #for val,idx in zip(phmi_breakPtsNeg, phmi_breakIdx): #根据跳变点切分的曲线赋予不同的颜色打印 for val,idx in zip(phmi_breakPtsNeg, x): # print(val,idx) # break # x, y = zip(start, stop) plt.plot(idx, val, color=uniqueish_color()) #plt.scatter(list(range(len(result_conv))), [abs(v) for v in result_conv],s=1) #[abs(v) for v in discretizeIdx] plt.show() return con_breakPtsNeg,phmi_breakPtsNeg,phmi_breakIdx,x #合并landmarks,locations和曲线跳变点切分,打印
Example #28
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 4 votes |
def readMatLabFig_PHMI_A(PHMI_fn,LandmarkMap_dic): PHMI=loadmat(PHMI_fn, squeeze_me=True, struct_as_record=False) x=loadmat(PHMI_fn) print(sorted(PHMI.keys())) PHMI_dic={} #提取MatLab的.fig值 ax1=[c for c in PHMI['hgS_070000'].children if c.type == 'axes'] if(len(ax1) > 0): ax1 = ax1[0] i=0 for line in ax1.children: # print(line) # for object_idx in range(PHMI['hgS_070000'].children.children.shape[0]): # print(object_idx) try: X=line.properties.XData #good Y=line.properties.YData Z=line.properties.ZData PHMI_dic[i]=(X,Y,Z) except: pass i+=1 # print(PHMI2_dic) fig= plt.figure(figsize=(130,20)) #figsize=(20,130) colors=['#7f7f7f','#d62728','#1f77b4','','',''] markers=['.','+','o','','',''] dotSizes=[200,3000,3000,0,0,0] linewidths=[2,10,10,0,0,0] ScalePhmi=math.pow(10,1) plt.plot(PHMI_dic[0][1],PHMI_dic[0][0],marker=markers[0], color=colors[0],linewidth=linewidths[0]) ref=math.pow(10,-5) #for display clearly PHmiValue=PHMI_dic[1][2] replaceValue=np.extract(PHmiValue<ref,PHmiValue)*-math.pow(10,5) PHmiValue[PHmiValue<ref]=replaceValue plt.plot( PHMI_dic[0][1],PHmiValue*ScalePhmi,marker=markers[0], color=colors[1],linewidth=1) # plt.plot(PHMI_dic[1][2]*ScalePhmi, PHMI_dic[0][1],marker=markers[0], color=colors[1],linewidth=1) #plt.axvline(x=ref*ScalePhmi) plt.axhline(y=ref*ScalePhmi) plt.scatter(LandmarkMap_dic[1][1],LandmarkMap_dic[1][0],marker=markers[1], s=dotSizes[1],color=colors[2],linewidth=10) plt.tick_params(axis='both',labelsize=80) plt.show() return PHMI_dic #数据类型B
Example #29
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 4 votes |
def interactiveG(G): from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider from bokeh.plotting import figure, output_file, show, ColumnDataSource from bokeh.io import output_notebook, show output_notebook() # We could use figure here but don't want all the axes and titles #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1)) output_file("PHMI_network") source=ColumnDataSource(data=dict( x=locations[0].tolist(), #x=[idx for idx in range(len(PHMIList))], #y=locations[1].tolist(), y=PHMIList, #desc=[str(i) for i in PHMIList], #PHMI_value=PHMI_dic[0][0].tolist(), )) TOOLTIPS=[ ("index", "$index"), ("(x,y)", "($x, $y)"), #("desc", "@desc"), #("PHMI", "$PHMI_value"), ] plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network") #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()} graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0)) #plot.renderers.append(graph) fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position) graph.layout_provider = fixed_layout_provider plot.renderers.append(graph) # Blue circles for nodes, and light grey lines for edges graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba') graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2) # green hover for both nodes and edges graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4') graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4) # When we hover over nodes, highlight adjecent edges too graph.inspection_policy = NodesAndLinkedEdges() plot.add_tools(HoverTool(tooltips=None)) colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen') ScalePhmi=math.pow(10,1) i=0 for val,idx in zip(phmi_breakPtsNeg, plot_x): plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i]) i+=1 show(plot) #05-single landmarks pattern 无人车位置点与对应landmarks栅格图 #convert location and corresponding landmarks to raster data format using numpy.histogram2d
Example #30
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py From python-urbanPlanning with MIT License | 4 votes |
def colorMesh_phmi(landmarks,locations,targetPts_idx,Phmi): patternValuesDic={} for key in targetPts_idx.keys(): patternValuesDic[key]=[0.5]*len(targetPts_idx[key]) patternValuesDic[key].append(0.9) patternDic={} for key in patternValuesDic.keys(): patternDic[key]={"x":landmarks[0][targetPts_idx[key]], "y":landmarks[1][targetPts_idx[key]], "z":patternValuesDic[key] } patternDic[key]["x"]=np.append(patternDic[key]["x"],locations[0][key]) patternDic[key]["y"]=np.append(patternDic[key]["y"],locations[1][key]) histogram2dDic={} binNumber=(32,32) #32,25,68,70 for key in patternDic.keys(): zi, yi, xi = np.histogram2d(patternDic[key]["y"], patternDic[key]["x"], bins=binNumber, weights=patternDic[key]["z"], normed=False) counts, _, _ = np.histogram2d(patternDic[key]["y"], patternDic[key]["x"],bins=binNumber) # print(counts) histogram2dDic[key]={"xi":xi,"yi":yi,"zi":zi,"count":counts,"ziCount":zi / counts,"ziMasked":np.ma.masked_invalid(zi)} for key in histogram2dDic.keys(): xi=histogram2dDic[key]["xi"] yi=histogram2dDic[key]["yi"] zi=histogram2dDic[key]["ziMasked"] x=patternDic[key]["x"] y=patternDic[key]["y"] z=patternDic[key]["z"] # print(x,y,z) #plot it ''' fig, ax = plt.subplots(figsize=(25,20)) ax.pcolormesh(xi, yi, zi, edgecolors='black') scat = ax.scatter(x, y, c=z, s=30) fig.colorbar(scat) ax.margins(0.05) plt.title("PHmi_%d:%f"%(key,Phmi[key])) plt.show() if key==20: break ''' return histogram2dDic,patternDic #show raster