def view_1(self): y, x = np.mgrid[-5:5, -5:5] * 0.1 heights = np.sin(x ** 2 + y ** 2) hv.Scatter3D((x.flat, y.flat, heights.flat)).opts( cmap='fire', color='z', size=5) plot = ( hv.Scatter3D(np.random.randn(100, 4), vdims='Size') * hv.Scatter3D(np.random.randn(100, 4) + 2,vdims='Size')) plot.opts(height=100, width=200) return plot
def mark_color_3d_plot(self, elevation, azimuth, col1='c00', col2='c01', col3='c02'): hv.output(backend='matplotlib') scatter = [ hv.Scatter3D(mark_pos.loc[:, [col1, col2, col3]]).opts( dict(Scatter3D=dict(bgcolor='black', s=3))) for elec_id, mark_pos in self.unit_spks.items() ] overlay = hv.Overlay(scatter, label='Plot of spikes and their features ' + col1 + ', ' + col2 + ', and ' + col3) overlay = overlay.opts({ 'Scatter3D': { 'plot': { 'fig_size': 400, 'azimuth': int(azimuth), 'elevation': int(elevation) }, 'norm': { 'framewise': True } } }) return overlay
def plot_embed3d(max_win): group = 'Sleep Stage' color_key = { 'Wake': 'orange', 'Stage 1': 'yellow', 'Stage 2': 'green', 'Stage 3': 'blue', 'Undetermined': 'gray' } output = hv.Scatter3D( (LE3D_df['x_norm'][0:max_win], LE3D_df['y_norm'][0:max_win], LE3D_df['z_norm'][0:max_win])).opts( color=LE3D_df[group].map(color_key), show_legend=True, size=5, xlim=(-1, 1), ylim=(-1, 1), zlim=(-1, 1), aspect={ 'x': 1, 'y': 1, 'z': 1 }, camera_zoom=1, margins=(5, 5, 5, 5), height=600, width=600) return output
def plot_embed3d(max_win): output = hv.Scatter3D((embedding_df['x_norm'][0:max_win], embedding_df['y_norm'][0:max_win], embedding_df['z_norm'][0:max_win])).opts(color=embedding_df['color_rgb'][0:max_win], size=5, xlim=(-1,1), ylim=(-1,1), zlim=(-1,1), aspect={'x':1,'y':1,'z':1}, camera_zoom=1, margins=(5,5,5,5), height=800, width=800) return output
def hvplot(self, scatter_opt=None): if self.n_features != 2: raise NotImplementedError hv.extension('plotly') # x, y = self.data['X'], self.data['y'] x, y = self.split_fn(self.data) scatter_opt = scatter_opt or opts.Scatter3D( size=5, width=800, height=800, title=self.descr, show_legend=True if self.label else False) return hv.Scatter3D((x[:, 0], x[:, 1], y.squeeze()), label=self.label).opts(scatter_opt)
def test_gaussian_x_linear_mapping(): x_gen_mu = [0,0] x_gen_cov = [[1,0], [0,1]] true_w = [1,2] true_b = 10. n_samples = 1000 noise_std = 0. data = gaussian_x_linear_mapping(x_gen_mu, x_gen_cov, n_samples, true_w, true_b) x, y = data['X'], data['y'] hv.Scatter3D((x[:,0], x[:,1], y.squeeze())).opts( opts.Scatter3D(color='z', colorbar=True, width=800, height=800, title=f''' true w, b: {true_w}, {true_b} noise: {noise_std} '''))
def plotKmeansClusters(df: pd.DataFrame, numClusters: int, colors: [], title: str, **kwargs): ''' Plot KMeans clusters and their respective centroids. This can only plot 1D, 2D, and 3D data @df: data frame object @numClusters: number of clusters @colors: list containing color strings to differentiate each cluster Returns: a holoview overlay object ''' # Run KMeans kmeans = KMeans(n_clusters=numClusters, **kwargs) preds = kmeans.fit_predict(df) numCols = kmeans.cluster_centers_.shape[1] # Display a warning if data has more than 3 dimensions if (numCols > 3): warnings.warn( "[WARNING] This function only supports drawing clusters up to 3 dimensions max." ) # Construct the prediction data frame to include a color column clustersDf = df.copy(True) clustersDf["color"] = [colors[p] for p in preds] # Construct centroids data frame to include a color column # If centroid data dimensions exceed 3, then just use the first 3 dimensions columnRange = [i for i in range(numCols)][:3] centroids = kmeans.cluster_centers_[:, columnRange] centroidColumns = [f"Col_{i}" for i in columnRange] # Add a color column to the centroidsDf centroidsDf = pd.DataFrame(centroids, columns=centroidColumns) centroidsDf["color"] = pd.Series(colors[:len(centroidsDf)]) # Plot the scatter points in 2D or 3D clustersScatter = None centroidsScatter = None # Scatter plot options clustersScatterOpts = {"color": "color", "size": 10} centroidsScatterOpts = {"color": "color", "size": 20} if (numCols <= 2): hv.extension("bokeh") # If data is only 1D then use 0 as the y values if (numCols == 1): # Assign 0 as y column clustersDf["Zero_Col"] = 0 centroidsDf["Zero_Col"] = 0 # Swap the columns so that the zero column is the 2nd column. This # allows holoviews to use the 2nd column as the y values clustersDf = swapTwoColumns(clustersDf, "color", "Zero_Col") centroidsDf = swapTwoColumns(centroidsDf, "color", "Zero_Col") clustersScatter = hv.Scatter(clustersDf).opts(tools=["hover"], **clustersScatterOpts) centroidsScatter = hv.Scatter(centroidsDf).opts(tools=["hover"], marker="triangle", **centroidsScatterOpts) else: # Use plotly backend. Currently holoviews doesn't support bokeh 3D scatter plot hv.extension("plotly") clustersScatter = hv.Scatter3D(clustersDf).opts(**clustersScatterOpts) centroidsScatter = hv.Scatter3D(centroidsDf).opts( marker="diamond-open", **centroidsScatterOpts) # Render both plots on the same figure scatterOverlay = (clustersScatter * centroidsScatter).opts(title=title, width=800, height=650) return scatterOverlay
def draw( self, data: pd.DataFrame, *, centers: pd.DataFrame = _empty_dataframe, ) -> None: """Draw the first three components in subplots. Parameters ---------- data : pd.DataFrame Matrix with shape (n_samples, n_components) centers : pd.DataFrame, optional Vector of cluster centers (n_components, ) Notes ----- Four subplots are created. * component 1 vs. component 2 * component 1 vs. component 3 * component 2 vs. component 3 * 3D plot """ table = hv.Table(data) kdims = table.data.columns[2:5].to_list() vdims = table.data.columns[:2].to_list() centroid = hv.Table(centers) if not centers.empty else hv.Table([]) points = [ hv.Points(table, [i, j], vdims=vdims).opts( show_legend=False, marker=".", s=5, cmap=glasbey_cool, color_index="Cluster", ) for i, j in itertools.combinations(kdims, 2) ] if centroid: scatter = [ hv.Points(centroid, kdims=[i, j], vdims="Cluster").opts( show_legend=False, marker=".", s=15, cmap=glasbey_light, color_index="Cluster", ) for i, j in itertools.combinations(kdims, 2) ] points = [i * j for i, j in zip(points, scatter)] self._figure = hv.Layout(points) scatter3d = hv.Scatter3D(data, kdims, vdims=vdims).opts( show_legend=False, marker=".", s=5, cmap=glasbey_cool, color_index="Cluster", ) if centroid: scatter3d *= hv.Scatter3D(centers, kdims=kdims, vdims="Cluster").opts( show_legend=False, marker=".", s=25, cmap=glasbey_light, color_index="Cluster", ) self._figure += scatter3d self._figure.cols(2)
def scatter_3d(df, x, y, z, **args): hv.extension("plotly") return hv.Scatter3D(df, kdims=[x, y, z]).opts(**args)