def taylor(scores): fig = plt.figure(1) tr = PolarAxes.PolarTransform() CCgrid= np.concatenate((np.arange(0,10,2)/10.,[0.9,0.95,0.99])) CCpolar=np.arccos(CCgrid) gf=FixedLocator(CCpolar) tf=DictFormatter(dict(zip(CCpolar, map(str,CCgrid)))) STDgrid=np.arange(0,2.0,.5) gfs=FixedLocator(STDgrid) tfs=DictFormatter(dict(zip(STDgrid, map(str,STDgrid)))) ra0, ra1 =0, np.pi/2 cz0, cz1 = 0, 2 grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(ra0, ra1, cz0, cz1), grid_locator1=gf, tick_formatter1=tf, grid_locator2=gfs, tick_formatter2=tfs) ax1 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper) fig.add_subplot(ax1) ax1.axis["top"].set_axis_direction("bottom") ax1.axis["top"].toggle(ticklabels=True, label=True) ax1.axis["top"].major_ticklabels.set_axis_direction("top") ax1.axis["top"].label.set_axis_direction("top") ax1.axis["top"].label.set_text("Correlation") ax1.axis["left"].set_axis_direction("bottom") ax1.axis["left"].label.set_text("Normalized Standard deviation") ax1.axis["right"].set_axis_direction("top") ax1.axis["right"].toggle(ticklabels=True) ax1.axis["right"].major_ticklabels.set_axis_direction("left") ax1.axis["bottom"].set_visible(False) ax1 = ax1.get_aux_axes(tr) rs,ts = np.meshgrid(np.linspace(0,2),np.linspace(0,np.pi/2)) rms = np.sqrt(1 + rs**2 - 2*rs*np.cos(ts)) contours = ax1.contour(ts, rs, rms, 3,colors='0.5') plt.clabel(contours, inline=1, fontsize=10) plt.grid(linestyle=':',alpha=0.5) for r in scores.iterrows(): th=np.arccos(r[1].CORRELATION) rr=r[1].MSTD/r[1].OSTD ax1.plot(th,rr,'o',label=r[0]) plt.legend(loc='upper right',bbox_to_anchor=[1.2,1.15]) plt.show()
def taylor_template(angle_lim, std_lim, rect, xaxislab, fig=None): # written by Maria Aristizabal: https://github.com/MariaAristizabal/Evaluation_surf_metrics_Dorian_figures import mpl_toolkits.axisartist.floating_axes as floating_axes from matplotlib.projections import PolarAxes from mpl_toolkits.axisartist.grid_finder import (FixedLocator, DictFormatter) if fig is None: fig = plt.figure() tr = PolarAxes.PolarTransform() min_corr = np.round(np.cos(angle_lim), 1) CCgrid = np.concatenate( (np.arange(min_corr * 10, 10, 2.0) / 10., [0.9, 0.95, 0.99])) CCpolar = np.arccos(CCgrid) gf = FixedLocator(CCpolar) tf = DictFormatter(dict(zip(CCpolar, map(str, CCgrid)))) STDgrid = np.arange(0, std_lim, .5) gfs = FixedLocator(STDgrid) tfs = DictFormatter(dict(zip(STDgrid, map(str, STDgrid)))) ra0, ra1 = 0, angle_lim cz0, cz1 = 0, std_lim grid_helper = floating_axes.GridHelperCurveLinear(tr, extremes=(ra0, ra1, cz0, cz1), grid_locator1=gf, tick_formatter1=tf, grid_locator2=gfs, tick_formatter2=tfs) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) ax1.axis["top"].set_axis_direction("bottom") ax1.axis["top"].toggle(ticklabels=True, label=True) ax1.axis["top"].major_ticklabels.set_axis_direction("top") ax1.axis["top"].label.set_axis_direction("top") ax1.axis["top"].label.set_text("Correlation") ax1.axis['top'].label.set_size(14) ax1.axis["left"].set_axis_direction("bottom") if xaxislab == 'yes': ax1.axis["left"].label.set_text("Normalized Standard Deviation") ax1.axis['left'].label.set_size(14) ax1.axis["right"].set_axis_direction("top") ax1.axis["right"].toggle(ticklabels=True) ax1.axis["right"].major_ticklabels.set_axis_direction("left") ax1.axis["bottom"].set_visible(False) ax1 = ax1.get_aux_axes(tr) plt.grid(linestyle=':', alpha=0.5) return fig, ax1
def taylor_template(angle_lim, std_lim): fig = plt.figure() tr = PolarAxes.PolarTransform() min_corr = np.round(np.cos(angle_lim), 1) CCgrid = np.concatenate( (np.arange(min_corr * 10, 10, 2.0) / 10., [0.9, 0.95, 0.99])) CCpolar = np.arccos(CCgrid) gf = FixedLocator(CCpolar) tf = DictFormatter(dict(zip(CCpolar, map(str, CCgrid)))) STDgrid = np.arange(0, std_lim, .5) gfs = FixedLocator(STDgrid) tfs = DictFormatter(dict(zip(STDgrid, map(str, STDgrid)))) ra0, ra1 = 0, angle_lim cz0, cz1 = 0, std_lim grid_helper = floating_axes.GridHelperCurveLinear(tr, extremes=(ra0, ra1, cz0, cz1), grid_locator1=gf, tick_formatter1=tf, grid_locator2=gfs, tick_formatter2=tfs) ax1 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper) fig.add_subplot(ax1) ax1.axis["top"].set_axis_direction("bottom") ax1.axis["top"].toggle(ticklabels=True, label=True) ax1.axis["top"].major_ticklabels.set_axis_direction("top") ax1.axis["top"].label.set_axis_direction("top") ax1.axis["top"].label.set_text("Correlation") ax1.axis['top'].label.set_size(14) ax1.axis["left"].set_axis_direction("bottom") ax1.axis["left"].label.set_text("Normalized Standard Deviation") ax1.axis['left'].label.set_size(14) ax1.axis["right"].set_axis_direction("top") ax1.axis["right"].toggle(ticklabels=True) ax1.axis["right"].major_ticklabels.set_axis_direction("left") ax1.axis["bottom"].set_visible(False) ax1 = ax1.get_aux_axes(tr) plt.grid(linestyle=':', alpha=0.5) return fig, ax1
def setup_axes2(fig, rect): #mengatur locator dan formatter tr = PolarAxes.PolarTransform() pi = np.pi angle_ticks = [(0, r"$0$"), (.25 * pi, r"$\frac{1}{4}\pi$"), (.5 * pi, r"$\frac{1}{2}\pi$")] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(2) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(.5 * pi, 0, 2, 1), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None, ) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch ax1.patch.zorder = 0.9 return ax1, aux_ax
def setup_axes2(fig, rect): tr = PolarAxes.PolarTransform() pi = np.pi angle_ticks = [(0, r"$0$"), (.25 * pi, r"$\frac{1}{4}\pi$"), (.5 * pi, r"$\frac{1}{2}\pi$")] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(2) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(.5 * pi, 0, 2, 1), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) # 创建一个ParasiteAxes aux_ax = ax1.get_aux_axes(tr) # 让aux_ax具有一个ax中的剪切路径 aux_ax.patch = ax1.patch # 但这样做会有一个副作用,这个patch会被绘制两次,并且可能会被绘制于其它 # Artist的上面,因此用降低其zorder值的方法来阻止该情况 ax1.patch.zorder = 0.9 return ax1, aux_ax
def polarplot(self): tr = PolarAxes.PolarTransform() grid_locator1 = FixedLocator([v for v, s in self.angle_ticks]) tick_formatter1 = DictFormatter(dict(self.angle_ticks)) grid_locator2 = FixedLocator([a for a, b in self.radius_ticks]) tick_formatter2 = DictFormatter(dict(self.radius_ticks)) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(self.max_angle, self.min_angle, self.max_rad, self.min_rad), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2) ax = floating_axes.FloatingSubplot(self.fig, self.rect, grid_helper=grid_helper) self.fig.add_subplot(ax) ax.grid(True, color='b', linewidth=0.2, linestyle='-') aux_ax = ax.get_aux_axes(tr) aux_ax.patch = ax.patch ax.patch.zorder = 0.9 ax.axis['bottom'].set_label(r'Angle ($^{\circ}$)') ax.axis['bottom'].major_ticklabels.set_rotation(180) ax.axis['bottom'].label.set_rotation(180) ax.axis['bottom'].LABELPAD += 30 ax.axis['left'].set_label('Range (m)') ax.axis['left'].label.set_rotation(0) ax.axis['left'].LABELPAD += 15 ax.axis['left'].set_visible(True) return ax, aux_ax
def setup_axes2(self, fig, rect, n_markers, lat_min, lat_max, angle_ticks): """ for thin shells, lat subset """ tr = PolarAxes.PolarTransform() rs = np.linspace(self.r_inner, self.r_outer, n_markers) if not angle_ticks: angle_ticks = [] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) # set the number of r points you want on plot grid_locator2 = FixedLocator(rs) tick_formatter2 = None grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(lat_max / 180 * np.pi, lat_min / 180 * np.pi, self.r_outer, self.r_inner), # 70/180 grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) # format tick labels (see: https://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html) ax1.axis["bottom"].major_ticklabels.set_rotation(-90) ax1.axis["bottom"].major_ticklabels.set_va("center") ax1.axis["bottom"].major_ticklabels.set_pad(12) # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. return ax1, aux_ax
def setup_axes(fig, rect, theta, radius): """ Sets up the axes in such a way we can plot the polarplot. """ tr = PolarAxes.PolarTransform() pi = np.pi angle_ticks = [(-4. / 8. * pi, r"$-\frac{1}{2}\pi$"), (-3. / 8. * pi, r""), (-2. / 8. * pi, r"$-\frac{1}{4}\pi$"), (-1. / 8. * pi, r""), (0. / 8. * pi, r"$0$"), (1. / 8. * pi, r""), (2. / 8. * pi, r"$\frac{1}{4}\pi$"), (3. / 8. * pi, r""), (4. / 8. * pi, r"$\frac{1}{2}\pi$"), (6. / 8. * pi, r"$\frac{3}{4}\pi$"), (8. / 8. * pi, r"$\pi$")] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(3) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(theta[0], theta[1], radius[0], radius[1]), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) # adjust axis # "bottom", "top", "left", "right" ax1.axis["left"].set_axis_direction("bottom") ax1.axis["right"].set_axis_direction("top") ax1.axis["bottom"].set_visible(False) ax1.axis["top"].set_axis_direction("bottom") ax1.axis["top"].toggle(ticklabels=True, label=True) ax1.axis["top"].major_ticklabels.set_axis_direction("top") ax1.axis["top"].label.set_axis_direction("top") # create a parasite axes aux_ax = ax1.get_aux_axes(tr) return ax1, aux_ax
def setup_axes2(fig, rect): """ With custom locator and formatter. Note that the extreme values are swapped. """ tr = PolarAxes.PolarTransform() pi = np.pi angle_ticks = [(.5 * pi, r"90$\degree$"), (.625 * pi, r"112.5$\degree$"), (.75 * pi, r"135$\degree$"), (.81111111 * pi, r"146$\degree$"), (.84444444 * pi, r"152$\degree$"), (pi, r"180$\degree$")] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(2) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(pi, 0.5 * pi, 6371, 0), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) ax1.axis["bottom"].major_ticklabels.set_axis_direction("top") ax1.axis["left"].toggle(ticklabels=False) ax1.axis["left"].toggle(ticks=False) ax1.axis["top"].toggle(ticks=False) fig.add_subplot(ax1) # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. return ax1, aux_ax
def setup_axes(self, fig, rect, n_markers): """ With custom locator and formatter. Note that the extreme values are swapped. """ tr = PolarAxes.PolarTransform() rs = np.linspace(self.r_inner, self.r_outer, n_markers) angle_ticks = [] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) # set the number of r points you want on plot grid_locator2 = FixedLocator(rs) tick_formatter2 = None grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(0.5 * np.pi, -0.5 * np.pi, self.r_outer, self.r_inner), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. return ax1, aux_ax
def setup_axes2(fig, rect): """ With custom locator and formatter. Note that the extreme values are swapped. """ #tr_scale = Affine2D().scale(np.pi/180., 1.) tr = PolarAxes.PolarTransform() pi = np.pi angle_ticks = [(0, r"$0$"), (.25 * pi, r"$\frac{1}{4}\pi$"), (.5 * pi, r"$\frac{1}{2}\pi$")] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(2) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(.5 * pi, 0, 2, 1), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None, ) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. return ax1, aux_ax
def setup_axes2(fig, rect, tmin, tmax, zmin, zmax): """ With custom locator and formatter. Note that the extreme values are swapped. """ tr = PolarAxes.PolarTransform() pi = np.pi angle_ticks = [(tmin, '%.2f' % tmin), (0, r'$0$'), (tmax, '%.2f' % tmax)] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(4) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(tmax, tmin, zmax, zmin), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.95 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. return ax1, aux_ax
def setup_axes2(fig, rect): """ With custom locator and formatter. Note that the extreme values are swapped. """ tr = PolarAxes.PolarTransform() pi = np.pi angle_ticks = [(0,'180' ), (.25*pi,'135' ), (.5*pi, '90'), (.75*pi,'45' ), (pi,'0')] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(nbins=6) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(pi,0, 6371,3481), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. return ax1, aux_ax
def curved_earth_axes(rect=111, fig=None, minground=0., maxground=2000, minalt=0, maxalt=500, Re=6371., nyticks=5, nxticks=4): """ Create curved axes in ground-range and altitude Copied from DaViTPy: https://github.com/vtsuperdarn/davitpy/blob/1b578ea2491888e3d97d6e0a8bc6d8cc7c9211fb/davitpy/utils/plotUtils.py#L559 """ from matplotlib.transforms import Affine2D, Transform import mpl_toolkits.axisartist.floating_axes as floating_axes from matplotlib.projections import polar from mpl_toolkits.axisartist.grid_finder import FixedLocator, DictFormatter import numpy as np from pylab import gcf ang = maxground / Re minang = minground / Re angran = ang - minang angle_ticks = [(0, "{:.0f}".format(minground))] while angle_ticks[-1][0] < angran: tang = angle_ticks[-1][0] + 1. / nxticks * angran angle_ticks.append((tang, "{:.0f}".format((tang - minang) * Re))) grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) altran = float(maxalt - minalt) alt_ticks = [(minalt + Re, "{:.0f}".format(minalt))] while alt_ticks[-1][0] < Re + maxalt: alt_ticks.append( (altran / float(nyticks) + alt_ticks[-1][0], "{:.0f}".format(altran / float(nyticks) + alt_ticks[-1][0] - Re))) _ = alt_ticks.pop() grid_locator2 = FixedLocator([v for v, s in alt_ticks]) tick_formatter2 = DictFormatter(dict(alt_ticks)) tr_rotate = Affine2D().rotate(np.pi / 2 - ang / 2) tr_shift = Affine2D().translate(0, Re) tr = polar.PolarTransform() + tr_rotate grid_helper = \ floating_axes.GridHelperCurveLinear(tr, extremes=(0, angran, Re+minalt, Re+maxalt), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2,) if not fig: fig = gcf() ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) # adjust axis # ax1.axis["left"].label.set_text(r"Alt. [km]") # ax1.axis["bottom"].label.set_text(r"Ground range [km]") ax1.invert_xaxis() ax1.minground = minground ax1.maxground = maxground ax1.minalt = minalt ax1.maxalt = maxalt ax1.Re = Re fig.add_subplot(ax1, transform=tr) # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) # for aux_ax to have a clip path as in ax aux_ax.patch = ax1.patch # but this has a side effect that the patch is drawn twice, and possibly # over some other artists. So, we decrease the zorder a bit to prevent this. ax1.patch.zorder = 0.9 return ax1, aux_ax
def get_slice_axes(fig, num, lat1=-90., lat2=90., shrink=1.0): tr_rotate = Affine2D().translate(0, 90) # set up polar axis tr = PolarAxes.PolarTransform() + tr_rotate angle_ticks = [(np.radians(i), str(i)) for i in np.arange(80, -81, -10)] # angle_ticks = [(np.radians(80), r"$80$"), # (np.radians(40), r"$\frac{3}{4}\pi$"), # (1.*np.pi, r"$\pi$"), # (1.25*np.pi, r"$\frac{5}{4}\pi$"), # (1.5*np.pi, r"$\frac{3}{2}\pi$"), # (1.75*np.pi, r"$\frac{7}{4}\pi$")] # set up ticks and spacing around the circle grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) # set up grid spacing along the 'radius' radius_ticks = [ (1., ''), # (1.5, '%i' % (MAX_R/2.)), (R / Rb, '') ] grid_locator2 = FixedLocator([v for v, s in radius_ticks]) tick_formatter2 = DictFormatter(dict(radius_ticks)) # define angle ticks around the circumference: # set up axis: # tr: the polar axis setup # extremes: theta max, theta min, r max, r min # the grid for the theta axis # the grid for the r axis # the tick formatting for the theta axis # the tick formatting for the r axis lat1 = np.radians(lat1) lat2 = np.radians(lat2) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(-lat1, lat2, R / Rb * shrink, 1 * shrink), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2) ax1 = floating_axes.FloatingSubplot(fig, num, grid_helper=grid_helper) fig.add_subplot(ax1) ax1.axis["left"].set_axis_direction("bottom") ax1.axis["right"].set_axis_direction("bottom") ax1.axis["left"].major_ticklabels.set_rotation(90) #ax1.axis["right"].set_tick_direction('out') #ax1.axis # ax1.axis["left"].major_ticks.set_tick_out(True) # # ax1.axis["bottom"].set_visible(False) ax1.axis["bottom"].set_axis_direction("right") ax1.axis["bottom"].major_ticks.set_tick_out(True) # ax1.axis["bottom"].major_ticklabels.locs_angles_labels = [0, 0, 0, 0,0,0,0] # print(ax1.axis["bottom"].major_ticklabels._locs_angles_labels) #ax1.axis["bottom"].major_ticklabels.set_ha('right') majortick_iter, minortick_iter = ax1.axis[ 'bottom']._axis_artist_helper.get_tick_iterators(ax1) tick_loc_angle, ticklabel_loc_angle_label = ax1.axis[ 'bottom']._get_tick_info(majortick_iter) #ax1.axis["bottom"].major_ticklabels.set_pad(1.0) aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. return ax1, aux_ax
def plot_polar_heatmap(data, name, interp_factor=5., color_limits=False, hide_colorbar=False, vmin=None, vmax=None, log_scale=True, dpi=200, output_dir=None): """Plots the polar heatmap describing azimuth and latitude / elevation components. Plots the polar heatmap where each cell of the heatmap corresponds to the specific element of the array provided by `gather_polar_errors` function. Parameters ---------- data : 2D array Indicates the array containing the sum of angular errors within the specified angular ranges. It is usually provided by `gather_polar_errors` function. name : str Indicates the name of the output png file. interp_factor : float Indicates the interpolation factor of the heatmap. color_limits : boolean Specifies if the determined intensity limits should be returned. hide_colorbar : boolean Specifies if the colorbar should be hidden. vmin : float Indicates the minimum value of the colorbar. vmax : float Indicates the maximum value of the colorbar. log_scale : float Specifies if the heatmap sould be in the logarithmic scale. dpi : integer Indicates the DPI of the output image. output_dir : str Indicates the path to the output folder where the image will be stored. """ th0, th1 = 0., 180. r0, r1 = 0, 90 thlabel, rlabel = 'Azimuth', 'Elevation' tr_scale = Affine2D().scale(np.pi / 180., 1.) tr = tr_scale + PolarAxes.PolarTransform() lat_ticks = [(.0 * 90., '0$^{\circ}$'), (.33 * 90., '30$^{\circ}$'), (.66 * 90., '60$^{\circ}$'), (1. * 90., '90$^{\circ}$')] r_grid_locator = FixedLocator([v for v, s in lat_ticks]) r_grid_formatter = DictFormatter(dict(lat_ticks)) angle_ticks = [(0 * 180., '90$^{\circ}$'), (.25 * 180., '45$^{\circ}$'), (.5 * 180., '0$^{\circ}$'), (.75 * 180., '-45$^{\circ}$'), (1. * 180., '-90$^{\circ}$')] theta_grid_locator = FixedLocator([v for v, s in angle_ticks]) theta_tick_formatter = DictFormatter(dict(angle_ticks)) grid_helper = GridHelperCurveLinear(tr, extremes=(th0, th1, r0, r1), grid_locator1=theta_grid_locator, grid_locator2=r_grid_locator, tick_formatter1=theta_tick_formatter, tick_formatter2=r_grid_formatter) fig = plt.figure() ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper) fig.add_subplot(ax) ax.set_facecolor('white') ax.axis["bottom"].set_visible(False) ax.axis["top"].toggle(ticklabels=True, label=True) ax.axis["top"].set_axis_direction("bottom") ax.axis["top"].major_ticklabels.set_axis_direction("top") ax.axis["top"].label.set_axis_direction("top") ax.axis["left"].set_axis_direction("bottom") ax.axis["right"].set_axis_direction("top") ax.axis["top"].label.set_text(thlabel) ax.axis["left"].label.set_text(rlabel) aux_ax = ax.get_aux_axes(tr) aux_ax.patch = ax.patch ax.patch.zorder = 0.9 rad = np.linspace(0, 90, data.shape[1]) azm = np.linspace(0, 180, data.shape[0]) f = interpolate.interp2d(rad, azm, data, kind='linear', bounds_error=True, fill_value=0) new_rad = np.linspace(0, 90, 180 * interp_factor) new_azm = np.linspace(0, 180, 360 * interp_factor) new_data_angle_dist = f(new_rad, new_azm) new_r, new_th = np.meshgrid(new_rad, new_azm) new_data_angle_dist += 1. if log_scale: data_mesh = aux_ax.pcolormesh( new_th, new_r, new_data_angle_dist, cmap='jet', norm=colors.LogNorm( vmin=1. if vmin is None else vmin, vmax=new_data_angle_dist.max() if vmax is None else vmax)) else: data_mesh = aux_ax.pcolormesh(new_th, new_r, new_data_angle_dist, cmap='jet', vmin=vmin, vmax=vmax) cbar = plt.colorbar(data_mesh, orientation='vertical', shrink=.88, pad=.1, aspect=15) cbar.ax.set_ylabel('Absolute error, [deg.]') if hide_colorbar: cbar.remove() ax.grid(False) plt.show() if output_dir is not None: if not os.path.exists(output_dir): os.makedirs(output_dir) fig.savefig(os.path.join(output_dir, f'{name}_chart.png'), transparent=False, bbox_inches='tight', pad_inches=0.1, dpi=dpi) if color_limits: return 1., new_data_angle_dist.max()
def taylor(scores, colors, units, angle_lim): fig = plt.figure() tr = PolarAxes.PolarTransform() CCgrid = np.concatenate((np.arange(0, 10, 2) / 10., [0.9, 0.95, 0.99])) CCpolar = np.arccos(CCgrid) gf = FixedLocator(CCpolar) tf = DictFormatter(dict(zip(CCpolar, map(str, CCgrid)))) max_std = np.nanmax([scores.OSTD, scores.MSTD]) if np.round(scores.OSTD[0], 2) <= 0.2: #STDgrid=np.linspace(0,np.round(scores.OSTD[0]+0.01,2),3) STDgrid = np.linspace(0, np.round(scores.OSTD[0] + max_std + 0.02, 2), 3) if np.logical_and( np.round(scores.OSTD[0], 2) > 0.2, np.round(scores.OSTD[0], 2) <= 1): STDgrid = np.linspace(0, np.round(scores.OSTD[0] + 0.1, 2), 3) if np.logical_and( np.round(scores.OSTD[0], 2) > 1, np.round(scores.OSTD[0], 2) <= 5): STDgrid = np.arange(0, np.round(scores.OSTD[0] + 2, 2), 1) if np.round(scores.OSTD[0], 2) > 5: STDgrid = np.arange(0, np.round(scores.OSTD[0] + 5, 1), 2) gfs = FixedLocator(STDgrid) tfs = DictFormatter(dict(zip(STDgrid, map(str, STDgrid)))) ra0, ra1 = 0, angle_lim if np.round(scores.OSTD[0], 2) <= 0.2: cz0, cz1 = 0, np.round(max_std + 0.1, 2) else: #cz0, cz1 = 0, np.round(scores.OSTD[0]+0.1,2) cz0, cz1 = 0, np.round(max_std + 0.1, 2) grid_helper = floating_axes.GridHelperCurveLinear(tr, extremes=(ra0, ra1, cz0, cz1), grid_locator1=gf, tick_formatter1=tf, grid_locator2=gfs, tick_formatter2=tfs) ax1 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper) fig.add_subplot(ax1) ax1.axis["top"].set_axis_direction("bottom") ax1.axis["top"].toggle(ticklabels=True, label=True) ax1.axis["top"].major_ticklabels.set_axis_direction("top") ax1.axis["top"].label.set_axis_direction("top") ax1.axis["top"].label.set_text("Correlation") ax1.axis['top'].label.set_size(14) ax1.axis["left"].set_axis_direction("bottom") ax1.axis["left"].label.set_text("Standard Deviation " + '(' + units + ')') ax1.axis['left'].label.set_size(14) ax1.axis["right"].set_axis_direction("top") ax1.axis["right"].toggle(ticklabels=True) ax1.axis["right"].major_ticklabels.set_axis_direction("left") ax1.axis["bottom"].set_visible(False) ax1 = ax1.get_aux_axes(tr) plt.grid(linestyle=':', alpha=0.5) for i, r in enumerate(scores.iterrows()): theta = np.arccos(r[1].CORRELATION) rr = r[1].MSTD ax1.plot(theta, rr, 'o', label=r[0], color=colors[i]) ax1.plot(0, scores.OSTD[0], 'o', label='Obs') plt.legend(loc='upper right', bbox_to_anchor=[1.3, 1.15]) plt.show() rs, ts = np.meshgrid(np.linspace(0, np.round(max_std + 0.1, 2)), np.linspace(0, angle_lim)) rms = np.sqrt(scores.OSTD[0]**2 + rs**2 - 2 * rs * scores.OSTD[0] * np.cos(ts)) ax1.contour(ts, rs, rms, 5, colors='0.5') #contours = ax1.contour(ts, rs, rms,5,colors='0.5') #plt.clabel(contours, inline=1, fontsize=10) plt.grid(linestyle=':', alpha=0.5) for i, r in enumerate(scores.iterrows()): #crmse = np.sqrt(r[1].OSTD**2 + r[1].MSTD**2 \ # - 2*r[1].OSTD*r[1].MSTD*r[1].CORRELATION) crmse = np.sqrt(scores.OSTD[0]**2 + r[1].MSTD**2 \ - 2*scores.OSTD[0]*r[1].MSTD*r[1].CORRELATION) print(crmse) c1 = ax1.contour(ts, rs, rms, [crmse], colors=colors[i]) plt.clabel(c1, inline=1, fontsize=10, fmt='%1.2f') return fig, ax1
def curvedEarthAxes(rect=111, fig=None, minground=0., maxground=2000, minalt=0, maxalt=500, Re=6371., nyticks=5, nxticks=4): """Create curved axes in ground-range and altitude Parameters ---------- rect : Optional[int] subplot spcification fig : Optional[pylab.figure object] (default to gcf) minground : Optional[float] maxground : Optional[int] maximum ground range [km] minalt : Optional[int] lowest altitude limit [km] maxalt : Optional[int] highest altitude limit [km] Re : Optional[float] Earth radius in kilometers nyticks : Optional[int] Number of y axis tick marks; default is 5 nxticks : Optional[int] Number of x axis tick marks; deafult is 4 Returns ------- ax : matplotlib.axes object containing formatting aax : matplotlib.axes object containing data Example ------- import numpy as np from utils import plotUtils ax, aax = plotUtils.curvedEarthAxes() th = np.linspace(0, ax.maxground/ax.Re, 50) r = np.linspace(ax.Re+ax.minalt, ax.Re+ax.maxalt, 20) Z = exp( -(r - 300 - ax.Re)**2 / 100**2 ) * np.cos(th[:, np.newaxis]/th.max()*4*np.pi) x, y = np.meshgrid(th, r) im = aax.pcolormesh(x, y, Z.T) ax.grid() written by Sebastien, 2013-04 """ from matplotlib.transforms import Affine2D, Transform import mpl_toolkits.axisartist.floating_axes as floating_axes from matplotlib.projections import polar from mpl_toolkits.axisartist.grid_finder import FixedLocator, DictFormatter import numpy as np from pylab import gcf ang = maxground / Re minang = minground / Re angran = ang - minang angle_ticks = [(0, "{:.0f}".format(minground))] while angle_ticks[-1][0] < angran: tang = angle_ticks[-1][0] + 1. / nxticks * angran angle_ticks.append((tang, "{:.0f}".format((tang - minang) * Re))) grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) altran = float(maxalt - minalt) alt_ticks = [(minalt + Re, "{:.0f}".format(minalt))] while alt_ticks[-1][0] < Re + maxalt: alt_ticks.append( (altran / float(nyticks) + alt_ticks[-1][0], "{:.0f}".format(altran / float(nyticks) + alt_ticks[-1][0] - Re))) _ = alt_ticks.pop() grid_locator2 = FixedLocator([v for v, s in alt_ticks]) tick_formatter2 = DictFormatter(dict(alt_ticks)) tr_rotate = Affine2D().rotate(np.pi / 2 - ang / 2) tr_shift = Affine2D().translate(0, Re) tr = polar.PolarTransform() + tr_rotate grid_helper = \ floating_axes.GridHelperCurveLinear(tr, extremes=(0, angran, Re+minalt, Re+maxalt), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2,) if not fig: fig = gcf() ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) # adjust axis ax1.axis["left"].label.set_text(r"Alt. [km]") ax1.axis["bottom"].label.set_text(r"Ground range [km]") ax1.invert_xaxis() ax1.minground = minground ax1.maxground = maxground ax1.minalt = minalt ax1.maxalt = maxalt ax1.Re = Re fig.add_subplot(ax1, transform=tr) # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) # for aux_ax to have a clip path as in ax aux_ax.patch = ax1.patch # but this has a side effect that the patch is drawn twice, and possibly # over some other artists. So, we decrease the zorder a bit to prevent this. ax1.patch.zorder = 0.9 return ax1, aux_ax
def plot_crosssection_any(self, lon1, lon2, lat1, lat2, numpoints=400, whattoplot='clust', title='', stretch=1, greatcirclepath=True, lon0=180, spherical=False): """ plot horizontal slices through an ses3d model plot_slice(self,depth,colormap='tomo',res='i',verbose=False) depth=depth in km of the slice colormap='tomo','mono' res=resolution of the map, admissible values are: c, l, i, h f """ model = getattr(self, whattoplot) #lon=(lon1+lon2)/2. #- set up a map and colourmap ----------------------------------------- fig = plt.figure() plt.subplot(2, 1, 1) m = Basemap(projection='hammer', lon_0=lon0) #m.drawparallels(np.arange(self.lat_min,self.lat_max,45.),labels=[0,0,0,0])#[1,0,0,1]) #m.drawmeridians(np.arange(self.lon_min,self.lon_max,60.),labels=[0,0,0,0])#[1,0,0,1]) coasts = m.drawcoastlines(zorder=1, color='white', linewidth=0) coasts_paths = coasts.get_paths() ipolygons = range(40) # want Baikal, but not Tanganyika # 80 = Superior+Michigan+Huron, 81 = Victoria, 82 = Aral, 83 = Tanganyika, # 84 = Baikal, 85 = Great Bear, 86 = Great Slave, 87 = Nyasa, 88 = Erie # 89 = Winnipeg, 90 = Ontario for ipoly in ipolygons: r = coasts_paths[ipoly] # Convert into lon/lat vertices polygon_vertices = [(vertex[0], vertex[1]) for (vertex, code) in r.iter_segments(simplify=False)] px = [polygon_vertices[i][0] for i in range(len(polygon_vertices))] py = [polygon_vertices[i][1] for i in range(len(polygon_vertices))] m.plot(px, py, linewidth=1., zorder=3, color=[0.2, 0.2, 0.2]) #m.drawmapboundary(fill_color=[1.0,1.0,1.0]) #m.drawmapboundary(fill_color=[1.0,1.0,1.0]) if lon0 == 180: z = (model[:, :, 0]) #z=z.transpose([1,0,2]) #zt,lonstmp=shiftgrid(0,z.T,self.lon) #lonst,lonstmp=shiftgrid(0,lons.T,lons[:,0]) x1, y1 = np.meshgrid(self.lon, self.lat) x, y = m(x1.T, y1.T) else: z = (model[:, :, 0]) zt, lonstmp = shiftgrid(0, z.T, self.lon, start=False) x1, y1 = np.meshgrid(self.lon, self.lat) print(np.shape(x1), np.shape(y1)) x, y = m(x1.T, y1.T) #x=m.shiftdata(x,lon_0=lon0) rgb =np.array(np.transpose(clustmap,(1,2,0)),dtype='float32') #rgb =zt.transpose([1,2,0]) #color_tuple=rgb.reshape((rgb.shape[1]*rgb.shape[0],rgb.shape[2]),order='C') #mapper=np.linspace(0.,1.,rgb.shape[1]*rgb.shape[0]).reshape(rgb.shape[0],rgb.shape[1]) #rgb_map=LinearSegmentedColormap.from_list('rgbmap',color_tuple,N=rgb.shape[1]*rgb.shape[0]) cs = m.pcolor(x, y, z, cmap=self.rgb_map, linewidth=0, rasterized=True) #plt.colorbar() inv = geo.WGS84.Inverse(lat1, lon1, lat2, lon2) points = np.linspace(0, inv['s12'], numpoints) line = geo.WGS84.Line(lat1, lon1, inv['azi1']) if greatcirclepath: [x1, y1] = m.gcpoints(lon1, lat1, lon2, lat2, numpoints) m.plot(x1, y1, 'k', linewidth=3) m.plot(x1[0], y1[0], '.c', markersize=15, markeredgecolor='k') m.plot(x1[-1], y1[-1], '.m', markersize=15, markeredgecolor='k') dist = [] lonsline = [] latsline = [] for i in range(len(points)): loc = line.Position(points[i]) # dist.append(haversine((loc['lat2'],loc['lon2']),([lat1],[lon1]))/111194.) dist.append(loc['s12'] / 111194.) lonsline.append(loc['lon2']) latsline.append(loc['lat2']) lonsline = np.array(lonsline) latsline = np.array(latsline) else: lonsline = np.linspace(lon1, lon2, numpoints) latsline = np.linspace(lat1, lat2, numpoints) dist = haversine((lat1, lon1), (latsline, lonsline)) / 111194. [x1, y1] = m(lonsline, latsline) m.plot(x1, y1, 'k', linewidth=3) m.plot(x1[0], y1[0], '.c', markersize=15, markeredgecolor='k') m.plot(x1[-1], y1[-1], '.m', markersize=15, markeredgecolor='k') modeltoplot = getattr(self, 'indg6') idxs = [] for i in range(len(lonsline)): idxs.append( np.argmin( haversine((latsline[i], lonsline[i]), (self.latg6, self.long6)))) idxs = np.array(idxs) toplot = np.empty((len(lonsline), len(self.depth))) for d in range(len(self.depth)): el = np.where(self.deps == self.depth[d]) clusttmp = np.squeeze(modeltoplot[el]) for i in range(len(lonsline)): toplot[i, d] = clusttmp[idxs[i]] #toplot.append(np.round(scipy.ndimage.map_coordinates(model[:,:,d], np.vstack((row,col)),order=0,mode='constant'))) toplot = np.array(toplot).T xx, yy = np.meshgrid(dist, self.depth) if spherical == False: ax = plt.subplot(2, 1, 2) minval = np.min(np.min(toplot)) maxval = np.max(np.max(toplot)) contours = np.round(np.linspace(-1.1, 1.1, 12), 2) plt.title(title) cs = plt.pcolor(xx, yy, toplot, cmap=self.rgb_map, vmin=0.5, vmax=21.5) plt.plot([dist[0], dist[-1]], [min(self.depth), min(self.depth)], 'k', linewidth=8) plt.plot(dist[0], min(self.depth), '.c', markersize=40, markeredgecolor='k') plt.plot(dist[-1], min(self.depth), '.m', markersize=40, markeredgecolor='k') #plt.pcolor(x,y,self.dvs[:,:,layer],vmin=-0.04, vmax=0.04,cmap=plt.cm.get_cmap('jet_r')) plt.ylim([min(self.depth), 2890]) plt.gca().invert_yaxis() plt.xlim([min(dist), max(dist)]) ax.set_aspect(.015 / stretch) #plt.xlabel(xlabel) plt.ylabel('depth (km)') if spherical == True: thetamin = 0 thetamax = inv['a12'] * np.pi / 180. tr = PolarAxes.PolarTransform() pi = np.pi shift = pi / 2 - (thetamax + thetamin) / 2 xx = xx + shift * 180. / pi angle_ticks = [(thetamin + shift, r""), ((thetamax + thetamin) / 2 + shift, r""), (thetamax + shift, r"")] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(6) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(thetamin + shift, thetamax + shift, 6371, 3480), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None) ax1 = floating_axes.FloatingSubplot(fig, 212, grid_helper=grid_helper) fig.add_subplot(ax1) # create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. #ax=plt.subplot(212, polar = True) minval = np.min(np.min(toplot)) maxval = np.max(np.max(toplot)) contours = np.round(np.linspace(-1.1, 1.1, 12), 2) #plt.title(title) cs = aux_ax.pcolor((180. - xx) * np.pi / 180., 6371. - yy, toplot, cmap=self.rgb_map, vmin=0.5, vmax=21.5) aux_ax.plot(np.pi - (thetamin + shift), 6371., '.c', markersize=55, markeredgecolor='k') aux_ax.plot(np.pi - (thetamax + shift), 6371., '.m', markersize=55, markeredgecolor='k') return aux_ax, shift
def __init__(self,fig,angularRange,radialRange,\ angularUnits="degrees",angularSigFig=2,angularLabel=None,\ radialUnits=None,radialSigFig=2,radialLabel=None,\ subplot=111,rotate=0.0,gridlines=True,verbose=False): classname = self.__class__.__name__ funcname = self.__class__.__name__+"."+sys._getframe().f_code.co_name # Store figure self.fig = fig # Set angular range self.ANGULAR = angularGeometry(units=angularUnits) angularTicks = self.ANGULAR.getTicks(angularRange[0],angularRange[1],angularRange[2],sigFig=angularSigFig) # Set grid lines for angular coordinates angular_grid_locator = FixedLocator([v for v, s in angularTicks]) angular_tick_formatter = DictFormatter(dict(angularTicks)) # Set radial range self.RADIAL = radialGeometry(units=radialUnits) radialTicks = self.RADIAL.getTicks(radialRange[0],radialRange[1],radialRange[2],sigFig=radialSigFig) # Set radial grid lines radial_grid_locator = FixedLocator([v for v, s in radialTicks]) # Check whether creating special case of all-sky axes self.fullSky = self.ANGULAR.fullSky(angularRange[0],angularRange[1]) if self.fullSky: # Create axes self.ax = self.fig.add_subplot(subplot,polar=True) # Set radial tickmarks self.ax.set_ylim(0.0,radialRange[1]) tick_labels = np.arange(0.0,radialRange[1],radialRange[2])[1:] majorLocator = matplotlib.ticker.FixedLocator(tick_labels) self.ax.yaxis.set_major_locator(majorLocator) # Set angular tick marks self.ax.set_xlim(0.0,360.0) angularDiff = self.ANGULAR.convert(angularRange[2],units='radians') tick_labels = np.arange(0.0,(2.0*Pi)+angularDiff,angularDiff) majorLocator = matplotlib.ticker.FixedLocator(tick_labels) self.ax.xaxis.set_major_locator(majorLocator) labels = [s for v, s in angularTicks] if angularSigFig <= 2: labels[0] = labels[0].replace(".0","") self.ax.set_xticklabels(labels) # Show axis labels? if angularLabel is not None: self.ax.set_xlabel(angularLabel) # Show gridlines? self.ax.grid(gridlines,ls='-',c='grey',alpha=0.25) self.aux_ax = None self.radialAxis = self.ax.yaxis self.angularAxis = self.ax.xaxis return # Set rotation/orientation of axes such that wedge is # symmetrical about +/-X or +/-Y axis minAngle,maxAngle = self.ANGULAR.wrap(angularRange[0],angularRange[1]) minAngleDeg = self.ANGULAR.convert(minAngle,units='deg') maxAngleDeg = self.ANGULAR.convert(maxAngle,units='deg') midway = minAngleDeg + (maxAngleDeg-minAngleDeg)/2.0 if rotate < 0.0: rotate = 360.0 + rotate tr_rotate = Affine2D().translate(rotate-midway, 0) # Scale degree to radians tr_scale = Affine2D().scale(np.pi/180., 1.) # Apply rotation and scaling to polar axes tr = tr_rotate + tr_scale + PolarAxes.PolarTransform() # Construct grid, setting angular and radial limits extremes = (minAngleDeg,maxAngleDeg,radialRange[0],radialRange[1]) grid_helper = floating_axes.GridHelperCurveLinear(tr,extremes=extremes,\ grid_locator1=angular_grid_locator,\ grid_locator2=radial_grid_locator,\ tick_formatter1=angular_tick_formatter,\ tick_formatter2=None) # Construct axes self.ax = floating_axes.FloatingSubplot(self.fig,subplot,grid_helper=grid_helper) self.fig.add_subplot(self.ax) # Adjust angular tick marks and labels according to orientation self.angularAxis = self.ax.axis["top"] if(radialRange[0] == 0.0): self.ax.axis["bottom"].set_visible(False) else: self.ax.axis["bottom"].set_axis_direction("top") self.ax.axis["bottom"].toggle(ticklabels=False,label=False) self.angularAxis.set_axis_direction("bottom") self.angularAxis.toggle(ticklabels=True,label=True) if rotate <= 180.0: self.angularAxis.major_ticklabels.set_axis_direction("top") self.angularAxis.label.set_axis_direction("top") else: self.angularAxis.major_ticklabels.set_axis_direction("bottom") self.angularAxis.label.set_axis_direction("bottom") if angularLabel is not None: self.angularAxis.label.set_text(angularLabel) self.angularAxis.label.set_size(20.0) # Adjust radial tick marks and labels according to orientation if rotate <= 90.0 or rotate >= 270.0: self.radialAxis1 = self.ax.axis["left"] self.radialAxis2 = self.ax.axis["right"] self.radialAxis1.set_axis_direction("bottom") self.radialAxis2.set_axis_direction("top") else: self.radialAxis1 = self.ax.axis["right"] self.radialAxis2 = self.ax.axis["left"] self.radialAxis1.set_axis_direction("top") self.radialAxis2.set_axis_direction("bottom") self.radialAxis1.toggle(ticklabels=True, label=True) self.radialAxis2.toggle(ticklabels=True, label=True) if rotate > 45.0 and rotate < 135.0: self.radialAxis1.major_ticklabels.set_axis_direction("right") self.radialAxis1.label.set_axis_direction("right") self.radialAxis2.major_ticklabels.set_axis_direction("left") if rotate >= 135.0 and rotate <= 225.0: self.radialAxis1.major_ticklabels.set_axis_direction("bottom") self.radialAxis1.label.set_axis_direction("bottom") self.radialAxis2.major_ticklabels.set_axis_direction("top") if rotate > 225.0 and rotate < 315.0: self.radialAxis1.major_ticklabels.set_axis_direction("left") self.radialAxis1.label.set_axis_direction("left") self.radialAxis2.major_ticklabels.set_axis_direction("right") if radialLabel is not None: self.radialAxis1.label.set_text(radialLabel+"["+self.RADIAL.latex+"]") self.radialAxis1.label.set_size(20.0) # Add gridlines to plot? (Default = True) self.ax.grid(gridlines) # Create a parasite axes whose transData in RA, z self.aux_ax = self.ax.get_aux_axes(tr) # For aux_ax to have a clip path as in ax but this has a side # effect that the patch is drawn twice, and possibly over some # other artists. So, we decrease the zorder a bit to prevent this. self.aux_ax.patch = self.ax.patch self.ax.patch.zorder=0.9 return
from matplotlib.projections import PolarAxes from mpl_toolkits.axisartist.grid_finder import FixedLocator, MaxNLocator, \ DictFormatter import matplotlib.pyplot as plt tr = PolarAxes.PolarTransform() def degree_ticks(d): return (d * np.pi / 180, "%d$^\\circ$" % (360 - d)) degree0 = 0 angle_ticks = map(degree_ticks, np.linspace(degree0, 360, 5)) grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) tick_formatter2 = DictFormatter( dict(zip(np.linspace(1000, 6000, 6), map(str, np.linspace(0, 5000, 6))))) grid_locator2 = MaxNLocator(5) gh = floating_axes.GridHelperCurveLinear(tr, extremes=(2 * np.pi, np.pi, 1000, 6000), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2) fig = plt.figure() ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=gh)
response.close() np.save('data/hmi_rmesh.npy', rmesh) # rot2d has 49 columns, latitudes are 90-i*15/8; i starts at 0 lat = np.array([15./8.*i for i in np.arange(49)])/180.*np.pi r, th = np.meshgrid(rmesh, lat) # adapted from # http://matplotlib.org/examples/axes_grid/demo_floating_axes.html fig = pl.gcf() tr = PolarAxes.PolarTransform() angle_ticks = [(0.0, r"$0^\circ$"), (0.25*np.pi, r"$45^\circ$"), (0.5*np.pi, r"$90^\circ$")] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) grid_locator2 = MaxNLocator(2) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(0, 0.5*np.pi, 0, 1), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=None) ax1 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper) fig.add_subplot(ax1) ax1.axis["left"].set_axis_direction("bottom") ax1.axis["right"].set_axis_direction("top")
def create_cg(st, fig=None, subplot=111): """ Helper function to create curvelinear grid The function makes use of the Matplotlib AXISARTIST namespace `mpl_toolkits.axisartist \ <https://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html>`_. Here are some limitations to normal Matplotlib Axes. While using the Matplotlib `AxesGrid Toolkit \ <https://matplotlib.org/mpl_toolkits/axes_grid/index.html>`_ most of the limitations can be overcome. See `Matplotlib AxesGrid Toolkit User’s Guide \ <https://matplotlib.org/mpl_toolkits/axes_grid/users/index.html>`_. Parameters ---------- st : string scan type, 'PPI' or 'RHI' fig : matplotlib Figure object If given, the PPI will be plotted into this figure object. Axes are created as needed. If None a new figure object will be created or current figure will be used, depending on "subplot". subplot : :class:`matplotlib:matplotlib.gridspec.GridSpec`, \ matplotlib grid definition nrows/ncols/plotnumber, see examples section defaults to '111', only one subplot Returns ------- cgax : matplotlib toolkit axisartist Axes object curvelinear Axes (r-theta-grid) caax : matplotlib Axes object (twin to cgax) Cartesian Axes (x-y-grid) for plotting cartesian data paax : matplotlib Axes object (parasite to cgax) The parasite axes object for plotting polar data """ if st == 'RHI': # create transformation tr = Affine2D().scale(np.pi / 180, 1) + PolarAxes.PolarTransform() # build up curvelinear grid extreme_finder = ah.ExtremeFinderCycle(20, 20, lon_cycle=100, lat_cycle=None, lon_minmax=(0, np.inf), lat_minmax=(0, np.inf), ) # locator and formatter for angular annotation grid_locator1 = ah.LocatorDMS(10.) tick_formatter1 = ah.FormatterDMS() # grid_helper for curvelinear grid grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=None, tick_formatter1=tick_formatter1, tick_formatter2=None, ) # try to set nice locations for range gridlines grid_helper.grid_finder.grid_locator2._nbins = 30.0 grid_helper.grid_finder.grid_locator2._steps = [0, 1, 1.5, 2, 2.5, 5, 10] if st == 'PPI': # Set theta start to north tr_rotate = Affine2D().translate(-90, 0) # set theta running clockwise tr_scale = Affine2D().scale(-np.pi / 180, 1) # create transformation tr = tr_rotate + tr_scale + PolarAxes.PolarTransform() # build up curvelinear grid extreme_finder = ah.ExtremeFinderCycle(20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=(360, 0), lat_minmax=(0, np.inf), ) # locator and formatter for angle annotation locs = [i for i in np.arange(0., 359., 10.)] grid_locator1 = FixedLocator(locs) tick_formatter1 = DictFormatter(dict([(i, r"${0:.0f}^\circ$".format(i)) for i in locs])) # grid_helper for curvelinear grid grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=None, tick_formatter1=tick_formatter1, tick_formatter2=None, ) # try to set nice locations for range gridlines grid_helper.grid_finder.grid_locator2._nbins = 15.0 grid_helper.grid_finder.grid_locator2._steps = [0, 1, 1.5, 2, 2.5, 5, 10] # if there is no figure object given if fig is None: # create new figure if there is only one subplot if subplot is 111: fig = pl.figure() # otherwise get current figure or create new figure else: fig = pl.gcf() # generate Axis cgax = SubplotHost(fig, subplot, grid_helper=grid_helper) fig.add_axes(cgax) # PPIs always plottetd with equal aspect if st == 'PPI': cgax.set_aspect('equal', adjustable='box') # get twin axis for cartesian grid caax = cgax.twin() # move axis annotation from right to left and top to bottom for # cartesian axis caax.toggle_axisline() # make right and top axis visible and show ticklabels (curvelinear axis) cgax.axis["top", "right"].set_visible(True) cgax.axis["top", "right"].major_ticklabels.set_visible(True) # make ticklabels of left and bottom axis invisible (curvelinear axis) cgax.axis["left", "bottom"].major_ticklabels.set_visible(False) # and also set tickmarklength to zero for better presentation # (curvelinear axis) cgax.axis["top", "right", "left", "bottom"].major_ticks.set_ticksize(0) # show theta (angles) on top and right axis cgax.axis["top"].get_helper().nth_coord_ticks = 0 cgax.axis["right"].get_helper().nth_coord_ticks = 0 # generate and add parasite axes with given transform paax = ParasiteAxesAuxTrans(cgax, tr, "equal") # note that paax.transData == tr + cgax.transData # Anything you draw in paax will match the ticks and grids of cgax. cgax.parasites.append(paax) return cgax, caax, paax
def taylor_normalized(scores, colors, angle_lim): import mpl_toolkits.axisartist.floating_axes as floating_axes from matplotlib.projections import PolarAxes from mpl_toolkits.axisartist.grid_finder import (FixedLocator, DictFormatter) fig = plt.figure() tr = PolarAxes.PolarTransform() min_corr = np.round(np.cos(angle_lim), 1) CCgrid = np.concatenate( (np.arange(min_corr * 10, 10, 2.0) / 10., [0.9, 0.95, 0.99])) CCpolar = np.arccos(CCgrid) gf = FixedLocator(CCpolar) tf = DictFormatter(dict(zip(CCpolar, map(str, CCgrid)))) STDgrid = np.arange(0, 2.0, .5) gfs = FixedLocator(STDgrid) tfs = DictFormatter(dict(zip(STDgrid, map(str, STDgrid)))) ra0, ra1 = 0, angle_lim cz0, cz1 = 0, 2 grid_helper = floating_axes.GridHelperCurveLinear(tr, extremes=(ra0, ra1, cz0, cz1), grid_locator1=gf, tick_formatter1=tf, grid_locator2=gfs, tick_formatter2=tfs) ax1 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper) fig.add_subplot(ax1) ax1.axis["top"].set_axis_direction("bottom") ax1.axis["top"].toggle(ticklabels=True, label=True) ax1.axis["top"].major_ticklabels.set_axis_direction("top") ax1.axis["top"].label.set_axis_direction("top") ax1.axis["top"].label.set_text("Correlation") ax1.axis['top'].label.set_size(14) ax1.axis["left"].set_axis_direction("bottom") ax1.axis["left"].label.set_text("Normalized Standard Deviation") ax1.axis['left'].label.set_size(14) ax1.axis["right"].set_axis_direction("top") ax1.axis["right"].toggle(ticklabels=True) ax1.axis["right"].major_ticklabels.set_axis_direction("left") ax1.axis["bottom"].set_visible(False) ax1 = ax1.get_aux_axes(tr) plt.grid(linestyle=':', alpha=0.5) for i, r in enumerate(scores.iterrows()): theta = np.arccos(r[1].CORRELATION) rr = r[1].MSTD / r[1].OSTD print(rr) print(theta) ax1.plot(theta, rr, 'o', label=r[0], color=colors[i]) ax1.plot(0, 1, 'o', label='Obs') plt.legend(loc='upper right', bbox_to_anchor=[1.3, 1.15]) plt.show() rs, ts = np.meshgrid(np.linspace(0, 2), np.linspace(0, angle_lim)) rms = np.sqrt(1 + rs**2 - 2 * rs * np.cos(ts)) ax1.contour(ts, rs, rms, 3, colors='0.5') #contours = ax1.contour(ts, rs, rms,3,colors='0.5') #plt.clabel(contours, inline=1, fontsize=10) plt.grid(linestyle=':', alpha=0.5) for i, r in enumerate(scores.iterrows()): crmse = np.sqrt(1 + (r[1].MSTD/scores.OSTD[i])**2 \ - 2*(r[1].MSTD/scores.OSTD[i])*r[1].CORRELATION) print(crmse) c1 = ax1.contour(ts, rs, rms, [crmse], colors=colors[i]) plt.clabel(c1, inline=1, fontsize=10, fmt='%1.2f')
def get_smith(fig, rect=111, plot_impedance=True, plot_ticks=False, plot_admittance=False, plot_labels=False): '''Function which returns an axis with a blank smith chart, provide a figure and optional rect coords''' #Example use: # fig3 = plt.figure(3) # ax31 = pySmith.get_smith(fig3, 221) # ax31.plot(np.real(filtsmatrix[0,:,0,0]),np.imag(filtsmatrix[0,:,0,0])) # ax32= pySmith.get_smith(fig3, 222) # ax32.plot(np.real(filtsmatrix[0,:,0,1]),np.imag(filtsmatrix[0,:,0,1])) # ax33 = pySmith.get_smith(fig3, 223) # ax33.plot(np.real(filtsmatrix[0,:,1,0]),np.imag(filtsmatrix[0,:,1,0])) # ax34 = pySmith.get_smith(fig3, 224) # ax34.plot(np.real(filtsmatrix[0,:,1,1]),np.imag(filtsmatrix[0,:,1,1])) try: #font definition font = { 'family': 'sans-serif', 'color': 'black', 'weight': 'normal', 'size': 16, } #plot radial tick marks tr = PolarAxes.PolarTransform() num_thetas = 8 #*3 #12 gives in 30 deg intervals, 8 in 45 deg, 24 in 15deg thetas = np.linspace(0.0, math.pi * (1 - 2.0 / num_thetas), num_thetas // 2) angle_ticks = [] #(0, r"$0$"), for theta in thetas: angle_info = [] angle_info.append(theta) deg = int(round(180.0 * theta / math.pi)) angle_info.append(r'%d$^{\circ}$' % deg) angle_ticks.append(angle_info) grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) thetas2 = np.linspace(math.pi, 2 * math.pi * (1 - 1.0 / num_thetas), num_thetas // 2) angle_ticks2 = [] #(0, r"$0$"), for theta in thetas2: angle_info = [] angle_info.append(theta) deg = int(round(180.0 * theta / math.pi)) angle_info.append(r'%d$^{\circ}$' % deg) angle_ticks2.append(angle_info) grid_locator2 = FixedLocator([v for v, s in angle_ticks2]) tick_formatter2 = DictFormatter(dict(angle_ticks2)) grid_helper1 = floating_axes.GridHelperCurveLinear( tr, extremes=(math.pi, 0, 1, 0), grid_locator1=grid_locator1, #grid_locator2=grid_locator2, tick_formatter1=tick_formatter1 #, #tick_formatter2=None, ) grid_helper2 = floating_axes.GridHelperCurveLinear( tr, extremes=(2 * math.pi, math.pi, 1, 0), grid_locator1=grid_locator2, #grid_locator2=grid_locator2, tick_formatter1=tick_formatter2 #, #tick_formatter2=None, ) r1 = int(math.floor(rect / 100)) r2 = int(math.floor((rect - 100 * r1) / 10)) r3 = int(math.floor((rect - 100 * r1 - 10 * r2))) ax = SubplotHost(fig, r1, r2, r3, grid_helper=grid_helper1) ax2 = SubplotHost(fig, r1, r2, r3, grid_helper=grid_helper2) #ax.set_aspect(math.pi/180.0,'datalim') fig.add_subplot(ax) fig.add_subplot(ax2) ax.axis["bottom"].major_ticklabels.set_axis_direction("top") ax.axis["bottom"].major_ticklabels.set_fontsize(13) ax.axis["left"].set_visible(False) ax.axis["left"].toggle(all=False) ax.axis["right"].set_visible(False) ax.axis["right"].toggle(all=False) ax.axis["top"].set_visible(False) ax.axis["top"].toggle(all=False) ax.patch.set_visible(False) ax2.axis["bottom"].major_ticklabels.set_fontsize(13) ax2.axis["left"].set_visible(False) ax2.axis["left"].toggle(all=False) ax2.axis["right"].set_visible(False) ax2.axis["right"].toggle(all=False) ax2.axis["top"].set_visible(False) ax2.axis["top"].toggle(all=False) #ax = fig.add_subplot(rect) #remove axis labels ax.axis('off') #set aspect ratio to 1 ax.set_aspect(1) #, 'datalim') #set limits ax.set_xlim([-1.02, 1.02]) ax.set_ylim([-1.02, 1.02]) #remove axis labels ax2.axis('off') #set aspect ratio to 1 ax2.set_aspect(1) #,'datalim') #set limits ax2.set_xlim([-1.02, 1.02]) ax2.set_ylim([-1.02, 1.02]) ax2.patch.set_visible(False) if plot_impedance: #make lines of constant resistance res_log = np.linspace(-4, 4, 9) react_log = np.linspace(-5, 5, 2001) res = 2**res_log react = 10**react_log react2 = np.append(-1.0 * react[::-1], np.array([0])) react = np.append(react2, react) for r in res: z = 1j * react + r gam = (z - 1) / (z + 1) x = np.real(gam) y = np.imag(gam) if abs(r - 1) > 1e-6: ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25) else: ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4) #make lines of constant reactance react_log = np.linspace(-3, 3, 7) res_log = np.linspace(-5, 5, 2001) res = 10**res_log react = 2**react_log react2 = np.append(-1.0 * react[::-1], np.array([0])) react = np.append(react2, react) for chi in react: z = 1j * chi + res gam = (z - 1) / (z + 1) x = np.real(gam) y = np.imag(gam) if abs(chi - 1) > 1e-6 and abs(chi + 1) > 1e-6 and abs(chi) > 1e-6: ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25) else: ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4) if plot_admittance: #make lines of constant conductance res_log = np.linspace(-4, 4, 9) react_log = np.linspace(-5, 5, 2001) res = 2**res_log react = 10**react_log react = np.append(-1.0 * react[::-1], react) for r in res: y = 1.0 / r + 1.0 / (1j * react) gam = (1.0 / y - 1) / (1.0 / y + 1) x = np.real(gam) y = np.imag(gam) if abs(r - 1) > 1e-6: ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25) else: ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4) #make lines of constant susceptance react_log = np.linspace(-3, 3, 7) res_log = np.linspace(-5, 5, 2001) res = 10**res_log react = 2**react_log react = np.append(-1.0 * react[::-1], react) for chi in react: y = 1.0 / (1j * chi) + 1.0 / res gam = (1.0 / y - 1) / (1.0 / y + 1) x = np.real(gam) y = np.imag(gam) if abs(chi - 1) > 1e-6 and abs(chi + 1) > 1e-6: ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25) else: ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4) y = 1.0 / res gam = (1.0 / y - 1) / (1.0 / y + 1) x = np.real(gam) y = np.imag(gam) ax.plot(x, y, c='k', linewidth=1.0, alpha=0.75) if plot_labels: #naive text placement only works for default python figure size with 1 subplot ax.text(-0.15, 1.04, r'$\Gamma$ = 1j', fontdict=font) ax.text(-1.4, -0.035, r'$\Gamma$ = -1', fontdict=font) ax.text(-0.17, -1.11, r'$\Gamma$ = -1j', fontdict=font) ax.text(1.04, -0.035, r'$\Gamma$ = 1', fontdict=font) if plot_ticks: num_minorticks = 3 num_thetas = num_thetas * (num_minorticks + 1) thetas = np.linspace(0, 2.0 * math.pi * (1.0 - 1.0 / num_thetas), num_thetas) r_inner = 0.985 r_outer = 1.0 rads = np.linspace(r_inner, r_outer, 2) ticknum = 0 for theta in thetas: x = rads * np.cos(theta) y = rads * np.sin(theta) if ticknum % (num_minorticks + 1) != 0: ax.plot(x, y, c='k', linewidth=1.0, alpha=1.0) ticknum = ticknum + 1 return ax except Exception as e: print('\nError in %s' % inspect.stack()[0][3]) print(e) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno)
def erpa_axes(fig, rect, PA_bin_edges, epq_edges, log_epq_offset): import mpl_toolkits.axisartist.floating_axes as floating_axes from matplotlib.projections import PolarAxes from mpl_toolkits.axisartist.grid_finder import (FixedLocator, DictFormatter) ''' Function that creates the axes for the energy resolved pitch angle plots. Arguments: fig: the figure the axes will be plotted on rect: the subplot of the figure the axis belongs on Note that the extreme/boundary values are swapped. If this function is used within the function erpa_plotter, the arguments are defined within erpa_plotter ''' tr = PolarAxes.PolarTransform() #pi = np.pi #setting tick marks and tick labels for the pitch angle/circumference axis angle_ticks = [(x * np.pi / 180.0, str(x) + '$^\circ$') for x in PA_bin_edges] grid_locator1 = FixedLocator([v for v, s in angle_ticks]) tick_formatter1 = DictFormatter(dict(angle_ticks)) #Make our log scale r axis start closer to r=0 #setting tick marks and tick labels of the energy per charge/radial axis radius_ticks = [ (np.log10(x) - log_epq_offset, "{:.1f}".format(x)) for x in epq_edges ] #may cause issue if log(epq) < 0 (negative radius on polar plot...) grid_locator2 = FixedLocator([v for v, s in radius_ticks]) tick_formatter2 = DictFormatter(dict(radius_ticks)) #Arika's version with the extremes flipped grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(np.max(PA_bin_edges) * np.pi / 180.0, np.min(PA_bin_edges), np.max(np.log10(epq_edges)) - log_epq_offset, np.min(np.log10(epq_edges)) - log_epq_offset), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2) #version w/o extremes flipped -> doesn't appear to work! #grid_helper = floating_axes.GridHelperCurveLinear( # tr, extremes=(np.min(PA_bin_edges),np.max(PA_bin_edges)*np.pi/180.0, np.min(np.log10(epq_edges),np.max(np.log10(epq_edges)))), # grid_locator1=grid_locator1, # grid_locator2=grid_locator2, # tick_formatter1=tick_formatter1, # tick_formatter2=tick_formatter2) #grid_helper = floating_axes.GridHelperCurveLinear( # tr, extremes=(np.pi,0,1,0.5), # grid_locator1=grid_locator1, # grid_locator2=grid_locator2, # tick_formatter1=tick_formatter1, # tick_formatter2=tick_formatter2) ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) #Old way of doing plotting label and ticks ax1.axis["bottom"].major_ticklabels.set_rotation(180) ax1.axis["top"].major_ticklabels.set_axis_direction("top") ax1.axis["top"].label.set_axis_direction("top") ax1.axis['bottom'].major_ticklabels.set_fontsize( 15) #pitch angle tick label #after some experimenting, this works! #bad documentation for this #new experiemnt with radial text on right hand side ax1.axis['left'].toggle( ticklabels=False) #turn off left side radial labels ax1.axis['right'].label.set_text('E/q (keV/e)') ax1.axis['right'].label.set_fontsize(15) ax1.axis['right'].label.set_visible( True) #turn on right side radial labels ax1.axis['right'].toggle(ticklabels=True, label='E/q (keV/e)') ax1.axis['right'].major_ticklabels.set_fontsize( 15) #E/q tick label size, after some guesswork, this works! #Alternate plotting label and ticks section --> doesn't appear to work! #adjust x axis (theta): # ticklabels=True # thlabel='Pitch Angle' # rlabel='E/q (keV/e)' # ax1.axis["bottom"].set_visible(False) # ax1.axis["top"].set_axis_direction("bottom") # tick direction # ax1.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel)) # ax1.axis["top"].major_ticklabels.set_axis_direction("top") # ax1.axis["top"].label.set_axis_direction("top") # # # adjust y axis (r): # ax1.axis["left"].set_axis_direction("bottom") # tick direction # ax1.axis["right"].set_axis_direction("top") # tick direction # ax1.axis["left"].toggle(ticklabels=ticklabels, label=bool(rlabel)) # # # add labels: # ax1.axis["top"].label.set_text(thlabel) # ax1.axis["left"].label.set_text(rlabel) #create a parasite axes whose transData in RA, cz aux_ax = ax1.get_aux_axes(tr) aux_ax.set_axis_bgcolor('k') ###Note from Arika Egan: Not sure why this part is necessary, but it accompanied the example this function was created from, and it doesn't do any harm. aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax ax1.patch.zorder = 0.9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to prevent this. return ax1, aux_ax
def fractional_polar_axes(f, thlim=(0, 180), rlim=(0, 1), step=(30, 0.25), thlabel='theta', rlabel='r', ticklabels=True, rlabels = None, subplot=111): '''Return polar axes that adhere to desired theta (in deg) and r limits. steps for theta and r are really just hints for the locators.''' th0, th1 = thlim # deg r0, r1 = rlim thstep, rstep = step # scale degrees to radians: tr_scale = Affine2D().scale(np.pi/180., 1.) pa = PolarAxes tr = tr_scale + pa.PolarTransform() theta_grid_locator = angle_helper.LocatorDMS((th1-th0)//thstep) r_grid_locator = MaxNLocator((r1-r0)//rstep) theta_tick_formatter = angle_helper.FormatterDMS() if rlabels: rlabels = DictFormatter(rlabels) grid_helper = GridHelperCurveLinear(tr, extremes=(th0, th1, r0, r1), grid_locator1=theta_grid_locator, grid_locator2=r_grid_locator, tick_formatter1=theta_tick_formatter, tick_formatter2=rlabels) a = FloatingSubplot(f, subplot, grid_helper=grid_helper) f.add_subplot(a) # adjust x axis (theta): a.axis["bottom"].set_visible(False) a.axis["top"].set_axis_direction("bottom") # tick direction a.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel)) a.axis["top"].major_ticklabels.set_axis_direction("top") a.axis["top"].label.set_axis_direction("top") a.axis["top"].major_ticklabels.set_pad(10) # adjust y axis (r): a.axis["left"].set_axis_direction("bottom") # tick direction a.axis["right"].set_axis_direction("top") # tick direction a.axis["left"].toggle(ticklabels=True, label=bool(rlabel)) # add labels: a.axis["top"].label.set_text(thlabel) a.axis["left"].label.set_text(rlabel) # create a parasite axes whose transData is theta, r: auxa = a.get_aux_axes(tr) # make aux_ax to have a clip path as in a?: auxa.patch = a.patch # this has a side effect that the patch is drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to prevent this: a.patch.zorder = -2 # add sector lines for both dimensions: thticks = grid_helper.grid_info['lon_info'][0] rticks = grid_helper.grid_info['lat_info'][0] for th in thticks[1:-1]: # all but the first and last auxa.plot([th, th], [r0, r1], ':', c='grey', zorder=-1, lw=0.5) for ri, r in enumerate(rticks): # plot first r line as axes border in solid black only if it isn't at r=0 if ri == 0 and r != 0: ls, lw, color = 'solid', 1, 'black' else: ls, lw, color = 'dashed', 0.5, 'grey' # From http://stackoverflow.com/a/19828753/2020363 auxa.add_artist(plt.Circle([0, 0], radius=r, ls=ls, lw=lw, color=color, fill=False, transform=auxa.transData._b, zorder=-1)) return auxa
def plot_shape(topological, max_level=10): ''' Shows the average tree shape as a bullseye plot. Parameters ---------- topological : TopologicalAnalysisResult Topological stats of the model to be visualized. max_level : int Maximul tree-depth of the visualization. Maximum allowed value is 16. Returns ------- : matplotlib.figure.Figure The matpotlib Figure ''' ts = topological.avg_tree_shape() max_levels, _ = ts.shape max_levels = min(max_levels, max_level + 1) # precision of the plot (should be at least 2**max_levels) max_nodes = max(128, 2**max_levels) # custom color map cm = LinearSegmentedColormap.from_list( 'w2r', [(1, 1, 1), (23. / 255., 118. / 255., 182. / 255.)], N=256) # figure fig = plt.figure(1, figsize=(12, 6)) tr = Affine2D().translate(np.pi, 0) + PolarAxes.PolarTransform() x_ticks = [x + 2. for x in range(max_levels - 1)] grid_locator2 = FixedLocator(x_ticks) tick_formatter2 = DictFormatter( {k: " " + str(int(k) - 1) for k in x_ticks}) grid_helper = floating_axes.GridHelperCurveLinear( tr, extremes=(0, np.pi, 0, max_levels), grid_locator2=grid_locator2, tick_formatter2=tick_formatter2) ax3 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper) fig.add_axes(ax3) # fix axes ax3.axis["bottom"].set_visible(False) ax3.axis["top"].set_visible(False) ax3.axis["right"].set_axis_direction("top") ax3.axis["left"].set_axis_direction("bottom") ax3.axis["left"].major_ticklabels.set_pad(-5) ax3.axis["left"].major_ticklabels.set_rotation(180) # ax3.axis["left"].label.set_text("tree level") # ax3.axis["left"].label.set_ha("right") ax3.axis["left"].label.set_rotation(180) ax3.axis["left"].label.set_pad(20) ax3.axis["left"].major_ticklabels.set_ha("left") ax = ax3.get_aux_axes(tr) ax.patch = ax3.patch # for aux_ax to have a clip path as in ax ax3.patch.zorder = .9 # but this has a side effect that the patch is # drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to # prevent this. # data to be plotted theta, r = np.mgrid[0:np.pi:(max_nodes + 1) * 1j, 0:max_levels + 1] z = np.zeros(theta.size).reshape(theta.shape) for level in xrange(max_levels): num_nodes = 2**level num_same_color = max_nodes / num_nodes for node in xrange(num_nodes): if node < ts.shape[1]: z[num_same_color * node:num_same_color * (node + 1), level] = ts[level, node] # draw the tree nodes frequencies h = ax.pcolormesh(theta, r, z, cmap=cm, vmin=0., vmax=1.) # color bar cax = fig.add_axes([.95, 0.15, 0.025, 0.8]) # axes for the colot bar cbar = fig.colorbar(h, cax=cax, ticks=np.linspace(0, 1, 11)) cbar.ax.tick_params(labelsize=8) cax.set_title('Frequency', verticalalignment="bottom", fontsize=10) # separate depths for level in xrange(1, max_levels + 1): ax.plot(np.linspace(0, np.pi, num=128), [1 * level] * 128, 'k:', lw=0.3) # separate left sub-tree from right sub-tree ax.plot([np.pi, np.pi], [0, 1], 'k-') ax.plot([0, 0], [0, 1], 'k-') # label tree depths ax.text(np.pi / 2 * 3, .2, "ROOT", horizontalalignment='center', verticalalignment='center') ax.text(-.08, max_levels, "Tree level", verticalalignment='bottom', fontsize=14) # left/right subtree # ax.text(np.pi/4.,max_levels*1.15, "Left subtree", fontsize=12, # horizontalalignment="center", verticalalignment="center") # ax.text(np.pi/4.*3,max_levels*1.15, "Right subtree", fontsize=12, # horizontalalignment="center", verticalalignment="center") ax3.set_title("Average Tree Shape: " + str(topological.model), fontsize=16, y=1.2) return fig
cbar = plt.gcf().colorbar(pm, shrink=0.8, extend='both') #, pad=0.05) plt.gca().invert_xaxis() cbar.set_label('Z (dBZ)', fontsize=fft) caax.set_xlabel('x (km)', fontsize=fft) caax.set_ylabel('z (km)', fontsize=fft) cbar.ax.tick_params(labelsize=fft) caax.tick_params(labelsize=fft) plt.figtext(xl, yu, 'c) BoXPol RHI \n 2014-10-07, 02:37 UTC', fontsize=fft) gh = cgax.get_grid_helper() locs = [0.] gh.grid_finder.grid_locator1 = FixedLocator(locs) gh.grid_finder.tick_formatter1 = DictFormatter( dict([(i, r"${0:.0f}^\circ$".format(i)) for i in locs])) plt.yticks(fontsize=fft) plt.xticks(fontsize=fft) plt.tight_layout() plt.show() ''' grid_gpm_xy2 = np.vstack((gpm_x[:,cut].ravel(), gpm_y.ravel())).transpose() # GPM Grid erschaffen xxxyyy = np.vstack((xxx[0:-1,0:-1].ravel(), yyy[0:-1,0:-1].ravel())).transpose() mask1 = ~np.isnan(ma) result2 = wrl.ipol.interpolate(xxxyyy, grid_gpm_xy2, ma[mask1].reshape(ma.shape[0]*ma.shape[1],1), wrl.ipol.Idw, nnearest=4) #Idw result2 = np.ma.masked_invalid(result2)
def fractional_polar_axes(f, thlim=(0, 180), rlim=(0, 1), step=(30, 0.01), thlabel=r'$\alpha$', rlabel='z', ticklabels=True): import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D from matplotlib.projections import PolarAxes from mpl_toolkits.axisartist import angle_helper from mpl_toolkits.axisartist.grid_finder import MaxNLocator from mpl_toolkits.axisartist.floating_axes import GridHelperCurveLinear, FloatingSubplot from mpl_toolkits.axisartist.grid_finder import (FixedLocator, MaxNLocator, DictFormatter) """Return polar axes that adhere to desired theta (in deg) and r limits. steps for theta and r are really just hints for the locators. Using negative values for rlim causes problems for GridHelperCurveLinear for some reason""" th0, th1 = thlim # deg r0, r1 = rlim thstep, rstep = step # scale degrees to radians: tr_scale = Affine2D().scale(np.pi/180., 1.) tr = tr_scale + PolarAxes.PolarTransform() theta_grid_locator = angle_helper.LocatorDMS((th1-th0) // thstep) r_grid_locator = MaxNLocator((r1-r0) // rstep) theta_tick_formatter = angle_helper.FormatterDMS() theta_tick_formatter = None theta_ticks = [(0, r"$90^{\circ}$"), (30, r"$120^{\circ}$"), (60, r"$150^{\circ}$"), (90, r"$180^{\circ}$"), (120, r"$210^{\circ}$"), (150, r"$270^{\circ}$"), (180, r"$0^{\circ}$")] theta_tick_formatter = DictFormatter(dict(theta_ticks)) grid_helper = GridHelperCurveLinear(tr, extremes=(th0, th1, r0, r1), grid_locator1=theta_grid_locator, grid_locator2=r_grid_locator, tick_formatter1=theta_tick_formatter, tick_formatter2=None) a = FloatingSubplot(f, 111, grid_helper=grid_helper) f.add_subplot(a) # adjust x axis (theta): a.axis["bottom"].set_visible(False) a.axis["top"].set_axis_direction("bottom") # tick direction a.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel)) a.axis["top"].major_ticklabels.set_axis_direction("top") a.axis["top"].label.set_axis_direction("top") # adjust y axis (r): a.axis["left"].set_axis_direction("bottom") # tick direction a.axis["right"].set_axis_direction("top") # tick direction a.axis["left"].toggle(ticklabels=ticklabels, label=bool(rlabel)) # add labels: a.axis["top"].label.set_text(thlabel) a.axis["left"].label.set_text(rlabel) # create a parasite axes whose transData is theta, r: auxa = a.get_aux_axes(tr) # make aux_ax to have a clip path as in a?: auxa.patch = a.patch # this has a side effect that the patch is drawn twice, and possibly over some other # artists. So, we decrease the zorder a bit to prevent this: a.patch.zorder = -2 # add sector lines for both dimensions: thticks = grid_helper.grid_info['lon_info'][0] rticks = grid_helper.grid_info['lat_info'][0] for th in thticks[1:-1]: # all but the first and last auxa.plot([th, th], [r0, r1], '--', c='grey', zorder=-1) for ri, r in enumerate(rticks): # plot first r line as axes border in solid black only if it isn't at r=0 if ri == 0 and r != 0: ls, lw, color = 'solid', 2, 'black' else: ls, lw, color = 'dashed', 1, 'grey' # From http://stackoverflow.com/a/19828753/2020363 auxa.add_artist(plt.Circle([0, 0], radius=r, ls=ls, lw=lw, color=color, fill=False, transform=auxa.transData._b, zorder=-1)) return auxa