def double_choropleth(gdf, label_fn=lambda _: "", Rt_col="Rt", Rt_proj_col="Rt_proj", titles=["Current $R_t$", "Projected $R_t$ (1 Week)"], arrangement=(1, 2), label_kwargs={}, mappable=sm): """ plot two choropleths side-by-side based on multiple metrics """ gdf["pt"] = gdf["geometry"].centroid fig, (ax1, ax2) = plt.subplots(*arrangement) for (ax, title, col) in zip((ax1, ax2), titles, (Rt_col, Rt_proj_col)): ax.grid(False) ax.set_xticks([]) ax.set_yticks([]) ax.set_title(title, loc="left", fontdict=theme.label) gdf.plot(color=[mappable.to_rgba(_) for _ in gdf[col]], ax=ax, edgecolors="black", linewidth=0.5, missing_kwds={ "color": theme.accent, "edgecolor": "white" }) if label_fn is not None: for (_, row) in gdf.iterrows(): label = label_fn(row) Rt_c, Rt_p = round(row[Rt_col], 2), round(row[Rt_proj_col], 2) a1 = ax1.annotate(s=f"{label}{Rt_c}", xy=list(row["pt"].coords)[0], ha="center", fontfamily=theme.note["family"], color="white", **label_kwargs) a2 = ax2.annotate(s=f"{label}{Rt_p}", xy=list(row["pt"].coords)[0], ha="center", fontfamily=theme.note["family"], color="white", **label_kwargs) a1.set_path_effects( [Stroke(linewidth=2, foreground="black"), Normal()]) a2.set_path_effects( [Stroke(linewidth=2, foreground="black"), Normal()]) cbar_ax = fig.add_axes([0.95, 0.25, 0.01, 0.5]) cb = fig.colorbar(mappable=mappable, orientation="vertical", cax=cbar_ax) cbar_ax.set_title("$R_t$", fontdict=theme.note) return PlotDevice(fig)
def insert_miniglobe(ax, fig, extent=[-50, -41, -30, -22], center=[-45, -15], location=None, box_color='red', box_alpha=1, box_edge_width=1): # upper left: [0.13, 0.642, 0.2, 0.15] # lower right: [0.7, 0.18, 0.2, 0.2] # if not location: location = [0.75, 0.18, 0.2, 0.2] sub_ax = fig.add_axes(location, projection=ccrs.Orthographic(center[0], center[1])) # Make a nice border around the inset axes. effect = Stroke(linewidth=.1, foreground='black', alpha=0.5) sub_ax.outline_patch.set_path_effects([effect]) sub_ax.coastlines(linewidth=0.00000001, edgecolor='k', alpha=.8) sub_ax.stock_img() extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), facecolor='bisque', edgecolor=box_color, linewidth=box_edge_width, alpha=box_alpha) return sub_ax
def __init__(self, size=1, extent=0.025, label="", loc=2, ax=None, pad=0.6, borderpad=0.5, ppad=0, sep=4, prop=None, frameon=False, colour='black', **kwargs): # size: length of bar in data units. # extent: height of bar ends in axes units. if loc == 'upper right': loc = 1 elif loc == 'upper left': loc = 2 elif loc == 'lower left': loc = 3 elif loc == 'lower right': loc = 4 if colour in ['w', 'white']: fc = 'w' # Foreground colour. ec = 'k' # Edge colour. else: fc = 'k' ec = 'w' trans = ax.get_xaxis_transform() size_bar = matplotlib.offsetbox.AuxTransformBox(trans) rectangle = Rectangle((0, 0), width=size, height=extent, fc=fc, ec=ec) size_bar.add_artist(rectangle) text = matplotlib.offsetbox.TextArea(label, minimumdescent=False, textprops={'color': fc}) path_effects = [ Stroke(linewidth=2, foreground=ec, alpha=0.75), Normal() ] text._text.set_path_effects(path_effects) self.vpac = matplotlib.offsetbox.VPacker( \ children=[size_bar, text], align="center", pad=ppad, sep=sep) matplotlib.offsetbox.AnchoredOffsetbox.__init__( \ self, loc, pad=pad, borderpad=borderpad, child=self.vpac, prop=prop, frameon=frameon)
def display_map(f1_radiances_subset_reproj, utm_resampler, fname): lons, lats = utm_resampler.area_def.get_lonlats() crs = ccrs.PlateCarree() extent = [np.min(lons), np.max(lons), np.min(lats), np.max(lats)] u_padding = 0.25 l_padding = 1 padded_extent = [ np.min(lons) - u_padding, np.max(lons) + u_padding, np.min(lats) - u_padding, np.max(lats) + l_padding ] ax = plt.axes(projection=crs) ax.set_extent(padded_extent) ax.coastlines(resolution='50m', color='black', linewidth=1) gridlines = ax.gridlines(draw_labels=True) ax.imshow(f1_radiances_subset_reproj, transform=crs, extent=extent, origin='upper', cmap='gray') # Create an inset GeoAxes showing the location sub_ax = plt.axes([0.5, 0.66, 0.2, 0.2], projection=ccrs.PlateCarree()) sub_ax.set_extent([95, 145, -20, 10]) # Make a nice border around the inset axes. effect = Stroke(linewidth=4, foreground='wheat', alpha=0.5) sub_ax.outline_patch.set_path_effects([effect]) # Add the land, coastlines and the extent of the Solomon Islands. sub_ax.add_feature(cartopy.feature.LAND) sub_ax.coastlines() extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), color='none', edgecolor='blue', linewidth=2) plt.savefig(os.path.join(fp.path_to_plume_tracking_visualisations, 'maps', fname), bbox_inches='tight', dpi=300) plt.close()
def test_patheffect1(): ax1 = plt.subplot(111) ax1.imshow([[1, 2], [2, 3]]) txt = ax1.annotate("test", (1., 1.), (0., 0), arrowprops=dict(arrowstyle="->", connectionstyle="angle3", lw=2), size=20, ha="center", path_effects=[withStroke(linewidth=3, foreground="w")]) txt.arrow_patch.set_path_effects([Stroke(linewidth=5, foreground="w"), Normal()]) ax1.grid(True, linestyle="-") pe = [withStroke(linewidth=3, foreground="w")] for l in ax1.get_xgridlines() + ax1.get_ygridlines(): l.set_path_effects(pe)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # if "main" axes if not kwargs.get("sharex"): text = AnchoredText("PRELIMINARY", loc="center", frameon=False, borderpad=0, prop=dict(alpha=0.15, fontsize=50, rotation=30, color="black")) text.set_path_effects( [Stroke(linewidth=3, foreground="white"), Normal()]) text.set_zorder(1000) self.add_artist(text)
def choropleth(gdf, label_fn=lambda _: "", col="Rt", title="$R_t$", label_kwargs={}, mappable=sm, fig=None, ax=None): """ display choropleth of locations by metric """ gdf["pt"] = gdf["geometry"].centroid if not fig: fig, ax = plt.subplots() ax.grid(False) ax.set_xticks([]) ax.set_yticks([]) if title: ax.set_title(title, loc="left", fontdict=theme.label) gdf.plot(color=[mappable.to_rgba(_) for _ in gdf[col]], ax=ax, edgecolors="black", linewidth=0.5, missing_kwds={ "color": theme.accent, "edgecolor": "white" }) if label_fn is not None: for (_, row) in gdf.iterrows(): label = label_fn(row) value = round(row[col], 2) ax.annotate( s = f"{label}{value}", xy = list(row["pt"].coords)[0], ha = "center", fontfamily = theme.note["family"], color = "black", **label_kwargs, fontweight = "semibold", size = 12)\ .set_path_effects([Stroke(linewidth = 2, foreground = "white"), Normal()]) cbar_ax = fig.add_axes([0.90, 0.25, 0.01, 0.5]) cb = fig.colorbar(mappable=mappable, orientation="vertical", cax=cbar_ax) cbar_ax.set_title("$R_t$", fontdict=theme.note) return PlotDevice(fig)
def plot_global_hc_map(name_str, var, lakes_path, indir_lakedata): # get region specific info from dictionary if name_str == 'global_absolute': levels = np.arange(-1e17, 1.1e17, 0.1e17) elif name_str == 'global': levels = np.arange(-1e19, 1.1e19, 0.1e19) cb_orientation = 'horizontal' path_lakes = lakes_path + name_str + '.shp' # settings clb_label = 'Joule' title_str = name_str + ' heat content anomaly' fig_name = 'Heat_content_' + name_str cmap = 'RdBu_r' #, 'YlOrBr' cmap, norm = mpu.from_levels_and_cmap(levels, cmap, extend='max') lon, lat = get_lonlat(indir_lakedata) LON, LAT = mpu.infer_interval_breaks(lon, lat) # plotting fig, ax = plt.subplots(1, 1, figsize=(13, 8), subplot_kw={'projection': ccrs.PlateCarree()}) ax.add_feature(ctp.feature.OCEAN, color='gainsboro') ax.coastlines(color="grey") # add the data to the map (more info on colormaps: https://matplotlib.org/users/colormaps.html) h = ax.pcolormesh(LON, LAT, var, cmap=cmap, norm=norm) # set grid lines gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.5, color='gainsboro', alpha=0.5) gl.xlines = True gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabels_bottom = None gl.ylabels_right = None effect = Stroke(linewidth=1.5, foreground='darkgray') # set effect for main ax ax.outline_patch.set_path_effects([effect]) # plot the colorbar cbar = mpu.colorbar(h, ax, extend='max', orientation=cb_orientation, pad=0.05) if cb_orientation == 'vertical': cbar.ax.set_ylabel(clb_label, size=16) elif cb_orientation == 'horizontal': cbar.ax.set_xlabel(clb_label, size=16) #ax.set_title(title_str, pad=10) plotdir = '/home/inne/documents/phd/data/processed/isimip_lakeheat/plots/' plt.savefig(plotdir + fig_name + '.png')
import matplotlib.dates as mdt import matplotlib.font_manager as mfm import matplotlib.patches as mpatch import matplotlib.path as mpath import matplotlib.pyplot as plt import matplotlib.transforms as mtrans import numpy as np from matplotlib.patheffects import Normal, Stroke from .cell import Cell, CellRow from .gpf import pure_cmap from .weathercode import WeatherCode from .wxsymbols import wx_symbol_font STROKE = [Stroke(linewidth=0.8, foreground='w'), Normal()] ARROW_VER = [(0, -0.1), (0.66, -0.8), (0, 1), (-0.66, -0.8), (0, -0.1)] ARROW_CODE = [ mpath.Path.MOVETO, mpath.Path.LINETO, mpath.Path.LINETO, mpath.Path.LINETO, mpath.Path.CLOSEPOLY ] ARROW = mpath.Path(ARROW_VER, ARROW_CODE) temp_cmap = pure_cmap('temp') fontpath = os.path.join(os.path.dirname(__file__), 'source.ttf') source_font = mfm.FontProperties(fname=fontpath, size=6) matplotlib.rc('font', family='HelveticaNeue', size=6)
ax = fig.add_subplot(4, 2, 6, xticks=[], yticks=[]) ax.imshow(I, cmap=cmap, origin="lower") ax.text( x, y, "Read me", color="white", transform=ax.transData, bbox={ "facecolor": "black", "edgecolor": "None", "pad": 1, "alpha": 0.75 }, ) ax = fig.add_subplot(4, 2, 7, xticks=[], yticks=[]) ax.imshow(I, cmap=cmap, origin="lower") text = ax.text(x, y, "Read me", color="black", transform=ax.transData) text.set_path_effects([Stroke(linewidth=1.5, foreground="white"), Normal()]) ax = fig.add_subplot(4, 2, 8, xticks=[], yticks=[]) ax.imshow(I, cmap=cmap, origin="lower") text = ax.text(x, y, "Read me", color="white", transform=ax.transData) text.set_path_effects([Stroke(linewidth=1.5, foreground="black"), Normal()]) plt.tight_layout() plt.savefig("../../figures/typography/typography-legibility.pdf", dpi=600) plt.show()
def Arrow(xi, yi, xf, yf, sc=20, fc='#a2e3a2', ec='black', zo=0, st='simple', label=None, lbHa='left', lbVa='center', lbPos='cen', lbFs=10, lbRot=0, lbDx=0, lbDy=0, *args, **kwargs): """ Draw arrow ========== default arguments: mutation_scale = sc fc = fc ec = ec zorder = zo arrowstyle = st lbPos = {'cen', 'tip', 'tail'} styles: Curve - None CurveB -> head_length=0.4,head_width=0.2 BracketB -[ widthB=1.0,lengthB=0.2,angleB=None CurveFilledB -|> head_length=0.4,head_width=0.2 CurveA <- head_length=0.4,head_width=0.2 CurveAB <-> head_length=0.4,head_width=0.2 CurveFilledA <|- head_length=0.4,head_width=0.2 CurveFilledAB <|-|> head_length=0.4,head_width=0.2 BracketA ]- widthA=1.0,lengthA=0.2,angleA=None BracketAB ]-[ widthA=1.0,lengthA=0.2,angleA=None,widthB=1.0,lengthB=0.2,angleB=None Fancy fancy head_length=0.4,head_width=0.4,tail_width=0.4 Simple simple head_length=0.5,head_width=0.5,tail_width=0.2 Wedge wedge tail_width=0.3,shrink_factor=0.5 BarAB |-| widthA=1.0,angleA=None,widthB=1.0,angleB=None """ if not 'mutation_scale' in kwargs: kwargs['mutation_scale'] = sc if not 'fc' in kwargs: kwargs['fc'] = fc if not 'ec' in kwargs: kwargs['ec'] = ec if not 'zorder' in kwargs: kwargs['zorder'] = zo if not 'arrowstyle' in kwargs: kwargs['arrowstyle'] = st if True: # makes arrow tips sharper fa = FancyArrowPatch((xi, yi), (xf, yf), shrinkA=False, shrinkB=False, path_effects=[Stroke(joinstyle='miter')], *args, **kwargs) else: fa = FancyArrowPatch((xi, yi), (xf, yf), shrinkA=False, shrinkB=False, *args, **kwargs) gca().add_patch(fa) if label: if lbPos == 'cen': xm = (xi + xf) / 2.0 ym = (yi + yf) / 2.0 if lbPos == 'tip': xm, ym = xf, yf if lbPos == 'tail': xm, ym = xi, yi gca().text(xm + lbDx, ym + lbDy, label, ha=lbHa, va=lbVa, fontsize=lbFs, rotation=lbRot) return fa
def sbol_recombinase1(ax, type, num, start, end, prev_end, scale, linewidth, opts): """ SBOL recombinase site renderer - forward direction """ # Default parameters color = (0, 0, 0) color2 = (0, 0, 0) start_pad = 0.0 end_pad = 0.0 x_extent = 6.0 y_extent = 6.0 linestyle = '-' # Update default parameters if provided if opts != None: if 'start_pad' in list(opts.keys()): start_pad = opts['start_pad'] if 'end_pad' in list(opts.keys()): end_pad = opts['end_pad'] if 'x_extent' in list(opts.keys()): x_extent = opts['x_extent'] if 'y_extent' in list(opts.keys()): y_extent = opts['y_extent'] if 'linestyle' in list(opts.keys()): linestyle = opts['linestyle'] if 'linewidth' in list(opts.keys()): linewidth = opts['linewidth'] if 'scale' in list(opts.keys()): scale = opts['scale'] if 'color' in list(opts.keys()): color = opts['color'] if 'color2' in list(opts.keys()): color2 = opts['color2'] # Check direction add start padding final_end = end final_start = prev_end y_lower = -1 * y_extent / 2 y_upper = y_extent / 2 if start > end: start = prev_end + end_pad + x_extent + linewidth end = prev_end + end_pad final_end = start + start_pad color = color2 else: start = prev_end + start_pad + linewidth end = start + x_extent final_end = end + end_pad # Draw the site p1 = Polygon([(start, y_lower), (start, y_upper), (end, 0)], edgecolor=(0, 0, 0), facecolor=color, linewidth=linewidth, zorder=11, path_effects=[Stroke(joinstyle="miter")]) ax.add_patch(p1) # Add a label if needed if opts != None and 'label' in list(opts.keys()): if final_start > final_end: write_label(ax, opts['label'], final_end + ((final_start - final_end) / 2.0), opts=opts) else: write_label(ax, opts['label'], final_start + ((final_end - final_start) / 2.0), opts=opts) # Return the final start and end positions to the DNA renderer if final_start > final_end: return prev_end, final_start else: return prev_end, final_end
def draw_outline(matplt_plot_obj, lw): matplt_plot_obj.set_path_effects( [Stroke(linewidth=lw, foreground='black'), Normal()])
for x in np.linspace(0, 1, 20): lw, color = x * 225, cmap(1 - x) t = ax.text( 0.5, 0.45, text, size=size, color="none", weight="bold", va="center", ha="center", family=family, zorder=-lw, ) t.set_path_effects([Stroke(linewidth=lw + 1, foreground="black")]) t = ax.text( 0.5, 0.45, text, size=size, color="black", weight="bold", va="center", ha="center", family=family, zorder=-lw + 1, ) t.set_path_effects([Stroke(linewidth=lw, foreground=color)]) t = ax.text( 1.0,
def plot_region_hc_map(var, region_props, lakes_path, indir_lakedata): # get region specific info from dictionary extent = region_props['extent'] continent_extent = region_props['continent_extent'] name = region_props['name'] name_str = region_props['name_str'] ax_location = region_props['ax_location'] levels = region_props['levels'] fig_size = region_props['fig_size'] cb_orientation = region_props['cb_orientation'] path_lakes = lakes_path + name + '.shp' # settings clb_label = 'Joule' title_str = name_str + ' heat content anomaly' fig_name = 'Heat_content_' + name cmap = 'YlOrBr' cmap, norm = mpu.from_levels_and_cmap(levels, cmap, extend='max') lon, lat = get_lonlat(indir_lakedata) LON, LAT = mpu.infer_interval_breaks(lon, lat) lakes = gpd.read_file(path_lakes) # plotting fig, ax = plt.subplots(1, 1, figsize=fig_size, subplot_kw={'projection': ccrs.PlateCarree()}) ax.add_feature(ctp.feature.OCEAN, color='gainsboro') ax.coastlines(color="grey") # add the data to the map (more info on colormaps: https://matplotlib.org/users/colormaps.html) h = ax.pcolormesh(LON, LAT, var, cmap=cmap, norm=norm) # load the lake shapefile lakes.plot(ax=ax, edgecolor='gray', facecolor='none') # set grid lines gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.5, color='gainsboro', alpha=0.5) gl.xlines = True gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabels_bottom = None gl.ylabels_right = None # set extent (in right way) extent[1], extent[2] = extent[2], extent[1] ax.set_extent(extent) # create effect for map borders: effect = Stroke(linewidth=1.5, foreground='darkgray') # set effect for main ax ax.outline_patch.set_path_effects([effect]) # Create an inset GeoAxes showing the location of the lakes region #x0 y0 width height sub_ax = fig.add_axes(ax_location, projection=ccrs.PlateCarree()) sub_ax.set_extent(continent_extent) #lakes.plot(ax=sub_ax) sub_ax.outline_patch.set_path_effects([effect]) extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), facecolor='none', edgecolor='red', linewidth=2) # Add the land, coastlines and the extent of the inset axis sub_ax.add_feature(cfeature.LAND, edgecolor='gray') sub_ax.coastlines(color='gray') extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), facecolor='none', edgecolor='black', linewidth=2) # plot the colorbar cbar = mpu.colorbar(h, ax, extend='max', orientation=cb_orientation, pad=0.05) if cb_orientation == 'vertical': cbar.ax.set_ylabel(clb_label, size=16) elif cb_orientation == 'horizontal': cbar.ax.set_xlabel(clb_label, size=16) #ax.set_title(title_str, pad=10) plotdir = '/home/inne/documents/phd/data/processed/isimip_lakeheat/plots/' plt.savefig(plotdir + fig_name + '.png', dpi=500)
def main(): # Define the two coordinate systems with different ellipses. wgs84 = ccrs.PlateCarree(globe=ccrs.Globe(datum='WGS84', ellipse='WGS84')) sphere = ccrs.PlateCarree( globe=ccrs.Globe(datum='WGS84', ellipse='sphere')) # Define the coordinate system of the data we have from Natural Earth and # acquire the 1:10m physical coastline shapefile. geodetic = ccrs.Geodetic(globe=ccrs.Globe(datum='WGS84')) dataset = cfeature.NaturalEarthFeature(category='physical', name='coastline', scale='10m') # Create a Stamen map tiler instance, and use its CRS for the GeoAxes. tiler = StamenTerrain() fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=tiler.crs) ax.set_title('The effect of incorrectly referencing the Solomon Islands') # Pick the area of interest. In our case, roughly the Solomon Islands, and # get hold of the coastlines for that area. extent = [155, 163, -11.5, -6] ax.set_extent(extent, geodetic) geoms = list(dataset.intersecting_geometries(extent)) # Add the Stamen aerial imagery at zoom level 7. ax.add_image(tiler, 7) # Transform the geodetic coordinates of the coastlines into the two # projections of differing ellipses. wgs84_geoms = [ geom_transform(transform_fn_factory(wgs84, geodetic), geom) for geom in geoms ] sphere_geoms = [ geom_transform(transform_fn_factory(sphere, geodetic), geom) for geom in geoms ] # Using these differently referenced geometries, assume that they are # both referenced to WGS84. ax.add_geometries(wgs84_geoms, wgs84, edgecolor='white', color='none') ax.add_geometries(sphere_geoms, wgs84, edgecolor='gray', color='none') # Create a legend for the coastlines. legend_artists = [ Line([0], [0], color=color, linewidth=3) for color in ('white', 'gray') ] legend_texts = ['Correct ellipse\n(WGS84)', 'Incorrect ellipse\n(sphere)'] legend = ax.legend(legend_artists, legend_texts, fancybox=True, loc='lower left', framealpha=0.75) legend.legendPatch.set_facecolor('wheat') # Create an inset GeoAxes showing the location of the Solomon Islands. sub_ax = fig.add_axes([0.7, 0.625, 0.2, 0.2], projection=ccrs.PlateCarree()) sub_ax.set_extent([110, 180, -50, 10], geodetic) # Make a nice border around the inset axes. effect = Stroke(linewidth=4, foreground='wheat', alpha=0.5) sub_ax.outline_patch.set_path_effects([effect]) # Add the land, coastlines and the extent of the Solomon Islands. sub_ax.add_feature(cfeature.LAND) sub_ax.coastlines() extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), color='none', edgecolor='blue', linewidth=2) plt.show()
def sbol_recombinase2(ax, type, num, start, end, prev_end, scale, linewidth, opts): """ SBOL recombinase site renderer - reverse direction """ # Default parameters color = (0, 0, 0) color2 = (0, 0, 0) start_pad = 0.0 end_pad = 0.0 x_extent = 6.0 y_extent = 6.0 linestyle = '-' # Update default parameters if provided if opts != None: if 'start_pad' in list(opts.keys()): start_pad = opts['start_pad'] if 'end_pad' in list(opts.keys()): end_pad = opts['end_pad'] if 'x_extent' in list(opts.keys()): x_extent = opts['x_extent'] if 'y_extent' in list(opts.keys()): y_extent = opts['y_extent'] if 'linestyle' in list(opts.keys()): linestyle = opts['linestyle'] if 'linewidth' in list(opts.keys()): linewidth = opts['linewidth'] if 'scale' in list(opts.keys()): scale = opts['scale'] if 'color' in list(opts.keys()): color = opts['color'] if 'color2' in list(opts.keys()): color2 = opts['color2'] else: if 'color' in list(opts.keys()): r2 = float(color[0]) / 2 g2 = float(color[1]) / 2 b2 = float(color[2]) / 2 color2 = (r2, g2, b2) # Check direction add start padding final_end = end final_start = prev_end y_lower = -1 * y_extent / 2 y_upper = y_extent / 2 if start > end: start = prev_end + end_pad + x_extent + linewidth end = prev_end + end_pad final_end = start + start_pad temp = color color = color2 color2 = temp else: start = prev_end + start_pad + linewidth end = start + x_extent final_end = end + end_pad # Draw the site p1 = Polygon([(start, y_lower), (start, y_upper), (end, 0)], edgecolor=(0, 0, 0), facecolor=color, linewidth=linewidth, zorder=11, path_effects=[Stroke(joinstyle="miter")]) midpoint = (end + start) / 2 hypotenuse = math.sqrt((y_extent / 2)**2 + (x_extent)**2) hypotenuse2 = hypotenuse / 2 cosineA = (y_extent / 2) / hypotenuse f = hypotenuse2 * cosineA p2 = Polygon([(midpoint, -1 * f), (midpoint, f), (end, 0)], edgecolor=(0, 0, 0), facecolor=color2, linewidth=linewidth, zorder=12, path_effects=[Stroke(joinstyle="miter")]) ax.add_patch(p1) ax.add_patch(p2) # Add a label if needed if opts != None and 'label' in list(opts.keys()): if final_start > final_end: write_label(ax, opts['label'], final_end + ((final_start - final_end) / 2.0), opts=opts) else: write_label(ax, opts['label'], final_start + ((final_end - final_start) / 2.0), opts=opts) # Return the final start and end positions to the DNA renderer if final_start > final_end: return prev_end, final_start else: return prev_end, final_end
def promoter_region(ax, type, num, start, end, prev_end, scale, linewidth, opts): # Default parameters - these can be added to, but we usually use this style (probably should simplify in future) y_offset = 0.0 color_35 = (0.5, 0.5, 0.5) color_10 = (0.5, 0.5, 0.5) color_connector = (0, 0, 0) linewidth_connector = 2.0 len_35 = 4 len_10 = 2 y_extent = 4.0 # Update default parameters if provided if opts != None: if 'y_extent' in opts.keys(): y_extent = opts['y_extent'] if 'y_offset' in opts.keys(): y_offset = opts['y_offset'] if 'linewidth' in opts.keys(): linewidth = opts['linewidth'] if 'color_35' in opts.keys(): color_35 = opts['color_35'] if 'color_10' in opts.keys(): color_10 = opts['color_10'] if 'color_connector' in opts.keys(): color_connector = opts['color_connector'] if 'linewidth_connector' in opts.keys(): linewidth_connector = opts['linewidth_connector'] if 'len_35' in opts.keys(): len_35 = opts['len_35'] if 'len_10' in opts.keys(): len_10 = opts['len_10'] # Check direction (we don't use at moment) fwd = True if start > end: fwd = False # Draw the -35 site (from start to start + length of -35 site) p35 = Polygon([(start, y_offset), (start, y_offset + y_extent), (start + len_35, y_offset + y_extent), (start + len_35, y_offset)], edgecolor=(0, 0, 0), facecolor=color_35, linewidth=linewidth, zorder=11, path_effects=[Stroke(joinstyle="miter")]) ax.add_patch(p35) # Draw the -10 site (from end-length of -10 site to end) p10 = Polygon([(end - len_10, y_offset), (end - len_10, y_offset + y_extent), (end, y_offset + y_extent), (end, y_offset)], edgecolor=(0, 0, 0), facecolor=color_10, linewidth=linewidth, zorder=11, path_effects=[Stroke(joinstyle="miter")]) ax.add_patch(p10) l1 = Line2D([start + len_35, end - len_10], [y_offset + (y_extent / 2.0), y_offset + (y_extent / 2.0)], linewidth=linewidth_connector, color=color_connector, zorder=10) ax.add_line(l1) # Add a label if needed if opts != None and 'label' in opts.keys(): if final_start > final_end: dpl.write_label(ax, opts['label'], final_end + ((final_start - final_end) / 2.0), opts=opts) else: dpl.write_label(ax, opts['label'], final_start + ((final_end - final_start) / 2.0), opts=opts) # Return the final start and end positions to the DNA renderer return start, end
def plot_stations_map(self, **kwargs): from matplotlib.transforms import offset_copy import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER from owslib.wms import WebMapService from matplotlib.patheffects import Stroke import cartopy.feature as cfeature import shapely.geometry as sgeom from matplotlib import pyplot as plt from isp import ROOT_DIR import os os.environ["CARTOPY_USER_BACKGROUNDS"] = os.path.join(ROOT_DIR, "maps") # MAP_SERVICE_URL = 'https://gis.ngdc.noaa.gov/arcgis/services/gebco08_hillshade/MapServer/WMSServer' MAP_SERVICE_URL = 'https://www.gebco.net/data_and_products/gebco_web_services/2020/mapserv?' # MAP_SERVICE_URL = 'https://gis.ngdc.noaa.gov/arcgis/services/etopo1/MapServer/WMSServer' geodetic = ccrs.Geodetic(globe=ccrs.Globe(datum='WGS84')) #layer = 'GEBCO_08 Hillshade' layer ='GEBCO_2020_Grid' #layer = 'shaded_relief' epi_lat = kwargs.pop('latitude') epi_lon = kwargs.pop('longitude') name_stations = [] lat = [] lon = [] for name, coords in self.__stations_dict.items(): name_stations.append(name) lat.append(float(coords[0])) lon.append(float(coords[1])) # proj = ccrs.PlateCarree() fig, ax = plt.subplots(1, 1, subplot_kw=dict(projection=proj), figsize=(16, 12)) self.mpf = MatplotlibFrame(fig) xmin = min(lon)-4 xmax = max(lon)+4 ymin = min(lat)-4 ymax = max(lat)+4 extent = [xmin, xmax, ymin, ymax] ax.set_extent(extent, crs=ccrs.PlateCarree()) try: wms = WebMapService(MAP_SERVICE_URL) ax.add_wms(wms, layer) except: ax.background_img(name='ne_shaded', resolution="high") #geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) geodetic_transform = ccrs.PlateCarree()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) ax.scatter(lon, lat, s=12, marker="^", color='red', alpha=0.7, transform=ccrs.PlateCarree()) ax.plot(epi_lon, epi_lat, color='black', marker='*', markersize=8) N=len(name_stations) for n in range(N): lon1=lon[n] lat1 = lat[n] name = name_stations[n] ax.text(lon1, lat1, name, verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='sandybrown', alpha=0.5, boxstyle='round')) # Create an inset GeoAxes showing the Global location #sub_ax = self.mpf.canvas.figure.add_axes([0.70, 0.75, 0.28, 0.28], # projection=ccrs.PlateCarree()) sub_ax = self.mpf.canvas.figure.add_axes([0.70, 0.73, 0.28, 0.28], projection=ccrs.PlateCarree()) sub_ax.set_extent([-179.9, 180, -89.9, 90], geodetic) # Make a nice border around the inset axes. effect = Stroke(linewidth=4, foreground='wheat', alpha=0.5) sub_ax.outline_patch.set_path_effects([effect]) # Add the land, coastlines and the extent . sub_ax.add_feature(cfeature.LAND) sub_ax.coastlines() extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), facecolor='none', edgecolor='blue', linewidth=1.0) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.2, color='gray', alpha=0.2, linestyle='-') gl.top_labels = False gl.left_labels = False gl.xlines = False gl.ylines = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER #plt.savefig("/Users/robertocabieces/Documents/ISPshare/isp/mti/output/stations.png", bbox_inches='tight') self.mpf.show()