Best Python code snippet using pytest-play_python
figures.py
Source:figures.py
...67 """68 path = join(dirpath, name+'.{}'.format(fmt))69 kw = dict(dpi=dpi, transparent=transparent, rasterized=rasterized)70 fig.savefig(path, format=fmt, **kwargs)71 def _add_markers(self, x, y, c, **kwargs):72 """73 Add markers to axis.74 Args:75 x, y (array like) - marker x and y positions76 c (array like) - marker colors77 kwargs: keyword arguments for matplotlib.pyplot.scatter78 """79 if len(self.fig.axes) == 0:80 ax = self.fig.subplots()81 ax = self.fig.axes[0]82 # add markers to plot83 ax.scatter(x, y, c=c, **kwargs)84 def format(self, **kwargs):85 """ Format all figure axes. """86 for ax in self.fig.axes:87 self.format_axis(ax, **kwargs)88 def format_axis(self, ax):89 """ Format individual axis. """90 pass91class CellSelection(Figure):92 """93 Visualize cell selection by overlaying cell position markers on top of an image of a single RGB layer.94 Inherited attributes:95 name (str) - figure name ('selection')96 directory (str) - default path for saving figure97 fig (matplotlib.figure.Figure)98 axes (matplotlib.axes.AxesSubplots)99 """100 def __init__(self, layer, data, channel='r', **kwargs):101 """102 Instantiate cell selection figure.103 Args:104 layer (Layer) - RGB image layer105 data (pd.DataFrame) - selected cell measurement data106 channel (str) - color channel to be added107 kwargs: keyword arguments for render108 """109 Figure.__init__(self, name='selection')110 self.render(layer, data, **kwargs)111 def render(self, layer, data, channel='r', figsize=(3, 3)):112 """113 Render figure.114 Args:115 layer (Layer) - RGB image layer116 data (pd.DataFrame) - selected cell measurement data117 channel (str) - color channel to be added118 figsize (tuple) - figure dimensions119 """120 # create figure121 self.fig = self.create_figure(figsize)122 self.add_axes()123 # add image124 self.add_image(layer, channel=channel)125 # add cell position markers126 self.add_markers(data)127 def add_image(self, layer, channel='r'):128 """129 Add scalar image to figure.130 Args:131 layer (Layer) - RGB image layer132 channel (str) - color channel to be added133 """134 _ = layer.get_channel(channel).show(ax=ax, segments=False, cmap=None)135 _ = ax.axis('off')136 def add_markers(self, data, color_by='genotype', xykey=None, **kwargs):137 """138 Add cell position markers to axis.139 Args:140 data (pd.DataFrame) - selected cell measurement data141 color_by (str) - cell measurement attribute used to color markers142 xykey (list) - attribute keys for cell x/y positions143 kwargs: keyword arguments for markers144 """145 if xykey is None:146 xykey = ['centroid_x', 'centroid_y']147 # get cell coordinates and color vector148 x, y = data[xykey].values.T149 # get color vector and colormap150 c = data[color_by]151 cmap = ListedColormap(['y', 'c', 'm'], 'indexed', 3)152 # add markers to plot153 self._add_markers(x, y, c, cmap=cmap, vmin=0, vmax=2, **kwargs)154class Scatterplot(Figure):155 """156 Scatter points in XY plane.157 Attributes:158 xvar, yvar (str) - cell measurement features to be scattered159 Inherited attributes:160 name (str) - figure name161 directory (str) - default path for saving figure162 fig (matplotlib.figure.Figure)163 axes (matplotlib.axes.AxesSubplots)164 """165 def __init__(self, data, xvar, yvar, name, **kwargs):166 """167 Instantiate scatter plot.168 Args:169 data (pd.DataFrame) - selected cell measurement data170 xvar, yvar (str) - cell measurement features to be scattered171 name (str) - figure name172 kwargs: keyword arguments for173 """174 Figure.__init__(self, name=name)175 self.xvar, self.yvar = xvar, yvar176 self.render(data, **kwargs)177 def render(self, data, figsize=(2, 2)):178 """179 Render figure.180 Args:181 data (pd.DataFrame) - selected cell measurement data182 figsize (tuple) - figure dimensions183 """184 # create figure185 self.fig = self.create_figure(figsize)186 self.add_axes()187 # add data188 self._add_markers(data[self.xvar], data[self.yvar], c='k', s=1)189 # format axes190 self.format()191 def format_axis(self, ax):192 """193 Format axis.194 Args:195 ax (matplotlib.axes.AxesSubplot)196 """197 _ = ax.spines['top'].set_visible(False)198 _ = ax.spines['right'].set_visible(False)199 _ = ax.set_xlabel(self.x)200 _ = ax.set_ylabel(self.y)201class BackgroundCorrelation(Scatterplot):202 """...
tk_geo_mapper.py
Source:tk_geo_mapper.py
1# pylint: disable=C04132import sys3import os4import tkinter as tk5from PIL import Image, ImageTk6import numpy as np7sys.path.insert(0, os.getcwd())8from geo_mapping.geo_mapper import MapFitter, MapCoordinateTransformer9class TkGeoMapper:10 '''11 Given a latitude and longitude series describing a track.12 Fetches a map that fits the data. Adds the map to a canvas. Draws13 the track on the canvas overlaying the map.14 This was used for MapFitter images and other geo mapper classes.15 Look at GeoMapScrubber for a more useful widget that allows scrubbing16 forward and backward on a track in a map.17 '''18 def __init__(self,19 latitude_series: np.ndarray,20 longitude_series: np.ndarray,21 marker_positions=None,22 track_color='red'23 ):24 self._latitude_series = latitude_series25 self._longitude_series = longitude_series26 self._marker_positions = marker_positions27 self._track_color = track_color28 if self._marker_positions is None:29 self._add_markers = False30 else:31 self._add_markers = True32 assert self._latitude_series.size == self._longitude_series.size, \33 (f'latitude_series ({self._latitude_series.size}) '34 f'must be same size as longitude_series ({self._longitude_series.size})')35 self._map_fitter = MapFitter(self._latitude_series,36 self._longitude_series,37 add_markers=self._add_markers,38 )39 self._map_coordinate_transformer = \40 MapCoordinateTransformer(self._map_fitter.get_center_latitude(),41 self._map_fitter.get_center_longitude(),42 self._map_fitter.get_map_scaled_width(),43 self._map_fitter.get_map_scaled_height(),44 self._map_fitter.get_zoom(),45 self._map_fitter.get_scale(),46 )47 # laxy init48 self._root = None49 self._canvas = None50 self._map_on_canvas = None51 self._map_image = None52 self._x_y_series = None53 self._x_y_series_flattened = None54 def _setup_ui(self):55 self._root = tk.Tk()56 self._canvas = tk.Canvas(master=self._root,57 width=self._map_fitter.get_map_scaled_width(),58 height=self._map_fitter.get_map_scaled_height(),59 )60 self._canvas.grid(row=0, column=0)61 self._map_on_canvas = self._canvas.create_image(0, 0, anchor='nw')62 self._canvas.itemconfig(self._map_on_canvas, image=self._get_map_image())63 self._canvas.create_line(*self._get_x_y_series_flattened(),64 fill=self._track_color,65 )66 self._add_marker_dots()67 def _add_marker_dots(self):68 if self._marker_positions is not None:69 for position in self._marker_positions:70 y = self._map_coordinate_transformer.get_y_for_latitude(position[0])71 x = self._map_coordinate_transformer.get_x_for_longitude(position[1])72 self._canvas.create_oval(x-2, y-2, x+2, y+2, fill='blue')73 def _get_map_image(self):74 if self._map_image is None:75 self._map_image = ImageTk.PhotoImage(Image.open(self._map_fitter.get_map()))76 return self._map_image77 def _get_x_y_series(self):78 if self._x_y_series is None:79 r = []80 for idx in range(self._latitude_series.size):81 x = self._map_coordinate_transformer.get_x_for_longitude(self._longitude_series[idx]) # pylint: disable=C030182 y = self._map_coordinate_transformer.get_y_for_latitude(self._latitude_series[idx])83 r.append([x, y])84 self._x_y_series = r85 return self._x_y_series86 def _get_x_y_series_flattened(self):87 if self._x_y_series_flattened is None:88 self._x_y_series_flattened = [item for sublist in self._get_x_y_series() for item in sublist] # pylint: disable=C030189 return self._x_y_series_flattened90 def run(self):91 self._setup_ui()92 self._root.mainloop()...
create_map.py
Source:create_map.py
...21 22 m = folium.Map(location=[lat, lng], tiles='Stamen Terrain', zoom_start=4)23 m.choropleth(geo_data=open(filename).read())24 return m25def _add_markers(m, features):26 for feature in features:27 long, lat = feature['geometry']['coordinates']28 address = feature['properties']['Response']29 folium.CircleMarker(30 location=[lat, long],31 radius=8,32 popup=address,33 weight = 2,34 color='#3186cc',35 fill=True,36 fill_color='#ff9966',37 fill_opacity = .7538 ).add_to(m)39 40def folium_map(filename):41 with open(filename) as f:42 data = json.load(f)43 features = data['features']44 lat, long = get_center_map(data)45 m = folium.Map(location=[lat, long], zoom_start=4)46 _add_markers(m, features)47 ...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!