def plotScatter3D(df, mytitle, allDict, notebook=True): import plotly import plotly.graph_objs as go statTooltips = [] doctopics = [] docdates = [] for key in df.index: try: statTooltips.append(tooltipText(allDict[key])) except: print(key, "not found") colorDropdown = widgets.Dropdown(description='Topics:', value=df["specGroup"][0], options=df["specGroup"]) trace = go.Scatter3d( x=df['pca-one'], y=df['pca-two'], z=df['pca-three'], mode='markers', marker=dict( size=df["size"], color=df["specGroup"], colorscale='Viridis', colorbar=dict(title="Topic<br>Relevance"), # symbol=df["specGroup"], # TODO actually want Feedname showscale=True, opacity=0.6), # symbol=df["specGroup"], text=statTooltips, textfont=dict(family="sans serif", size=8, color='crimson'), hoverinfo='text') # Configure the layout. # layout = go.Layout(margin={'l': 0, 'r': 0, 'b': 0, 't': 0}) layout = go.Layout(showlegend=False, title=mytitle, margin={ 'l': 0, 'r': 0, 'b': 50, 't': 30 }, scene=go.Scene( xaxis=go.XAxis(title='PCA Dimension<br>Reduced X'), yaxis=go.YAxis(title='PCA Dimension<br>Reduced Y'), zaxis=go.ZAxis(title='PCA Dimension<br>Reduced Z'))) data = [trace] plot_figure = go.Figure(data=data, layout=layout) camera = dict(eye=dict(x=1.5, y=1.5, z=0.1)) plot_figure.update_layout(scene_camera=camera) # plt.tight_layout() # Render the plot. pl = plotly.offline.iplot(plot_figure) pl if not notebook: plotly.offline.plot(plot_figure, filename='file.html') return trace
def plot3Dgraph(self, fig, x, y, z): import plotly.graph_objs as go surface = go.Surface(x=x, y=y, z=z) data = go.Data([surface]) layout = go.Layout( title='Parametric Plot', scene=go.Scene(xaxis=go.XAxis(gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)'), yaxis=go.YAxis(gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)'), zaxis=go.ZAxis( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)'))) fig = go.Figure(data=data, layout=go.Layout(title='Offline Plotly Testing', width=800, height=500, xaxis=dict(title='X-axis'), yaxis=dict(title='Y-axis'))) plot(fig, show_link=False)
def cluster_test(): dataSet = getDataSetFromDatabase() labels = cluster(dataSet) # transpose to work with Plotly-format (don't remember if it is sklear.cluster or plotly that is counterintuitive) dataToChart = dataSet.transpose() # create multi dimensional array of data by label segmentedData = [[[] for _ in xrange(3)] for _ in xrange(numClusters)] for num, label in enumerate(labels): print (str(num) + ' ' + str(label)) segmentedData[label][0].append(dataToChart[0][num]) segmentedData[label][1].append(dataToChart[1][num]) segmentedData[label][2].append(dataToChart[2][num]) if debug: print(segmentedData) # create traces for plotly traces = [] baseColor = 100 i = 0 while i < numClusters: trace = go.Scatter3d( x=segmentedData[i][0], y=segmentedData[i][1], z=segmentedData[i][2], mode='markers', marker=dict( size=12, line=dict( color='rgba(baseColor+(i*2), baseColor+(i*2), baseColor+(i*2), 0.14)', width=0.5 ), opacity=0.8 ), # @todo: fix names list for plotly #text=names ) traces.append(trace) i+=1 layout = go.Layout( scene=go.Scene( xaxis=go.XAxis(title='Carbs', tickprefix='Carbs ', showtickprefix='first'), yaxis=go.YAxis(title='Fat', tickprefix='Fat ', showtickprefix='first'), zaxis=go.ZAxis(title='Protein', tickprefix='Protein ', showtickprefix='first') ), height = 800, width = 800, ) fig = go.Figure(data=traces, layout=layout) graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template('cluster-test.html', graphJSON=graphJSON)
def production_envelope_3d(self, dataframe, grid=None, width=None, height=None, title=None, points=None, points_colors=None, palette=None, x_axis_label=None, y_axis_label=None, z_axis_label=None): variables = dataframe["strain"].unique() palette = self.get_option('palette') if palette is None else palette width = self.get_option('width') if width is None else width width, height = self.golden_ratio(width, height) data = [] palette = self._palette(palette, len(variables)) for variable, color in zip_repeat(variables, palette): _dataframe = dataframe[dataframe["strain"] == variable] surface = self._make_production_envelope_3d(_dataframe, variable, color=color) data.append(surface) if points is not None: x, y, z = zip(*points) scatter = go.Scatter3d( x=x, y=y, z=z, mode="markers", name="Data Points", marker=dict( color="green" if points_colors is None else points_colors)) data.append(scatter) layout = go.Layout(title=title, scene=go.Scene(xaxis=dict(title=x_axis_label), yaxis=dict(title=y_axis_label), zaxis=dict(title=z_axis_label)), width=width, height=height) if grid is not None: plot = self.Figure(data=data, layout=layout) grid.append(plot) return grid else: plot = go.Figure(data=data, layout=layout) return plot
def plotSentiment3D(df2, allDict, notebook=True, topic=""): statTooltips = [] for key in list(df2["UID"]): try: statTooltips.append(tooltipSentiText(allDict[key])) except: print(key, "not found") trace = go.Scatter3d( x=df2['Positive'], y=df2['Negative'], z=df2['Neutral'], mode='markers', marker=dict( size=df2["Topicality"], color=df2['Overall'], colorscale='Inferno', colorbar=dict(title="Compound<br>Sentiment"), # symbol=df["specGroup"], # TODO actually want Feedname showscale=True, opacity=0.7, ), # symbol=df["specGroup"], text=statTooltips, textfont=dict(family="sans serif", size=8, color='crimson'), hoverinfo='text') # Configure the layout. layout = go.Layout(showlegend=False, title="<b>Sentiment Analysis for Topic '" + topic + "'", margin={ 'l': 0, 'r': 0, 'b': 50, 't': 30 }, scene=go.Scene( xaxis=go.XAxis(title='Positive<br>Sentiment'), yaxis=go.YAxis(title='Negative<br>Sentiment'), zaxis=go.ZAxis(title='Neutral<br>Sentiment'))) data = [trace] plot_figure = go.Figure(data=data, layout=layout) camera = dict(eye=dict(x=1.5, y=1.5, z=0.1)) plot_figure.update_layout(scene_camera=camera) #plt.tight_layout() go.FigureWidget(data=data, layout=layout) pl = plotly.offline.iplot(plot_figure) pl if not notebook: plotly.offline.plot(plot_figure, filename='file.html') return
def _getKSDist( ) : # inpt = json.loads( request.args.get( 'inpt' ) ) # do some stuff # inpt = jsonify( result = inpt ) res = getKSDist() x = res[0] y = res[1] z = res[2] print inputdata xp = inputdata[:, 0] yp = inputdata[:, 12] zp = 0.*inputdata[:, 0] surface = go.Surface(x=x, y=y, z=z, opacity=0.95) scatter = go.Scatter3d( x=xp, y=yp, z=zp, mode='markers', marker=dict( size=6, line=dict( color='rgba(217, 217, 217, 0.14)', width=0.5 ), opacity=0.8 ) ) layout = go.Layout( scene=go.Scene( xaxis=dict(title='Day of the Year', range=[100, 350]), yaxis=dict(title='Veg Index Rate of Change ',range=[-0.2, 0.2]) ), title='Probability Density of Vegetative Index vs. Day of the Year' ) fig = go.Figure(data=[surface, scatter], layout=layout) KSDist = plot( fig , output_type='div' , include_plotlyjs=False , show_link=False ) KSDist = Markup( KSDist ) return jsonify( result = KSDist )
def create_standard_layout(title, axis_text): layout = go.Layout( title=title, margin=dict(l=50, r=50, b=50, t=50), scene=go.Scene(xaxis=dict(title=axis_text + ' Stock A', zeroline=True, titlefont=dict(size=14, color='#7f7f7f')), yaxis=dict(title=axis_text + ' Stock B', zeroline=True, titlefont=dict(size=14, color='#7f7f7f')), zaxis=dict(title=axis_text + ' Stock C', zeroline=True, titlefont=dict(size=14, color='#7f7f7f')))) return layout
def show(self, title): figs = [] for ind_f in range(len(self.frames)): (points, triangles, signals) = self.frames[ind_f] points = array(points) triangles = array(triangles) signals = array(signals) signals_per_triangle = list( (signals[triangles[i, 0]] + signals[triangles[i, 1]] + signals[triangles[i, 2]]) / 3 for i in range(triangles.shape[0])) signals_per_triangle[0] += 0.001 # Validate colormap my_colormap = FF._validate_colors("Portland", 'tuple') newdata = FF._trisurf(x=points[:, 2], y=points[:, 0], z=points[:, 1], colormap=my_colormap, simplices=triangles, color_func=signals_per_triangle, plot_edges=False, edges_color='rgb(50, 50, 50)', show_colorbar=False, data_list=True) figs += newdata axis = dict(showbackground=True, backgroundcolor='rgb(230, 230, 230)', gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)') xaxis = axis.copy() xaxis['range'] = [-0.08, 0.09] yaxis = axis.copy() yaxis['range'] = [-0.11, 0.05] zaxis = axis.copy() zaxis['range'] = [0.02, 0.18] aspectratio = dict(x=1, y=1, z=1) layout = graph_objs.Layout(title=title, width='100%', height=800, scene=graph_objs.Scene( xaxis=graph_objs.XAxis(xaxis), yaxis=graph_objs.YAxis(yaxis), zaxis=graph_objs.ZAxis(zaxis), aspectratio=dict(x=aspectratio['x'], y=aspectratio['y'], z=aspectratio['z']), )) return my_iplot(graph_objs.Figure(data=figs, layout=layout))
def build_layout(stnum): """ Build layout for ribbon plot. :param stnum: Student ID number for graph naming. :return: Layout for ribbon plot. """ layout = go.Layout( title='Ribbon Plot of Emotions by Time for Student' + str(stnum), scene=go.Scene( xaxis=dict(title='Emotions'), yaxis=dict(title='Time'), zaxis=dict(title='Emotion Value') ) ) return layout
def plot_reconstruction(vol1, vol2, s=10, c1=(105, 128, 155), c2=(182, 49, 62), show_grid=False): if vol1.dtype != np.bool: vol1 = vol1 > 0 if vol2.dtype != np.bool: vol2 = vol2 > 0 color1 = f'rgb({c1[0]}, {c1[1]}, {c1[2]})' color2 = f'rgb({c2[0]}, {c2[1]}, {c2[2]})' vol2 = np.logical_xor(vol2, vol1) pc1 = volume_to_point_cloud(vol1) pc2 = volume_to_point_cloud(vol2) x1, y1, z1 = zip(*pc1) x2, y2, z2 = zip(*pc2) trace1 = go.Scatter3d(x=x1, y=y1, z=z1, mode='markers', marker=dict(size=s, color=color1, line=dict( color='rgba(217, 217, 217, 0.14)', width=0.5), opacity=1)) trace2 = go.Scatter3d(x=x2, y=y2, z=z2, mode='markers', marker=dict(size=s, color=color2, line=dict( color='rgba(217, 217, 217, 0.14)', width=0.5), opacity=1)) data = [trace1, trace2] layout = go.Layout(margin=dict(l=0, r=0, b=0, t=0), scene=go.Scene(xaxis=dict(visible=show_grid), yaxis=dict(visible=show_grid), zaxis=dict(visible=show_grid)), showlegend=False) fig = go.Figure(data=data, layout=layout) iplot(fig)
def display(m, wireframe=True, smooth=True, data=None): """ The display function shows an interactive presentation of the Manifold, m, inside a Jupyter Notebook. wireframe=True means that a wireframe view of the mesh is superimposed on the 3D model. If smooth=True, the mesh is rendered with vertex normals. Otherwise, the mesh is rendered with face normals. If data=None, the mesh is shown in a light grey color. If data contains an array of scalar values per vertex, these are mapped to colors used to color the mesh.""" xyz = array([p for p in m.positions()]) m_tri = gel.Manifold(m) gel.triangulate(m_tri) ijk = array([[idx for idx in m_tri.circulate_face(f, 'v')] for f in m_tri.faces()]) mesh = go.Mesh3d(x=xyz[:, 0], y=xyz[:, 1], z=xyz[:, 2], i=ijk[:, 0], j=ijk[:, 1], k=ijk[:, 2], color='#dddddd', flatshading=not smooth) if data is not None: mesh['intensity'] = data mesh_data = [mesh] if wireframe: pos = m.positions() xyze = [] for h in m.halfedges(): if h < m.opposite_halfedge(h): p0 = pos[m.incident_vertex(m.opposite_halfedge(h))] p1 = pos[m.incident_vertex(h)] xyze.append(array(p0)) xyze.append(array(p1)) xyze.append(array([None, None, None])) xyze = array(xyze) trace1 = go.Scatter3d(x=xyze[:, 0], y=xyze[:, 1], z=xyze[:, 2], mode='lines', line=go.Line(color='rgb(125,0,0)', width=1), hoverinfo='none') mesh_data += [trace1] lyt = go.Layout(scene=go.Scene(aspectmode='data')) fig = go.Figure(data=mesh_data, layout=lyt) py.iplot(fig)
def plot_3D(feats,color_indexes,colors= {},var_comps= [],Names= [],ref_names= []): if len(colors) == 0: colors= {x:x for x in color_indexes} if len(var_comps) == 0: var_comps= [0 for x in range(feats.shape[1])] if len(Names) == 0: Names= ['ind' + str(x).zfill(int()) for x in range(feats.shape[0])] if len(ref_names) == 0: ref_names= {x:str(x) for x in color_indexes} fig_data= [go.Scatter3d( x = feats[color_indexes[i],0], y = feats[color_indexes[i],1], z = feats[color_indexes[i],2], mode= "markers", name= ref_names[i], text= ['ID: {}, gp: {}'.format(Names[x], ref_names[i]) for x in color_indexes[i]], marker= { 'line': {'width': 0}, 'size': 4, 'symbol': 'circle', 'color': colors[i], "opacity": 1 } ) for i in color_indexes.keys()] layout = go.Layout( scene= go.Scene( yaxis=dict( title='{}'.format(round(var_comps[1],3))), xaxis=dict( title= '{}'.format(round(var_comps[0],3))), zaxis=dict( title= '{}'.format(round(var_comps[2],3)))) ) fig = go.Figure(data=fig_data,layout= layout) iplot(fig)
def plot3D(eigenvectors, pred, infos, label_to_name, node_size=2, opacity=0.9): # copy past from above traces = [] my_axis = dict(showbackground=False, zeroline=False, ticks=False, showgrid=False, showspikes=False, showticklabels=False, showtickprefix=False, showexponent=False) for label in sorted(set(pred)): label_mask = pred == label x = eigenvectors[:, 1][label_mask] y = eigenvectors[:, 2][label_mask] z = eigenvectors[:, 3][label_mask] trace = go.Scatter3d( x=x, y=y, z=z, hoverinfo='text+name', name=label_to_name[label], mode='markers', marker=dict(size=node_size if label < 500 else node_size * 5, color=label, colorscale='Portland', opacity=opacity if label < 500 else 1), text=infos[label_mask]) traces.append(trace) layout = go.Layout(hovermode='closest', margin=dict(l=0, r=0, b=0, t=0), scene=go.Scene( dict(xaxis=my_axis, yaxis=my_axis, zaxis=my_axis))) data = traces fig = go.Figure(data=data, layout=layout) return iplot(fig)
def plot3d(verts, s=10, c=(105, 127, 155), show_grid=False): x, y, z = zip(*verts) color = f'rgb({c[0]}, {c[1]}, {c[2]})' trace = go.Scatter3d(x=x, y=y, z=z, mode='markers', marker=dict(size=s, color=color, line=dict( color='rgba(217, 217, 217, 0.14)', width=0.5), opacity=1)) data = [trace] layout = go.Layout(margin=dict(l=0, r=0, b=0, t=0), scene=go.Scene(xaxis=dict(visible=show_grid), yaxis=dict(visible=show_grid), zaxis=dict(visible=show_grid))) fig = go.Figure(data=data, layout=layout) iplot(fig)
def trace3d(*f): a1 = a2 = np.arange(10, 70, 1) a2t = a2[:, np.newaxis] trace = [] for fnct in f: z = fnct(a1, a2t) trace.append(go.Surface(z=z, x=a1, y=a2)) data = go.Data(trace) axis = dict( showbackground=True, # (!) show axis background backgroundcolor="rgb(204, 204, 204)", # set background color to grey gridcolor="rgb(255, 255, 255)", # set grid line color zerolinecolor="rgb(255, 255, 255)", # set zero grid line color ) layout = go.Layout(scene=go.Scene( xaxis=go.XAxis(axis, title='alpha1'), # set x-axis style yaxis=go.YAxis(axis, title='alpha2'), # set y-axis style zaxis=go.ZAxis(axis, title='Force') # set z-axis style )) fig = go.Figure(data=data, layout=layout) return iplot(fig, filename='s8_surface')
def plotEIH(cycEyeInHead_XYZW, xRange = [-1,1], yRange = [-1,1], zRange = [-1,1], yLim=[0 ,500], width=800, height=600, inline=False): head = createHead() eihDir = go.Scatter3d(x=[0,cycEyeInHead_XYZW[0]], y=[0,cycEyeInHead_XYZW[2]], z=[0,cycEyeInHead_XYZW[1]], mode='lines', line = dict( color = ('rgb(205, 12, 24)'), width = 4) ) layout = go.Layout(title="Head Centered Space", width=width, height=height, showlegend=False, scene=go.Scene(aspectmode='manual', aspectratio=dict(x=1, y=1, z=1), xaxis=dict(range=xRange, title='x Axis'), yaxis=dict(range=yRange, title='y Axis'), zaxis=dict(range=zRange, title='z Axis'), ), margin=go.Margin(t=100), hovermode='closest', ) fig = go.Figure(data=go.Data([head,eihDir]),layout=layout) return fig
def plot_surface_chart(title, x, y, z, xaxis, yaxis, zaxis, filename): ''' Plots surface 3D chart in polt.ly servers param title: string title of chart name param x: data array of x axis param y: data array of y axis param z: data array of z axis param x: data array of x axis param xaxis: string name of x axis param yaxis: string name of x yaxis param zaxis: string name of x zaxis param filename: name of the file that will be saved in plot.ly ''' data = go.Surface(x=x, y=y, z=z) layout = go.Layout(title=title, scene=go.Scene(xaxis=dict(title=xaxis), yaxis=dict(title=yaxis), zaxis=dict(title=zaxis))) fig = go.Figure(data=[data], layout=layout) py.iplot(fig, filename=filename)
def plot_3d_embeddings(x_values, labels, title): uniq_y = list(set(labels)) label_name = 'tissue' if 'tissue' in title else 'age' colors_dict = {} for y in uniq_y: colors_dict[y] = get_random_plotly_color() colors = list(map(lambda y: colors_dict[y], labels)) x_vals = list(np.array(x_values[:, 0:1]).flatten()) y_vals = list(np.array(x_values[:, 1:2]).flatten()) z_vals = list(np.array(x_values[:, 2:3]).flatten()) df = pd.DataFrame(labels, columns=[label_name]) df['x'] = x_vals df['y'] = y_vals df['z'] = z_vals df['color'] = colors fig = go.Figure( data=[ go.Scatter3d(x=df[df[label_name] == label]['x'].values, y=df[df[label_name] == label]['y'].values, z=df[df[label_name] == label]['z'].values, name=label, mode='markers', marker=dict(size=5, color=colors_dict[label])) for label in uniq_y ], layout=go.Layout( title=title, width=1000, showlegend=True, scene=graph_objs.Scene( xaxis=graph_objs.layout.scene.XAxis(title='x axis title'), yaxis=graph_objs.layout.scene.YAxis(title='y axis title'), zaxis=graph_objs.layout.scene.ZAxis(title='z axis title')))) fig.show()
def scatter_matrix_3d(M, marker=default_marker, width=600, height=600, title=None, x_label=None, y_label=None, z_label=None): data = [go.Scatter3d( x=M[:, 0], y=M[:, 1], z=M[:, 2], mode='markers', marker=marker )] layout = go.Layout( width=width, height=height, title=title, scene=go.Scene( xaxis=go.XAxis(title=x_label), yaxis=go.YAxis(title=y_label), zaxis=go.ZAxis(title=z_label), ) ) return iplot(go.Figure(data=data, layout=layout))
def setup_layout(self): "Setup the axis properties." axis = dict(showbackground=True, backgroundcolor='rgb(230, 230, 230)', gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)') xaxis = axis.copy() xaxis['range'] = [-1.1, 1.1] yaxis = axis.copy() yaxis['range'] = [-1.1, 1.1] zaxis = axis.copy() zaxis['range'] = [-1.1, 1.1] aspectratio = dict(x=1, y=1, z=1) self.layout = go.Layout(title='Kendall Triangles', width='100%', height=800, scene=go.Scene( xaxis=go.XAxis(xaxis), yaxis=go.YAxis(yaxis), zaxis=go.ZAxis(zaxis), aspectratio=dict(x=aspectratio['x'], y=aspectratio['y'], z=aspectratio['z']), ))
cloud._from_ply_file("E:/CloudMethod/Changed/000.ply") clouds = np.array(cloud.to_array(), dtype=np.float32) XT = clouds[:, 0] YT = clouds[:, 1] ZT = clouds[:, 2] X = XT[1::10] Y = YT[1::10] Z = ZT[1::10] trace = go.Scatter3d(x=X, y=Y, z=Z, mode='markers', marker=dict(color='rgb(127, 127, 127)', size=1, symbol='cube', line=dict(color='rgb(204, 204, 204)', width=1), opacity=0.9)) data = [trace] scene = go.Scene( xaxis=dict(title='X Axis', autorange=False, range=[-500, 500]), yaxis=dict(title='Y Axis', autorange=False, range=[-500, 500]), zaxis=dict(title='Z Axis', autorange=False, range=[0, 1000]), ) layout = go.Layout(margin=dict(l=0, r=0, b=0, t=0), scene=scene) fig = dict(data=data, layout=layout) py.iplot(fig, filename='Halo')
def prepare(self): # --------------------- print("Making plot...") # --------------------- # ------------------------------------------- x_data = self.x_data y_data = self.y_data z_data = self.z_data # ------------------------------------------- # ------------------------------------------------ # x_ticktext = x_data # x_tickvals = x_data # x_tickvals = list(range(len(x_data))) # x_ticktext = [str(i) for i in x_ticktext] # x_ticktext = x_ticktext[::50] # x_tickvals = x_tickvals[::50] # ------------------------------ # print('x_tickvals:', x_tickvals) # print('x_ticktext:', x_ticktext) # ------------------------------------------------ # ------------------------------------------------ # y_ticktext = y_data # y_ticktext = [str(i) for i in y_ticktext] # y_tickvals = list(range(len(y_data))) # y_tickvals = y_data # y_tickvals = np.array(y_tickvals) / self.t_coeff # y_ticktext = y_ticktext[::50] # y_tickvals = y_tickvals[::50] # y_tickvals = y_tickvals[::50] # ------------------------------ # print('y_tickvals:', y_tickvals) # print('y_ticktext:', y_ticktext) # ------------------------------------------------ data = [ # go.Surface( # showlegend=False, # showscale=False, # lighting=dict(diffuse=0.5, specular=.2, fresnel=0.2), # z=z_data, # # colorscale="Portland", # # colorscale='Viridis', # ) go.Surface( z=z_data, colorscale="Portland", contours=go.surface.Contours(z=go.surface.contours.Z( show=True, usecolormap=True, # highlightcolor="#42f462", project=dict(z=True), # colorscale="Portland", ))) ] scale = 1 # scale = int(y_ticktext[-1]) layout = go.Layout( # needed # --------------- title='<b>' + self.title + '</b>', # --------------- # ----------------- width=self.width, height=self.height, # ----------------- titlefont=dict( family='Lato', color="#222", size=20, ), xaxis=dict(title=r'$\sqrt{(n_\text{c}(t|{T_\text{early}}))}$'), # margin=go.Margin( # l=0, # r=0, # b=0, # t=35, # pad=50, # ), # zaxis=dict( # tickangle=90 # ), # -------------- # autosize=False, autosize=True, # -------------- plot_bgcolor="#AAA", # paper_bgcolor="#AAA", scene=go.Scene( camera=dict(up=dict(x=0, y=0, z=1), center=dict(x=0, y=0, z=0.2), eye=dict(x=3.75, y=3.75, z=3.75)), xaxis={ # -------------------- "title": self.x_title, # -------------------- # --------------------- # --------------------- "linewidth": 2, "showgrid": False, "showline": False, # ----------------------------------- 'titlefont': dict( family=self.ticks['family'], color=self.ticks['color'], size=self.ticks['title']['size'], ), 'tickfont': dict( family=self.ticks['family'], color=self.ticks['color'], size=self.ticks['size'], ), # ----------------------------------- # 'nticks': 5, 'tickangle': 0, # 'orientation': 'h', # 'autorange': True, # "ticktext": self.x_tickvals, "tickvals": self.x_tickvals, "ticktext": self.x_ticktext, # "showline":True, # "ticks": "outside", # "showticklabels": True, # "tickvals": list(range(len(x_tickvals))), # "ticktext": list(range(len(x_tickvals))), # "tickangle": 45, # "linecolor": "black", # "linewidth": 2, }, yaxis={ # -------------------------------- "title": self.y_title, # "title": self.y_title+"\t\t\t\t.", # -------------------------------- # --------------------- # "ticktext": self.y_tickvals, "tickvals": self.y_tickvals, "ticktext": self.y_ticktext, # --------------------- "linewidth": 2, # 'nticks': 5, # 'autotick': False, # 'tick0': 0.001, # 'dtick': 0.5, # ----------------------------------- 'titlefont': dict( family=self.ticks['family'], color=self.ticks['color'], size=self.ticks['title']['size'], ), 'tickfont': dict( family=self.ticks['family'], color=self.ticks['color'], size=self.ticks['size'], ), # ----------------------------------- 'tickangle': 0, # 'autorange': True, # "linecolor": "black", }, zaxis={ # -------------------- "title": self.z_title, # -------------------- "linewidth": 2, # 'nticks': 5, # ----------------------------------- 'titlefont': dict( family=self.ticks['family'], color=self.ticks['color'], size=self.ticks['title']['size'], ), 'tickfont': dict( family=self.ticks['family'], color=self.ticks['color'], size=self.ticks['size'], ), # ----------------------------------- 'tickangle': 0, 'autorange': True, # 'usecolormap': True, # 'highlightcolor': "#42f462", # 'dtick': -20, # "tickangle": 45, # "linecolor": "black", # "range": self.z_range, # "transform": {"rotate": '0'} }, aspectratio={ "x": self.scale['x'], "y": self.scale['y'], "z": self.scale['z'], }, ), # showlegend=False ) self.fig = go.Figure(data=data, layout=layout) if self.to_file: py.image.save_as(self.fig, filename=self.to_file) return return
def getLayout(kind=None,theme=None,title='',xTitle='',yTitle='',zTitle='',barmode='',bargap=None,bargroupgap=None, margin=None, dimensions=None, width=None, height=None, annotations=None,is3d=False,**kwargs): """ Generates a plotly Layout Parameters: ----------- theme : string Layout Theme solar pearl white title : string Chart Title xTitle : string X Axis Title yTitle : string Y Axis Title zTitle : string Z Axis Title Applicable only for 3d charts barmode : string Mode when displaying bars group stack overlay bargap : float Sets the gap between bars [0,1) Applicabe for bar and histogram plots bargroupgap : float Set the gap between groups [0,1) Applicabe for bar and histogram plots gridcolor : string grid color zerolinecolor : string zero line color margin : dict or tuple Dictionary (l,r,b,t) or Tuple containing the left, right, bottom and top margins dimensions : tuple Dimensions of figure annotations : dict or list Dictionary of annotations {x_point : text} or List of Plotly Annotations is3d : bool Indicates if the layout is for a 3D chart Other Kwargs ============ Shapes hline : int, list or dict Draws a horizontal line at the indicated y position(s) Extra parameters can be passed in the form of a dictionary (see shapes) vline : int, list or dict Draws a vertical line at the indicated x position(s) Extra parameters can be passed in the form of a dictionary (see shapes) hspan : (y0,y1) Draws a horizontal rectangle at the indicated (y0,y1) positions. Extra parameters can be passed in the form of a dictionary (see shapes) vspan : (x0,x1) Draws a vertical rectangle at the indicated (x0,x1) positions. Extra parameters can be passed in the form of a dictionary (see shapes) shapes : dict or list(dict) List of dictionaries with the specifications of a given shape. See help(cufflinks.tools.get_shape) for more information Axis Ranges xrange : [lower_bound,upper_bound] Sets the range for the x axis yrange : [lower_bound,upper_bound] Sets the range for the y axis zrange : [lower_bound,upper_bound] Sets the range for the z axis Explicit Layout Updates layout_update : dict The layout will be modified with all the explicit values stated in the dictionary Range Selector rangeselector : dict Defines a rangeselector object see help(cf.tools.get_range_selector) for more information Example: {'steps':['1y','2 months','5 weeks','ytd','2mtd'], 'axis':'xaxis1', 'bgcolor' : ('blue',.3), 'x': 0.2 , 'y' : 0.9} Range Slider rangeslider : bool or dict Defines if a rangeslider is displayed If bool: True : Makes it visible if dict: Rangeslider object Example: {'bgcolor':('blue',.3),'autorange':True} Annotations fontcolor : str Text color for annotations fontsize : int Text size for annotations textangle : int Textt angle See https://plot.ly/python/reference/#layout-annotations for a complete list of valid parameters. """ for key in list(kwargs.keys()): if key not in __LAYOUT_KWARGS: raise Exception("Invalid keyword : '{0}'".format(key)) if not theme: theme = auth.get_config_file()['theme'] theme_data = getTheme(theme) layout=go.Layout(theme_data['layout']) layout['xaxis1'].update({'title':xTitle}) layout['yaxis1'].update({'title':yTitle}) fontfamily=kwargs.pop('fontfamily',None) if fontfamily: deep_update(layout,{'font':{'family':fontfamily}}) if barmode: layout.update({'barmode':barmode}) if bargroupgap: layout.update({'bargroupgap':bargroupgap}) if bargap: layout.update(bargap=bargap) if title: layout.update({'title':title}) if annotations: layout.update({'annotations':annotations}) def update_axis(layout,axis='xy',**vals): for _x in axis: for k,v in list(vals.items()): if v==None: vals.pop(k) for k in layout: if '{0}{1}'.format(_x,'axis') in k: layout[k].update(**vals) return layout axis_kwargs=check_kwargs(kwargs,__LAYOUT_AXIS,{},True) xaxis_kwargs=kwargs_from_keyword(kwargs,{},'xaxis',True) yaxis_kwargs=kwargs_from_keyword(kwargs,{},'yaxis',True) for _x,_vals in (('xy',axis_kwargs),('x',xaxis_kwargs),('y',yaxis_kwargs)): layout=update_axis(layout,_x,**_vals) if margin: if isinstance(margin,dict): margin=margin else: margin=dict(list(zip(('l','r','b','t'),margin))) layout.update(margin=margin) if dimensions: layout.update(width=dimensions[0]) layout.update(height=dimensions[1]) if height: layout.update(height=height) if width: layout.update(width=width) if is3d: if '3d' in theme_data: layout=deep_update(layout,theme_data['3d']) zaxis=layout['xaxis1'].copy() zaxis.update(title=zTitle) scene=go.Scene(xaxis=layout['xaxis1'].copy(),yaxis=layout['yaxis1'].copy(),zaxis=zaxis) layout.update(scene=scene) del layout['xaxis1'] del layout['yaxis1'] ## Axis Range for r in ['x','y','z']: if '{0}range'.format(r) in kwargs: if is3d: layout['scene']['{0}axis'.format(r)].update(range=kwargs['{0}range'.format(r)]) else: layout['{0}axis1'.format(r)].update(range=kwargs['{0}range'.format(r)]) # Need to update this for an add_axis approach. if kind in ('candlestick','ohlc','candle'): layout['yaxis2']=layout['yaxis1'].copy() layout['yaxis1'].update(showticklabels=False) ## Kwargs if 'legend' in kwargs: if type(kwargs['legend'])==bool: layout['showlegend']=kwargs['legend'] elif type(kwargs['legend'])==str: if kwargs['legend']=='top': layout['legend'].update(orientation='h',yanchor='bottom',x=.3,y=.95) elif kwargs['legend']=='bottom': layout['legend'].update(orientation='h',yanchor='bottom',x=.3,y=-0.5) layout['showlegend']=True else: layout['legend']=kwargs['legend'] layout['showlegend']=True if 'showlegend' in kwargs: layout['showlegend']=kwargs['showlegend'] # Logarithmic Axis for _ in ['x','y','z']: if 'log{0}'.format(_) in kwargs: if is3d: if kwargs['log{0}'.format(_)]: layout['scene']['{0}axis'.format(_)]['type']='log' else: if kwargs['log{0}'.format(_)]: layout['{0}axis1'.format(_)]['type']='log' # Shapes if any(k in kwargs for k in ['vline','hline','shapes','hspan','vspan']): shapes=[] def get_shapes(xline): orientation=xline[0] xline=kwargs[xline] if isinstance(xline,list): for x_i in xline: if isinstance(x_i,dict): x_i['kind']='line' shapes.append(get_shape(**x_i)) else: if orientation=='h': shapes.append(get_shape(kind='line',y=x_i)) else: shapes.append(get_shape(kind='line',x=x_i)) elif isinstance(xline,dict): shapes.append(get_shape(**xline)) else: if orientation=='h': shapes.append(get_shape(kind='line',y=xline)) else: shapes.append(get_shape(kind='line',x=xline)) def get_span(xspan): orientation=xspan[0] xspan=kwargs[xspan] if isinstance(xspan,list): for x_i in xspan: if isinstance(x_i,dict): x_i['kind']='rect' shapes.append(get_shape(**x_i)) else: v0,v1=x_i if orientation=='h': shapes.append(get_shape(kind='rect',y0=v0,y1=v1,fill=True,opacity=.5)) else: shapes.append(get_shape(kind='rect',x0=v0,x1=v1,fill=True,opacity=.5)) elif isinstance(xspan,dict): xspan['kind']='rect' shapes.append(get_shape(**xspan)) elif isinstance(xspan,tuple): v0,v1=xspan if orientation=='h': shapes.append(get_shape(kind='rect',y0=v0,y1=v1,fill=True,opacity=.5)) else: shapes.append(get_shape(kind='rect',x0=v0,x1=v1,fill=True,opacity=.5)) else: raise Exception('Invalid value for {0}span: {1}'.format(orientation,xspan)) if 'hline' in kwargs: get_shapes('hline') if 'vline' in kwargs: get_shapes('vline') if 'hspan' in kwargs: get_span('hspan') if 'vspan' in kwargs: get_span('vspan') if 'shapes' in kwargs: shapes_=kwargs['shapes'] if isinstance(shapes_,list): for i in shapes_: shp=i if 'type' in i else get_shape(**i) shapes.append(shp) elif isinstance(shapes_,dict): shp=shapes_ if 'type' in shapes_ else get_shape(**shapes_) shapes.append(shp) else: raise Exception("Shapes need to be either a dict or list of dicts") layout['shapes']=shapes # Maps if kind in ('choropleth','scattergeo'): kw=check_kwargs(kwargs,__GEO_KWARGS) defaults={'projection':{'type':'equirectangular'},'showframe':False,'showcoastlines':False} for k,v in list(defaults.items()): if k not in kw: kw[k]=v kw_=kwargs_from_keyword(kw,{},'projection') deep_update(kw,kw_) layout['geo']=kw del layout['xaxis1'] del layout['yaxis1'] if not margin: layout['margin']={'autoexpand':True} # Range Selector if 'rangeselector' in kwargs: rs=kwargs['rangeselector'] if 'axis' in rs: axis=rs['axis'] del rs['axis'] else: axis='xaxis1' layout[axis]['rangeselector']=get_range_selector(**rs) # Range Slider if 'rangeslider' in kwargs: if type(kwargs['rangeslider'])==bool: if kwargs['rangeslider']: layout['xaxis1']['rangeslider']=dict(visible=kwargs['rangeslider']) else: layout['xaxis1']['rangeslider']=dict(visible=False) # layout['yaxis1'].update(domain=(0,0)) else: layout['xaxis1']['rangeslider']=kwargs['rangeslider'] else: if kind in ('ohlc','candle','candlestick'): layout['xaxis1']['rangeslider']=dict(visible=False) # layout['yaxis1'].update(domain=(0,0)) # Explicit Updates if 'layout_update' in kwargs: layout=deep_update(layout,kwargs['layout_update']) def updateColors(layout): for k,v in list(layout.items()): if isinstance(v,dict): updateColors(v) else: if isinstance(v,list): for _ in v: if isinstance(_,dict): updateColors(_) if 'color' in k.lower(): if 'rgba' not in v: layout[k]=normalize(v) return layout return updateColors(layout)
def graphlayout3d(): return (go.Layout(showlegend=False, scene=go.Scene(xaxis=go.YAxis(graphaxis()), yaxis=go.XAxis(graphaxis()), zaxis=go.ZAxis(graphaxis())), hovermode='closest'))
x=Y[y==name,0], y=Y[y==name,1], mode='markers', name=name, marker=go.Marker( size=12, line=go.Line( color='rgba(217, 217, 217, 0.14)', width=0.5), opacity=0.8)) traces.append(trace) data = go.Data(traces) layout = go.Layout(showlegend=True, scene=go.Scene(xaxis=go.XAxis(title='PC1'), yaxis=go.YAxis(title='PC2'),)) fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig) #%% # PCA4 from sklearn.decomposition import PCA as sklearnPCA sklearn_pca = sklearnPCA(n_components=4) Y_sklearn = sklearn_pca.fit_transform(X_std) traces = []
eye=dict(x=-0.5, y=2, z=0.9)) points = go.Scatter3d(x=data[:, 0], y=data[:, 1], z=data[:, 2], mode='markers', marker=dict(color='orange', size=10)) true_surface = go.Surface(x=xx, y=yy, z=zz, showscale=False, opacity=0.75, colorscale='Greys', showlegend=True) pca_surface = go.Surface(x=x_pca_plane, y=y_pca_plane, z=z_pca_plane, showscale=False, opacity=0.75, surfacecolor=255 * np.ones(x_pca_plane.shape), colorscale='orange') xaxis = go.XAxis(title='', showaxeslabels=False, showticklabels=False) yaxis = go.YAxis(title='', showaxeslabels=False, showticklabels=False) zaxis = go.ZAxis(title='', showaxeslabels=False, showticklabels=False) scene = go.Scene(camera=camera, xaxis=xaxis, yaxis=yaxis, zaxis=zaxis) layout = go.Layout(scene=scene, width=2000, height=2000) fig = go.Figure(data=[points, true_surface, pca_surface], layout=layout) pyo.plot(fig)
def plotly_skeleton_figure(skel3d, skel_desc): meta_fn = _make_joint_metadata_fn(skel_desc) cxs = [] cys = [] czs = [] lxs = [] lys = [] lzs = [] rxs = [] rys = [] rzs = [] xt = list(skel3d[:, 0]) zt = list(-skel3d[:, 1]) yt = list(skel3d[:, 2]) for j, p in enumerate(skel_desc.joint_tree): metadata = meta_fn(j) if metadata['group'] == 'left': xs, ys, zs = lxs, lys, lzs elif metadata['group'] == 'right': xs, ys, zs = rxs, rys, rzs else: xs, ys, zs = cxs, cys, czs xs += [xt[j], xt[p], None] ys += [yt[j], yt[p], None] zs += [zt[j], zt[p], None] points = go.Scatter3d( x=list(skel3d[:, 0]), z=list(-skel3d[:, 1]), y=list(skel3d[:, 2]), text=skel_desc.joint_names, mode='markers', marker=dict(color='grey', size=3, opacity=0.8), ) centre_lines = go.Scatter3d( x=cxs, y=cys, z=czs, mode='lines', line=dict(color='magenta', width=1), hoverinfo='none', ) left_lines = go.Scatter3d( x=lxs, y=lys, z=lzs, mode='lines', line=dict(color='blue', width=1), hoverinfo='none', ) right_lines = go.Scatter3d( x=rxs, y=rys, z=rzs, mode='lines', line=dict(color='red', width=1), hoverinfo='none', ) layout = go.Layout( margin=go.Margin(l=20, r=20, b=20, t=20, pad=0), hovermode='closest', scene=go.Scene( aspectmode='data', yaxis=go.YAxis(title='z'), zaxis=go.ZAxis(title='y'), ), showlegend=False, ) fig = go.Figure(data=[points, centre_lines, left_lines, right_lines], layout=layout) return fig
def PyPlot3D(title, z_csv, x_csv, y_csv, t_coeff=1, online=True, path=".", filename="wt2", xaxis="states", yaxis="time", to_file="", y_scale=1): print("Making plot...") # Z---------------------------------------------- z_data = pd.read_csv(z_csv, header=None) # Z---------------------------------------------- # X---------------------------------------------- x = pd.read_csv(x_csv, keep_default_na=False) # x.replace(r'\[(.+)\]', r'. ≺\1}', regex=True, inplace=True) x.replace(r'\[(.+)\]', r'{\1≻', regex=True, inplace=True) # x.replace(r'\[(.+)\]', r'≺\1}', regex=True, inplace=True) # x.replace(r'\[(.+)\]', r'≺\1≻', regex=True, inplace=True) x_header = list(x)[0] # x["x"] = list(x["x"]) x_ticktext = list(x['x']) x_tickvals = list(x['vals']) # x_tickvals = np.linspace( # list(x["x"])[0], list(x["x"])[-1], 10) # x_ticktext = np.linspace( # list(x["vals"])[0], list(x["vals"])[-1], 10) # x_ticktext = np.round(x_ticktext, 2) # print(list(x["x"])[-1]) for i in range(len(x_ticktext)): x_ticktext[i] = x_ticktext[i] x_ticktext[i] = str(x_ticktext[i]) print('x_ticktext:', x_ticktext) print('x_tickvals:', x_tickvals) # X---------------------------------------------- # Y---------------------------------------------- y = pd.read_csv(y_csv, keep_default_na=False) y_header = list(y)[0] # print(list(y["y"])) # exit(0) # y["y"] = list(y["y"]) # y["vals"] = list(y["vals"]) # y_tickvals = np.linspace( # list(y["y"])[0], list(y["y"])[-1], 10) # y_ticktext = np.linspace( # list(y["vals"])[0], list(y["vals"])[-1], 10) # y_ticktext = np.round(y_ticktext, 2) y_ticktext = list(y["y"]) y_tickvals = list(y["vals"]) y_tickvals = np.array(y_tickvals) / t_coeff print('y_ticktext:', y_ticktext) print('y_tickvals:', y_tickvals) # Y---------------------------------------------- data = [ go.Surface( showlegend=False, showscale=False, lighting=dict(diffuse=0.5, specular=.2, fresnel=0.2), z=z_data.values, colorscale="Portland", ) ] scale = int(y_ticktext[-1]) layout = go.Layout( # plot_bgcolor="#000000", # pap_bgcolor="#000000", title=title, titlefont=dict( # family="Courier New, monospace", # family='Open Sans, sans-serif', family='Lato', size=20, color="#222"), margin=go.Margin( l=0, r=0, b=0, t=35, pad=50, ), xaxis=dict( # linecolor="black", # linewidth=2, # autotick=False, # dtick=1, ticks='outside', tickfont=dict( # size=20, size=200, ), ), yaxis=dict( # tickangle=45, title="y Axis", titlefont=dict( family="Courier New, monospace", # family='Old Standard TT, serif', size=40, # size=14, color="#FFFFFF"), # autotick=False, # dtick=1, ticks='outside', tickfont=dict( # size=20, size=200, ), ), # zaxis=dict( # tickangle=90 # ), autosize=False, # autosize=True, width=1200, height=650, plot_bgcolor="#AAA", # paper_bgcolor="#AAA", scene=go.Scene( camera=dict(up=dict(x=0, y=0, z=1), center=dict(x=0, y=0, z=0.2), eye=dict(x=3.75, y=3.75, z=3.75)), aspectratio={ "x": 1, "y": y_scale * y_ticktext[-1], "z": 1 }, xaxis={ "title": xaxis, "showgrid": False, "showline": False, # "showline":True, # "ticks": "outside", # "showticklabels": True, # "linewidth": 1, # "tickvals": list(range(len(x_tickvals))), # "ticktext": list(range(len(x_tickvals))), "tickvals": x_tickvals, "ticktext": x_ticktext, 'titlefont': dict(size=18, ), 'tickfont': dict(size=14, ), 'autorange': True, # "tickangle": 45, # "linecolor": "black", # "linewidth": 2, }, yaxis={ 'autorange': True, "title": yaxis + "\t\t\t\t.", "ticktext": y_ticktext[::2], "tickvals": y_tickvals[::2], # "linecolor": "black", "linewidth": 1, 'titlefont': dict(size=18, ), 'tickfont': dict(size=14, ) }, zaxis={ 'autorange': True, "range": [0, 1], "title": "prob.\t\t\t\t\t\t.", # 'dtick': -20, # "tickangle": 45, # "linecolor": "black", "linewidth": 1, 'titlefont': dict(size=18, ), 'tickfont': dict(size=14, ) # "transform": {"rotate": '0'} }, ), showlegend=False) fig = go.Figure(data=data, layout=layout) if to_file: py.image.save_as(fig, filename=to_file) return # fig["layout"].update(scene=dict(aspectmode="data")) # online=False if online: py.plot(fig, filename=filename) # plotly.offline.init_notebook_mode() # plotly.offline.iplot(fig, filename="wt.html") # plotly. # py.offline.iplot(fig, filename="wt") else: # plotly.offline.init_notebook_mode() plotly.offline.plot(fig, filename=path + filename + ".html") return
def visualize_3d(config, G, node_sizes): keys = G.nodes() values = range(len(G.nodes())) dictionary = dict(zip(keys, values)) inv_map = {v: k for k, v in dictionary.items()} G = nx.relabel_nodes(G, dictionary) edge_trace = go.Scatter3d(x=[], y=[], z=[], mode='lines', line=go.scatter3d.Line( color='rgba(136, 136, 136, .8)', width=1), hoverinfo='none') node_trace = go.Scatter3d( x=[], y=[], z=[], mode='markers', #name='actors', marker=go.scatter3d.Marker( symbol='circle', size=[], color=[], colorscale=config.color_scale, #'Viridis', colorbar=dict(thickness=15, title='Node Connections', xanchor='left', titleside='right'), #line=go.Line(color='rgb(50,50,50)', width=0.5) ), text=[], hoverinfo='text') positions = nx.fruchterman_reingold_layout(G, dim=3, k=0.5, iterations=1000) for edge in G.edges(): x0, y0, z0 = positions[edge[0]] x1, y1, z1 = positions[edge[1]] edge_trace['x'] += ( x0, x1, ) edge_trace['y'] += ( y0, y1, ) edge_trace['z'] += ( z0, z1, ) for node in G.nodes(): x, y, z = positions[node] node_trace['x'] += (x, ) node_trace['y'] += (y, ) node_trace['z'] += (z, ) for i, adjacencies in G.adjacency(): node_trace['marker']['color'] += (len(adjacencies), ) for size in node_sizes: node_trace['marker']['size'] += (abs(math.log(size)) * 10, ) for node in G.nodes(): node_trace['text'] += (inv_map[node], ) axis = dict(showbackground=False, showline=False, zeroline=False, showgrid=False, showticklabels=False, title='') layout = go.Layout( title=config.title, width=1000, height=1000, showlegend=False, scene=go.Scene( xaxis=go.XAxis(axis), yaxis=go.YAxis(axis), zaxis=go.ZAxis(axis), ), margin=go.Margin(t=100), hovermode='closest', ) fig = go.Figure(data=[node_trace, edge_trace], layout=layout) offpy(fig, filename=config.out_file_name, auto_open=True, show_link=False)
def main(date, wavelengths, keywords=[], allSpectra=False): """ Plot three wavelengths against each other from a specified set of data. :param date: (string) Data collection date YYYY_MMDD :param wavelengths: (3-tuple) Wavelengths to plot against another :param keywords: (list of strings) Strings which should be included in the filenames of files being plotted :allSpectra: (boolean) Determines where there is one point for every spectra collected, or one point for every leaf file :return: (None) """ # Convert the wavelengths to indices for accessing the data wavelengthIndices = map(wavelengthToIndex, wavelengths) wavelengthIndex1 = wavelengthIndices[0] wavelengthIndex2 = wavelengthIndices[1] wavelengthIndex3 = wavelengthIndices[2] # Get the data files we will be looking at dataPath = DATA_DIRECTORIES[date] filesToPlot = FileIO.getDatafileNames(dataPath, keywords) pointsDR = [] pointsGR = [] pointsSUS = [] for name in filesToPlot: tokens = name[0:-4].split('_') map(lambda x: x.lower(), tokens) plant = tokens[0] resistance = tokens[1] filePath = os.path.join(dataPath, name) data = FileIO.loadCSV(filePath) try: rows, columns = data.shape if columns < 2: continue except: continue if allSpectra: xValues = data[:, wavelengthIndex1] yValues = data[:, wavelengthIndex2] zValues = data[:, wavelengthIndex3] points = np.zeros((rows, 3)) points[:, 0] = xValues points[:, 1] = yValues points[:, 2] = zValues if resistance == SUSCEPTIBLE: if pointsSUS == []: pointsSUS = points else: pointsSUS = np.append(pointsSUS, points, axis=0) elif resistance == DR_RESISTANT: if pointsDR == []: pointsDR = points else: pointsDR = np.append(pointsDR, points, axis=0) elif resistance == GR_RESISTANT: if pointsGR == []: pointsGR = points else: pointsGR = np.append(pointsGR, points, axis=0) else: raise Exception("Unknown resistance type: " + resistance) else: mean = np.mean(data, axis=0) meanValue1 = mean[wavelengthIndex1] meanValue2 = mean[wavelengthIndex2] meanValue3 = mean[wavelengthIndex3] if resistance == SUSCEPTIBLE: pointsSUS.append([meanValue1, meanValue2, meanValue3]) elif resistance == DR_RESISTANT: pointsDR.append([meanValue1, meanValue2, meanValue3]) elif resistance == GR_RESISTANT: pointsGR.append([meanValue1, meanValue2, meanValue3]) else: raise Exception("Unknown resistance type: " + resistance) # Plot the wavelengths pointsDR = np.array(pointsDR) pointsGR = np.array(pointsGR) pointsSUS = np.array(pointsSUS) traceSUS = plotPoints(pointsSUS, RESISTANCE_STRINGS[SUSCEPTIBLE], 'rgba(255, 0, 0, 0)') traceDR = plotPoints(pointsDR, RESISTANCE_STRINGS[DR_RESISTANT], 'rgba(0, 255, 0, 0)') traceGR = plotPoints(pointsGR, RESISTANCE_STRINGS[GR_RESISTANT], 'rgba(0, 0, 255, 0)') layout = go.Layout( title='3D Wavelength Plot', scene=go.Scene( xaxis=go.XAxis(title='Reflectance @ ' + str(wavelengths[0]) + ' nm'), yaxis=go.YAxis(title='Reflectance @ ' + str(wavelengths[1]) + ' nm'), zaxis=go.ZAxis(title='Reflectance @ ' + str(wavelengths[2]) + ' nm') ) ) data = [traceSUS, traceDR, traceGR] fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='3D Wavelength Plot')