def contourf(self, X, Y, Z, *args, **kwargs): ''' Create a 3D contourf plot. ========== ================================================ Argument Description ========== ================================================ *X*, *Y*, Data values as numpy.arrays *Z* *zdir* The direction to use: x, y or z (default) *offset* If specified plot a projection of the filled contour on this position in plane normal to zdir ========== ================================================ The positional and keyword arguments are passed on to :func:`~matplotlib.axes.Axes.contourf` Returns a :class:`~matplotlib.axes.Axes.contourf` ''' zdir = kwargs.pop('zdir', 'z') offset = kwargs.pop('offset', None) had_data = self.has_data() jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir) cset = Axes.contourf(self, jX, jY, jZ, *args, **kwargs) self.add_contourf_set(cset, zdir, offset) self.auto_scale_xyz(X, Y, Z, had_data) return cset
def contourf(self, *args, **kwargs): """ If the **mantid** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes.contourf` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid'}) ax.contourf(workspace) #for workspaces ax.contourf(x,y,z) #for arrays fig.show() For keywords related to workspaces, see :func:`plotfunctions.contourf` """ if helperfunctions.validate_args(*args): logger.debug('using plotfunctions') workspace = args[0] return self.track_workspace_artist(workspace, plotfunctions.contourf(self, *args, **kwargs)) else: return Axes.contourf(self, *args, **kwargs)
def contourf(self, *args, **kwargs): """ If the **mantid** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes.contourf` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid'}) ax.contourf(workspace) #for workspaces ax.contourf(x,y,z) #for arrays fig.show() For keywords related to workspaces, see :func:`plotfunctions.contourf` """ if helperfunctions.validate_args(*args): logger.debug('using plotfunctions') workspace = args[0] return self.track_workspace_artist( workspace, plotfunctions.contourf(self, *args, **kwargs)) else: return Axes.contourf(self, *args, **kwargs)
def plot_hyperplane(clf, ax: Axes = None, interval: float = .05, alpha=.3, colors=('r', 'b')) -> Line3DCollection: """ Plots the hyperplane of the model in an axes :param clf: the classifier to use to find the hyperplane :param ax: the axes to plot the hyperplane into :param interval: the precision of the the hyperplane rendering. :param alpha: :param colors: :return: the mesh of the created hyperplane that was added to the axes """ is_3d, ax = needed_axes(clf, ax) interval = int(1 / interval) # get the separating hyperplane x_min, x_max = ax.get_xlim() y_min, y_max = ax.get_ylim() # create grid to evaluate model xx = np.linspace(x_min, x_max, interval) yy = np.linspace(y_min, y_max, interval) if is_3d: z_min, z_max = ax.get_zlim() zz = np.linspace(z_min, z_max, interval) yy, xx, zz = np.meshgrid(yy, xx, zz) if hasattr(clf, "decision_function"): z = clf.decision_function(np.c_[xx.ravel(), yy.ravel(), zz.ravel()]) elif hasattr(clf, "predict_proba"): z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel(), zz.ravel()])[:, 1] else: raise ValueError( "The model passed in does not contain either the decision_function or the predict_proba functions.") z = z.reshape(xx.shape) vertices, faces, _, _ = measure.marching_cubes_lewiner(z, 0) # Scale and transform to actual size of the interesting volume vertices = vertices * [x_max - x_min, y_max - y_min, z_max - z_min] / interval vertices += [x_min, y_min, z_min] # and create a mesh to display mesh = Line3DCollection(vertices[faces], facecolor=colors, alpha=alpha) ax.add_collection3d(mesh) return mesh else: xx, yy = np.meshgrid(xx, yy) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) return ax.contourf(xx, yy, Z, 10, colors=colors, alpha=alpha)
def contour_plot(self, subplot: Axes) -> None: """ Draws the decision boundaries as a contour plot. The boundaries are drawn as red lines and the color gradient represents the value outputted by the network. :param subplot: The subplot where the content should be drawn. """ norm = cm.colors.Normalize(vmin=-1.0, vmax=1.0) subplot.contourf(self.grid_x, self.grid_y, self.z_plot, zorder=0, vmin=-1.0, vmax=1.0, norm=norm, alpha=.95) warnings.filterwarnings("ignore") subplot.contour(self.grid_x, self.grid_y, self.z_plot, levels=[-.0001, 0.0001], colors='r') warnings.filterwarnings("default")
def plot_2d(self, x1: Union[Iterable, ndarray], x2: Union[Iterable, ndarray], color_map: str = 'viridis', ax: Axes = None) -> Axes: """ Plot a 2-dimensional function as a grid heat-map. :param x1: Range of values of x1 to plot p(x1, x2) over. :param x2: Range of values of x2 to plot p(x1, x2) over. :param color_map: Optional colormap for the heat-map. :param ax: Optional matplotlib axes to plot on. """ x1_grid, x2_grid = meshgrid(x1, x2) x1_x2 = dstack((x1_grid, x2_grid)) f = self._method(x1_x2) ax = ax or new_axes() ax.contourf(x1_grid, x2_grid, f, cmap=color_map) ax.set_xlabel('x1') ax.set_ylabel('x2') return ax
def contourf(self, X, Y, Z, *args, **kwargs): ''' Plot filled 3D contours. *X*, *Y*, *Z*: data points. Keyword arguments are passed on to :func:`~matplotlib.axes.Axes.contour` ''' had_data = self.has_data() cset = Axes.contourf(self, X, Y, Z, *args, **kwargs) levels = cset.levels colls = cset.collections for z1, z2, linec in zip(levels, levels[1:], colls): art3d.poly_collection_2d_to_3d(linec, z1) linec.set_sort_zpos(z1) self.auto_scale_xyz(X, Y, Z, had_data) return cset
def _plot_2d(data: Union[DenseFunctionalData, IrregularFunctionalData], ax: Axes = None, **plt_kwargs) -> Axes: """Plot two dimensional functional data. This function is used to plot an instance of functional data in 2D. Parameters ---------- data: IrregularFunctionalData The object to plot. ax: matplotlib.axes._subplots.AxesSubplot Axes object onto which the objects are plotted. **plt_kwargs: Keywords plotting arguments Returns ------- ax: matplotlib.axes._subplots.AxesSubplot Axes objects onto the plot is done. """ if isinstance(data, DenseFunctionalData): if data.n_obs == 1: cs = ax.contourf(data.argvals['input_dim_0'], data.argvals['input_dim_1'], data.values.squeeze(), **plt_kwargs) plt.colorbar(cs) else: x, y = np.meshgrid(data.argvals['input_dim_0'], data.argvals['input_dim_1'], indexing='ij') for obs in data.values: ax.plot_surface(x, y, obs, **plt.kwargs) elif isinstance(data, IrregularFunctionalData): raise NotImplementedError("Currently 2d irregular functional data" " plotting is not implemented.") else: raise TypeError("Data type not recognized!") return ax
def plot_hyperplane(clf, ax: Axes = None, interval: float = .05, alpha=.3, colors: list = ('r', 'b')) -> Line3DCollection: """ Plots the hyperplane of the model in an axes :param clf: the classifier to use to find the hyperplane :param ax: the axes to plot the hyperplane into :param interval: the precision of the the hyperplane rendering. :return: the mesh of the created hyperplane that was added to the axes """ is_3d = False if ax is None: try: clf.predict([[0, 0, 0]]) is_3d = True ax = plt.gca(projection="3d") except ValueError: is_3d = False ax = plt.gca() elif isinstance(ax, Axes3D): is_3d = True interval = int(1 / interval) # get the separating hyperplane x_min, x_max = ax.get_xlim() y_min, y_max = ax.get_ylim() # create grid to evaluate model xx = np.linspace(x_min, x_max, interval) yy = np.linspace(y_min, y_max, interval) if is_3d: z_min, z_max = ax.get_zlim() zz = np.linspace(z_min, z_max, interval) yy, xx, zz = np.meshgrid(yy, xx, zz) if hasattr(clf, "decision_function"): z = clf.decision_function(np.c_[xx.ravel(), yy.ravel(), zz.ravel()]) elif hasattr(clf, "predict_proba"): z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel(), zz.ravel()])[:, 1] z = z.reshape(xx.shape) vertices, faces, _, _ = measure.marching_cubes(z, 0) # Scale and transform to actual size of the interesting volume vertices = vertices * [x_max - x_min, y_max - y_min, z_max - z_min] / interval vertices += [x_min, y_min, z_min] # and create a mesh to display mesh = Line3DCollection(vertices[faces], facecolor=colors, alpha=alpha) ax.add_collection3d(mesh) return mesh else: xx, yy = np.meshgrid(xx, yy) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) return ax.contourf(xx, yy, Z, 10, colors=colors, alpha=alpha)
def build_geojson_contours(data, ax: Axes, manifest: dict): ax.clear() z = data x = z.mesh2d_face_x[:len(z)] y = z.mesh2d_face_y[:len(z)] variable_name = z.name # capture date and convert to datetime dt = datetime64_to_datetime(z.time) # set title on figure ax.set_title(dt.isoformat()) # build json file name output file_name = '{}.json'.format(dt.isoformat()) # convert to numpy arrays z = z.values x = x.values y = y.values # build grid constraints xi = np.linspace(np.floor(x.min()), np.ceil(x.max()), GRID_SIZE) yi = np.linspace(np.floor(y.min()), np.ceil(y.max()), GRID_SIZE) # build delaunay triangles triang = tri.Triangulation(x, y) # build a list of the triangle coordinates tri_coords = [] for i in range(len(triang.triangles)): tri_coords.append( tuple(zip(x[triang.triangles[i]], y[triang.triangles[i]]))) # filter out large triangles large_triangles = [ i for i, t in enumerate(tri_coords) if circum_radius(*t) > MAX_CIRCUM_RADIUS ] mask = [i in large_triangles for i, _ in enumerate(triang.triangles)] triang.set_mask(mask) # interpolate values from triangle data and build a mesh of data interpolator = tri.LinearTriInterpolator(triang, z) Xi, Yi = np.meshgrid(xi, yi) zi = interpolator(Xi, Yi) contourf = ax.contourf(xi, yi, zi, LEVELS, cmap=plt.cm.jet) # create output directory if it doesn't exist output_path = '/tmp/{}'.format(variable_name) if not os.path.exists(output_path): os.makedirs(output_path) # convert matplotlib contourf to geojson geojsoncontour.contourf_to_geojson( contourf=contourf, min_angle_deg=3.0, ndigits=5, stroke_width=2, fill_opacity=0.5, geojson_filepath=os.path.join(output_path, file_name), ) # update the manifest with the geojson output manifest_entry = { 'date': dt.isoformat(), 'path': os.path.join(variable_name, file_name), } if variable_name not in manifest: manifest[variable_name] = {'geojson': []} manifest[variable_name]['geojson'].append(manifest_entry) return contourf