Python matplotlib.org() Examples
The following are 30
code examples of matplotlib.org().
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
matplotlib
, or try the search function
.
Example #1
Source File: validation.py From stdpopsim with GNU General Public License v3.0 | 6 votes |
def custom_violinplot(ax, data, labels): """ Violin plot with a colour scheme shown in the matplotlib gallery. https://matplotlib.org/3.1.3/gallery/statistics/customized_violin.html """ inds = list(range(1, len(labels)+1)) quartile1, medians, quartile3 = np.percentile(data, [25, 50, 75], axis=1) parts = ax.violinplot(data, vert=False) collections = [parts[x] for x in parts.keys() if x != "bodies"] + parts["bodies"] for pc in collections: pc.set_facecolor("#D43F3A") pc.set_edgecolor("black") pc.set_alpha(1) ax.scatter(medians, inds, marker='o', fc="white", ec="black", s=30, zorder=3) ax.hlines(inds, quartile1, quartile3, color='k', linestyle='-', lw=5) ax.set_yticks(inds) ax.set_yticklabels(labels)
Example #2
Source File: plot.py From cate with MIT License | 6 votes |
def plot_data_frame(df: pd.DataFrame, plot_type: str = 'line', file: str = None, **kwargs) -> Figure: """ Plot a data frame. This is a wrapper of pandas.DataFrame.plot() function. For further documentation please see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html :param df: A pandas dataframe to plot :param plot_type: Plot type :param file: path to a file in which to save the plot :param kwargs: Keyword arguments to pass to the underlying pandas.DataFrame.plot function """ if not isinstance(df, pd.DataFrame): raise ValidationError('"df" must be of type "pandas.DataFrame"') ax = df.plot(kind=plot_type, figsize=(8, 4), **kwargs) figure = ax.get_figure() if file: figure.savefig(file) return figure if not in_notebook() else None
Example #3
Source File: renderer.py From corrscope with BSD 2-Clause "Simplified" License | 6 votes |
def get_frame(self) -> ByteBuffer: """Returns bytes with shape (h, w, self.bytes_per_pixel). The actual return value's shape may be flat. """ self._redraw_over_background() canvas = self._fig.canvas # Agg is the default noninteractive backend except on OSX. # https://matplotlib.org/faq/usage_faq.html if not isinstance(canvas, self._canvas_type): raise RuntimeError( f"oh shit, cannot read data from {obj_name(canvas)} != {self._canvas_type.__name__}" ) buffer_rgb = self._canvas_to_bytes(canvas) assert len(buffer_rgb) == self.w * self.h * self.bytes_per_pixel return buffer_rgb # Pre-rendered background
Example #4
Source File: matplotlib_example.py From wxGlade with MIT License | 6 votes |
def on_button_draw_circle(self, event): # draw a circle; canvas coordinates / pixels # https://matplotlib.org/api/_as_gen/matplotlib.patches.Circle.html x,y,radius = self._get_floats("text_circle_",("x","y","radius")) if None in (x,y,radius): return None colour, width, style = self._get_styles() # implement method? self.matplotlib_canvas.draw_rectangle( (x,y), width, height, angle ) patch = matplotlib.patches.Circle((x,y), radius, figure=self.canvas.figure, color=colour, linewidth=width, linestyle=style) patch.set_picker(5) # enable picking, i.e. the user can select this with the mouse self.canvas.figure.patches.append(patch) # show the updates self.canvas.draw() self.set_history_buttons() #################################################################################################################### # helpers
Example #5
Source File: matplotlib_example.py From wxGlade with MIT License | 6 votes |
def on_button_plot_circle(self, event): # draw a circle; canvas coordinates / pixels # https://matplotlib.org/api/_as_gen/matplotlib.patches.Circle.html x,y,radius = self._get_floats("text_plot_circle_",("x","y","radius")) if None in (x,y,radius): return None axes = self.get_axes() colour, width, style = self._get_styles() circle = matplotlib.patches.Circle((x,y), radius, figure=self.canvas.figure, color=colour, linewidth=width, linestyle=style) circle.set_picker(5) # enable picking, i.e. the user can select this with the mouse axes.add_patch(circle) axes.autoscale(True, 'both', True) # ensure that it is visible # show the updates self.canvas.draw() self.set_history_buttons() #################################################################################################################### # draw elements on canvas (by pixels) # see https://matplotlib.org/api/artist_api.html # rectangles, arrows, circles: https://matplotlib.org/api/patches_api.html
Example #6
Source File: 10a PSG Plot (Matplotlib numpy pyplot(y=sinx)) .py From PySimpleGUI with GNU Lesser General Public License v3.0 | 6 votes |
def draw_figure(canvas, figure, loc = (0,0)): figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) return photo #------------ Matplotlib code ---------------------- #see https://matplotlib.org/
Example #7
Source File: gui_annot_center_correction.py From pyImSegm with BSD 3-Clause "New" or "Revised" License | 6 votes |
def arg_parse_params(): """ SEE: https://docs.python.org/3/library/argparse.html :return dict: """ parser = argparse.ArgumentParser() parser.add_argument('-imgs', '--path_images', type=str, required=False, help='path to dir and image pattern', default=PATH_IMAGES) parser.add_argument('-csv', '--path_csv', type=str, required=False, help='path to the CSV directory', default=PATH_CSV) parser.add_argument('-info', '--path_info', type=str, required=False, help='path to file with complete info', default=None) params = vars(parser.parse_args()) for k in (k for k in params if 'path' in k): if not params[k]: continue params[k] = os.path.abspath(os.path.expanduser(params[k])) p = os.path.dirname(params[k]) if '*' in params[k] else params[k] assert os.path.exists(p), 'missing: %s' % p logging.info('ARG PARAMETERS: \n %r', params) return params
Example #8
Source File: aggregation_api.py From aggregation with Apache License 2.0 | 6 votes |
def __plot_image__(self,subject_id,axes): # TODO - still learning about Matplotlib and axes # see http://matplotlib.org/users/artists.html fname = self.__image_setup__(subject_id) exception = None for i in range(10): try: # fig = plt.figure() # ax = fig.add_subplot(1, 1, 1) image_file = cbook.get_sample_data(fname) image = plt.imread(image_file) # fig, ax = plt.subplots() im = axes.imshow(image) return self.__get_subject_dimension__(subject_id) except IOError as e: # try downloading that image again os.remove(fname) self.__image_setup__(subject_id) exception = e raise exception or Exception('Failed to plot image')
Example #9
Source File: plotting.py From kvae with MIT License | 6 votes |
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'): # https://matplotlib.org/examples/color/colormaps_reference.html patches = [] for pos in var: if shape == 'c': patches.append(mpatches.Circle(pos, r)) elif shape == 'r': patches.append(mpatches.RegularPolygon(pos, 4, r)) elif shape == 's': patches.append(mpatches.RegularPolygon(pos, 6, r)) colors = np.linspace(start_color, .9, len(patches)) collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.) collection.set_array(np.array(colors)) collection.set_clim(0, 1) return collection
Example #10
Source File: keyboard_gui.py From synthesizer with GNU Lesser General Public License v3.0 | 6 votes |
def do_plot(self, osc): if not matplotlib: self.statusbar["text"] = "Cannot plot! To plot things, you need to have matplotlib installed!" return o = self.create_osc(None, None, osc.input_freq.get(), osc, all_oscillators=self.oscillators).blocks() blocks = list(itertools.islice(o, self.synth.samplerate//params.norm_osc_blocksize)) # integrating matplotlib in tikinter, see http://matplotlib.org/examples/user_interfaces/embedding_in_tk2.html fig = Figure(figsize=(8, 2), dpi=100) axis = fig.add_subplot(111) axis.plot(sum(blocks, [])) axis.set_title("Waveform") self.do_close_waveform() canvas = FigureCanvasTkAgg(fig, master=self.waveform_area) canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=1) canvas.draw() close_waveform = tk.Button(self.waveform_area, text="Close waveform", command=self.do_close_waveform) close_waveform.pack(side=tk.RIGHT)
Example #11
Source File: visualization.py From chemml with BSD 3-Clause "New" or "Revised" License | 5 votes |
def matplotlib_font(self, family='DejaVu Sans', size=18, weight='normal', style='normal', variant='normal'): """ The matplotlib_font function sets custom font properties. Notes ----- Changing these parameters wil affect all the plots in your working session. Parameters ---------- family: string, optional (default = 'normal') check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html size: integer or string, optional (default = 18) check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html weight: string, optional (default = 'normal') check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html style: string, optional (default = 'normal') check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html variant: string, optional (default = 'normal') check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html Returns ------- """ matplotlib.rcParams.update( {'font.size': size, 'font.weight': weight, 'font.family': family, 'font.style': style, 'font.variant': variant})
Example #12
Source File: stereographic_projection.py From dials with BSD 3-Clause "New" or "Revised" License | 5 votes |
def stereographic_projection(points, reference_poles): # https://doi.org/10.1107/S0021889868005029 # J. Appl. Cryst. (1968). 1, 68-70 # The construction of stereographic projections by computer # G. K. Stokes, S. R. Keown and D. J. Dyson assert len(reference_poles) == 3 r_0, r_1, r_2 = reference_poles projections = flex.vec2_double() for p in points: r_i = matrix.col(p) # theta is the angle between r_i and the plane normal, r_0 cos_theta = r_i.cos_angle(r_0) if cos_theta < 0: r_i = -r_i cos_theta = r_i.cos_angle(r_0) # alpha is the angle between r_i and r_1 cos_alpha = r_i.cos_angle(r_1) theta = math.acos(cos_theta) cos_phi = cos_alpha / math.sin(theta) if abs(cos_phi) > 1: cos_phi = math.copysign(1, cos_phi) phi = math.acos(cos_phi) N = r_i.dot(r_2) r = math.tan(theta / 2) x = r * cos_phi y = r * math.sin(phi) y = math.copysign(y, N) projections.append((x, y)) return projections
Example #13
Source File: cluster_unit_cell.py From dials with BSD 3-Clause "New" or "Revised" License | 5 votes |
def do_cluster_analysis(crystal_symmetries, params): ucs = Cluster.from_crystal_symmetries(crystal_symmetries) if params.plot.show or params.plot.name is not None: if not params.plot.show: import matplotlib # http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear matplotlib.use("Agg") # use a non-interactive backend import matplotlib.pyplot as plt plt.figure("Andrews-Bernstein distance dendogram", figsize=(12, 8)) ax = plt.gca() clusters, cluster_axes = ucs.ab_cluster( params.threshold, log=params.plot.log, ax=ax, write_file_lists=False, doplot=True, ) print(unit_cell_info(clusters)) plt.tight_layout() if params.plot.name is not None: plt.savefig(params.plot.name) if params.plot.show: plt.show() else: clusters, cluster_axes = ucs.ab_cluster( params.threshold, log=params.plot.log, write_file_lists=False, doplot=False ) print(unit_cell_info(clusters)) return clusters
Example #14
Source File: plot.py From code-jam-5 with MIT License | 5 votes |
def get_map_format(): """ Source: https://matplotlib.org/basemap/api/basemap_api.html Returns: Basemap: Constructed world basemap """ world_map = Basemap(projection="cyl", llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution="c") Plotter.draw_map_details(world_map) return world_map
Example #15
Source File: plot.py From code-jam-5 with MIT License | 5 votes |
def get_color_maps(): # https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html color_maps = ["seismic", "coolwarm", "bwr", "gnuplot2", "jet"] return color_maps
Example #16
Source File: gui.py From viscm with MIT License | 5 votes |
def save_colormap(self, filepath): with open(filepath, 'w') as f: xp, yp, fixed = self.control_point_model.get_control_points() rgb, _ = self.cmap_model.get_sRGB(num=256) hex_blob = "" for color in rgb: for component in color: hex_blob += "%02x" % (int(round(component * 255))) usage_hints = ["red-green-colorblind-safe", "greyscale-safe"] if self.cmtype == "diverging": usage_hints.append("diverging") elif self.cmtype == "linear": usage_hints.append("sequential") xp, yp, fixed = self.control_point_model.get_control_points() extensions = {"min_Jp" : self.min_Jp, "max_Jp" : self.max_Jp, "xp" : xp, "yp" : yp, "fixed" : fixed, "filter_k" : self.cmap_model.filter_k, "cmtype" : self.cmtype, "uniform_colorspace" : self._uniform_space, "spline_method" : self.method } json.dump({"content-type": "application/vnd.matplotlib.colormap-v1+json", "name": self.name, "license":"http://creativecommons.org/publicdomain/zero/1.0/", "usage-hints": usage_hints, "colorspace" : "sRGB", "domain" : "continuous", "colors" : hex_blob, "extensions" : {"https://matplotlib.org/viscm" : extensions} }, f, indent=4) print("Saved")
Example #17
Source File: renderer.py From corrscope with BSD 2-Clause "Simplified" License | 5 votes |
def _save_background(self) -> None: """ Draw static background. """ # https://stackoverflow.com/a/8956211 # https://matplotlib.org/api/animation_api.html#funcanimation fig = self._fig fig.canvas.draw() self.bg_cache = fig.canvas.copy_from_bbox(fig.bbox)
Example #18
Source File: plot_helper.py From MAST-ML with MIT License | 5 votes |
def make_fig_ax_square(aspect='equal', aspect_ratio=1): """ Method to make square shaped matplotlib figure and axes objects. Using Object Oriented interface from https://matplotlib.org/gallery/api/agg_oo_sgskip.html Args: aspect: (str), 'equal' denotes x and y aspect will be equal (i.e. square) aspect_ratio: (float), aspect ratio for figure and axes creation Returns: fig: (matplotlib fig object), a matplotlib figure object with the specified aspect ratio ax: (matplotlib ax object), a matplotlib axes object with the specified aspect ratio """ # Set image aspect ratio: w, h = figaspect(aspect_ratio) fig = Figure(figsize=(w,h)) FigureCanvas(fig) ax = fig.add_subplot(111, aspect=aspect) return fig, ax
Example #19
Source File: plot_helper.py From MAST-ML with MIT License | 5 votes |
def make_fig_ax(aspect_ratio=0.5, x_align=0.65, left=0.10): """ Method to make matplotlib figure and axes objects. Using Object Oriented interface from https://matplotlib.org/gallery/api/agg_oo_sgskip.html Args: aspect_ratio: (float), aspect ratio for figure and axes creation x_align: (float), x position to draw edge of figure. Needed so can display stats alongside plot left: (float), the leftmost position to draw edge of figure Returns: fig: (matplotlib fig object), a matplotlib figure object with the specified aspect ratio ax: (matplotlib ax object), a matplotlib axes object with the specified aspect ratio """ # Set image aspect ratio: w, h = figaspect(aspect_ratio) fig = Figure(figsize=(w,h)) FigureCanvas(fig) # Set custom positioning, see this guide for more details: # https://python4astronomers.github.io/plotting/advanced.html #left = 0.10 bottom = 0.15 right = 0.01 top = 0.05 width = x_align - left - right height = 1 - bottom - top ax = fig.add_axes((left, bottom, width, height), frameon=True) fig.set_tight_layout(False) return fig, ax
Example #20
Source File: utils.py From dynamo-release with BSD 3-Clause "New" or "Revised" License | 5 votes |
def set_colorbar(ax): """https://matplotlib.org/3.1.0/gallery/axes_grid1/demo_colorbar_with_inset_locator.html""" from mpl_toolkits.axes_grid1.inset_locator import inset_axes axins = inset_axes(ax, width="2.5%", # width = 5% of parent_bbox width height="20%", # height : 50% # loc='lower left', # bbox_to_anchor=(1.05, 0., 1, 1), # bbox_transform=ax.transAxes, # borderpad=0, ) return axins
Example #21
Source File: plot_occluded_activations.py From kaggle-dr with MIT License | 5 votes |
def accumulate_patches_into_heatmaps(self, all_test_output, outpath_prefix=''): outpath = "plots/%s_%s.png" % (outpath_prefix, path.splitext(path.basename(self.test_imagepath))[0]) # http://matplotlib.org/examples/axes_grid/demo_axes_grid.html fig = plt.figure() grid = AxesGrid(fig, 143, # similar to subplot(143) nrows_ncols = (1, 1)) orig_img = imread(self.test_imagepath+'.png') grid[0].imshow(orig_img) grid = AxesGrid(fig, 144, # similar to subplot(144) nrows_ncols = (2, 2), axes_pad = 0.15, label_mode = "1", share_all = True, cbar_location="right", cbar_mode="each", cbar_size="7%", cbar_pad="2%", ) for klass in xrange(all_test_output.shape[1]): accumulator = numpy.zeros(self.ds.image_shape[:2]) normalizer = numpy.zeros(self.ds.image_shape[:2]) for n in xrange(self.num_patch_centers): i_start,i_end,j_start,j_end = self.nth_patch(n) accumulator[i_start:i_end, j_start:j_end] += all_test_output[n,klass] normalizer[i_start:i_end, j_start:j_end] += 1 normalized_img = accumulator / normalizer im = grid[klass].imshow(normalized_img, interpolation="nearest", vmin=0, vmax=1) grid.cbar_axes[klass].colorbar(im) grid.axes_llc.set_xticks([]) grid.axes_llc.set_yticks([]) print("Saving figure as: %s" % outpath) plt.savefig(outpath, dpi=600, bbox_inches='tight')
Example #22
Source File: plots.py From AlphaPy with Apache License 2.0 | 5 votes |
def plot_distribution(df, target, tag='eda', directory=None): r"""Display a Distribution Plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``target`` feature. target : str The target variable for the distribution plot. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.distplot.html """ logger.info("Generating Distribution Plot") # Generate the distribution plot dist_plot = sns.distplot(df[target]) dist_fig = dist_plot.get_figure() # Save the plot write_plot('seaborn', dist_fig, 'distribution_plot', tag, directory) # # Function plot_box #
Example #23
Source File: plots.py From AlphaPy with Apache License 2.0 | 5 votes |
def plot_time_series(df, target, tag='eda', directory=None): r"""Plot time series data. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``target`` feature. target : str The target variable for the time series plot. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.tsplot.html """ logger.info("Generating Time Series Plot") # Generate the time series plot ts_plot = sns.tsplot(data=df[target]) ts_fig = ts_plot.get_figure() # Save the plot write_plot('seaborn', ts_fig, 'time_series_plot', tag, directory) # # Function plot_candlestick #
Example #24
Source File: aggregation_api.py From aggregation with Apache License 2.0 | 5 votes |
def __image_setup__(self,subject_id,download=True): """ get the local file name for a given subject id and downloads that image if necessary :param subject_id: :return: """ data = self.__panoptes_call__("subjects/"+str(subject_id)+"?") # url = str(data["subjects"][0]["locations"][0]["image/jpeg"]) image_paths = [] for image in data["subjects"][0]["locations"]: if "image/jpeg" in image: url = image["image/jpeg"] elif "image/png" in image: url = image["image/png"] else: raise Exception('Unknown image type: %s' % image) slash_index = url.rfind("/") fname = url[slash_index+1:] url = "http://zooniverse-static.s3.amazonaws.com/panoptes-uploads.zooniverse.org/production/subject_location/"+url[slash_index+1:] path = base_directory+"/Databases/images/"+fname image_paths.append(path) if not(os.path.isfile(path)): if download: print("downloading",url,path) urllib.urlretrieve(url, path) # raise ImageNotDownloaded() return image_paths
Example #25
Source File: evaluation.py From imageatm with Apache License 2.0 | 5 votes |
def _is_in_ipython_mode(self): try: __IPYTHON__ return True except NameError: ## TODO: Is this obsolete? Please remove! # Suppress figure window in terminal # https://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear import matplotlib matplotlib.use('Agg') return False
Example #26
Source File: hicPlotAverageRegions.py From HiCExplorer with GNU General Public License v3.0 | 4 votes |
def parse_arguments(args=None): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False, description=""" hicPlotAverage regions plots the data computed by hicAverageRegions. It shows the summed up and averaged regions around all given reference points. This tool is useful to plot differences at certain reference points as for example TAD boundaries between samples. """) parserRequired = parser.add_argument_group('Required arguments') parserRequired.add_argument('--matrix', '-m', help='The averaged regions file computed by hicAverageRegions (npz file).', required=True) parserRequired.add_argument('--outputFile', '-o', help='The averaged regions plot.', required=True) parserOpt = parser.add_argument_group('Optional arguments') parserOpt.add_argument('--log1p', help='Plot log1p of the matrix values.', action='store_true') parserOpt.add_argument('--log', help='Plot log of the matrix values.', action='store_true') parserOpt.add_argument('--colorMap', help='Color map to use for the heatmap. Available ' 'values can be seen here: ' 'http://matplotlib.org/examples/color/colormaps_reference.html', default='hot_r') parserOpt.add_argument('--vMin', help='Minimum score value.', type=float, default=None) parserOpt.add_argument('--vMax', help='Maximum score value.', type=float, default=None) parserOpt.add_argument('--dpi', help='Resolution of image if' 'ouput is a raster graphics image (e.g png, jpg).', type=int, default=300) parserOpt.add_argument('--help', '-h', action='help', help='show this help message and exit') parserOpt.add_argument('--version', action='version', version='%(prog)s {}'.format(__version__)) return parser
Example #27
Source File: plots.py From AlphaPy with Apache License 2.0 | 4 votes |
def plot_scatter(df, features, target, tag='eda', directory=None): r"""Plot a scatterplot matrix, also known as a pair plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the features. features: list of str The features to compare in the scatterplot. target : str The target variable for contrast. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- https://seaborn.pydata.org/examples/scatterplot_matrix.html """ logger.info("Generating Scatter Plot") # Get the feature subset features.append(target) df = df[features] # Generate the pair plot sns.set() sns_plot = sns.pairplot(df, hue=target) # Save the plot write_plot('seaborn', sns_plot, 'scatter_plot', tag, directory) # # Function plot_facet_grid #
Example #28
Source File: plots.py From AlphaPy with Apache License 2.0 | 4 votes |
def plot_facet_grid(df, target, frow, fcol, tag='eda', directory=None): r"""Plot a Seaborn faceted histogram grid. Parameters ---------- df : pandas.DataFrame The dataframe containing the features. target : str The target variable for contrast. frow : list of str Feature names for the row elements of the grid. fcol : list of str Feature names for the column elements of the grid. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.FacetGrid.html """ logger.info("Generating Facet Grid") # Calculate the number of bins using the Freedman-Diaconis rule. tlen = len(df[target]) tmax = df[target].max() tmin = df[target].min() trange = tmax - tmin iqr = df[target].quantile(Q3) - df[target].quantile(Q1) h = 2 * iqr * (tlen ** (-1/3)) nbins = math.ceil(trange / h) # Generate the pair plot sns.set(style="darkgrid") fg = sns.FacetGrid(df, row=frow, col=fcol, margin_titles=True) bins = np.linspace(tmin, tmax, nbins) fg.map(plt.hist, target, color="steelblue", bins=bins, lw=0) # Save the plot write_plot('seaborn', fg, 'facet_grid', tag, directory) # # Function plot_distribution #
Example #29
Source File: plots.py From AlphaPy with Apache License 2.0 | 4 votes |
def plot_box(df, x, y, hue, tag='eda', directory=None): r"""Display a Box Plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``x`` and ``y`` features. x : str Variable name in ``df`` to display along the x-axis. y : str Variable name in ``df`` to display along the y-axis. hue : str Variable name to be used as hue, i.e., another data dimension. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.boxplot.html """ logger.info("Generating Box Plot") # Generate the box plot box_plot = sns.boxplot(x=x, y=y, hue=hue, data=df) sns.despine(offset=10, trim=True) box_fig = box_plot.get_figure() # Save the plot write_plot('seaborn', box_fig, 'box_plot', tag, directory) # # Function plot_swarm #
Example #30
Source File: gui.py From viscm with MIT License | 4 votes |
def load(self, path): self.path = path if os.path.isfile(path): _, extension = os.path.splitext(path) if extension == ".py": self.can_edit = True self.cmtype = "linear" self.method = "Bezier" ns = {'__name__': '', '__file__': os.path.basename(self.path), } with open(self.path) as f: code = compile(f.read(), os.path.basename(self.path), 'exec') exec(code, globals(), ns) self.params = ns.get('parameters', {}) if not self.params: self.can_edit = False if "min_JK" in self.params: self.params["min_Jp"] = self.params.pop("min_JK") self.params["max_Jp"] = self.params.pop("max_JK") self.cmap = ns.get("test_cm", None) self.name = self.cmap.name elif extension == ".jscm": self.can_edit = False with open(self.path) as f: data = json.loads(f.read()) self.name = data["name"] colors = data["colors"] colors = [colors[i:i + 6] for i in range(0, len(colors), 6)] colors = [[int(c[2 * i:2 * i + 2], 16) / 255 for i in range(3)] for c in colors] self.cmap = matplotlib.colors.ListedColormap(colors, self.name) if "extensions" in data and "https://matplotlib.org/viscm" in data["extensions"]: self.can_edit = True self.params = {k:v for k,v in data["extensions"]["https://matplotlib.org/viscm"].items() if k in {"xp", "yp", "min_Jp", "max_Jp", "fixed", "filter_k", "uniform_space"}} self.params["name"] = self.name self.cmtype = data["extensions"]["https://matplotlib.org/viscm"]["cmtype"] self.method = data["extensions"]["https://matplotlib.org/viscm"]["spline_method"] self.uniform_space = data["extensions"]["https://matplotlib.org/viscm"]["uniform_colorspace"] else: sys.exit("Unsupported filetype") else: self.can_edit = False self.cmap = lookup_colormap_by_name(path) self.name = path