def __init__(self, *args, **kwargs): """ use the optional key-word arg 'transform' to supply a 2x2 transform-matrix """ try: transform = kwargs.pop('transform') except KeyError: transform = Matrix.eye(2) if isinstance(transform, GridHelperCurveLinear): assert 'Itransform' not in kwargs, ( 'no Itransform when transform is a %s' % type(transform)) grid_helper = transform elif callable(transform): grid_helper = GridHelperCurveLinear( [transform, kwargs.pop('Itransform')]) else: transform = Matrix(transform) try: Itransform = kwargs.pop('Itransform') except KeyError: Itransform = transform**(-1) grid_helper = GridHelperCurveLinear([ self.makeTransform(transform), self.makeTransform(Itransform) ]) kwargs['grid_helper'] = grid_helper mpl_toolkits.axisartist.Axes.__init__(self, *args, **kwargs)
def test_polar_box(): # Remove this line when this test image is regenerated. plt.rcParams['text.kerning_factor'] = 6 fig = plt.figure(figsize=(5, 5)) # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf)) grid_locator1 = angle_helper.LocatorDMS(12) tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) ax1.axis["right"].major_ticklabels.set_visible(True) ax1.axis["top"].major_ticklabels.set_visible(True) # let right axis shows ticklabels for 1st coordinate (angle) ax1.axis["right"].get_helper().nth_coord_ticks = 0 # let bottom axis shows ticklabels for 2nd coordinate (radius) ax1.axis["bottom"].get_helper().nth_coord_ticks = 1 fig.add_subplot(ax1) ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1) axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper().set_extremes(2, 12) ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1) axis.label.set_text("Test 2") axis.get_helper().set_extremes(-180, 90) # A parasite axes with given transform ax2 = ParasiteAxes(ax1, tr, viewlim_mode="equal") assert ax2.transData == tr + ax1.transData # Anything you draw in ax2 will match the ticks and grids of ax1. ax1.parasites.append(ax2) ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
def test_polar_box(): fig = plt.figure(figsize=(5, 5)) # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf)) grid_locator1 = angle_helper.LocatorDMS(12) tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) ax1.axis["right"].major_ticklabels.set_visible(True) ax1.axis["top"].major_ticklabels.set_visible(True) # let right axis shows ticklabels for 1st coordinate (angle) ax1.axis["right"].get_helper().nth_coord_ticks = 0 # let bottom axis shows ticklabels for 2nd coordinate (radius) ax1.axis["bottom"].get_helper().nth_coord_ticks = 1 fig.add_subplot(ax1) ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1) axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 2, 12 ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1) axis.label.set_text("Test 2") axis.get_helper()._extremes = -180, 90 # A parasite axes with given transform ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") assert ax2.transData == tr + ax1.transData # Anything you draw in ax2 will match the ticks and grids of ax1. ax1.parasites.append(ax2) ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
def __spacetime_diagram_o_prime_frame(self): # from (x,t) to (x',t') def tr(x_prime, t_prime): x_prime, t_prime = np.asarray(x_prime), np.asarray(t_prime) return self.lorentz_transformations.transform( x_prime, t_prime, self.velocity) # form (x',t') to (x,t) def inv_tr(x, t): x, t = np.asarray(x), np.asarray(t) return self.lorentz_transformations.transform(x, t, -self.velocity) grid_helper = GridHelperCurveLinear((tr, inv_tr)) ax = SubplotHost(self.fig, 1, 2, 2, grid_helper=grid_helper) self.fig.add_subplot(ax) ax.set_xlabel("x'", loc="center") ax.set_ylabel("t'", loc="center") # O x axis ax.axis["x1"] = x1 = ax.new_floating_axis(0, 0) x1.label.set_text("x") # O t axis ax.axis["t1"] = t1 = ax.new_floating_axis(1, 0) t1.label.set_text("t") self.__add_x_and_y_axis(ax) ax.format_coord = self.__format_coord_o_prime_frame self.__remove_ticks(ax, x1, t1) self.world_lines_plotter.transform_and_plot(plt, ax, self.velocity)
def curvelinear_test1(fig): """ grid for custom transform. """ def tr(x, y): x, y = np.asarray(x), np.asarray(y) return x, y - x def inv_tr(x, y): x, y = np.asarray(x), np.asarray(y) return x, y + x grid_helper = GridHelperCurveLinear((tr, inv_tr)) ax1 = Subplot(fig, 1, 2, 1, grid_helper=grid_helper) # ax1 will have a ticks and gridlines defined by the given # transform (+ transData of the Axes). Note that the transform of # the Axes itself (i.e., transData) is not affected by the given # transform. fig.add_subplot(ax1) xx, yy = tr([3, 6], [5.0, 10.]) ax1.plot(xx, yy, linewidth=2.0) ax1.set_aspect(1.) ax1.set_xlim(0, 10.) ax1.set_ylim(0, 10.) ax1.axis["t"] = ax1.new_floating_axis(0, 3.) ax1.axis["t2"] = ax1.new_floating_axis(1, 7.) ax1.grid(True, zorder=0)
def setup_axes(fig, rect): """Polar projection, but in a rectangular box.""" # see demo_curvelinear_grid.py for details tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() extreme_finder = angle_helper.ExtremeFinderCycle( 20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) grid_locator2 = grid_finder.MaxNLocator(5) tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1) ax1 = fig.add_subplot(rect, axes_class=axisartist.Axes, grid_helper=grid_helper) ax1.axis[:].set_visible(False) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) return ax1
def curvelinear_test1(fig): """Grid for custom transform.""" def tr(x, y): sgn = np.sign(x) x, y = np.abs(np.asarray(x)), np.asarray(y) return sgn*x**.5, y def inv_tr(x, y): sgn = np.sign(x) x, y = np.asarray(x), np.asarray(y) return sgn*x**2, y grid_helper = GridHelperCurveLinear( (tr, inv_tr), extreme_finder=ExtremeFinderSimple(20, 20), # better tick density grid_locator1=MaxNLocator(nbins=6), grid_locator2=MaxNLocator(nbins=6)) ax1 = fig.add_subplot(axes_class=Axes, grid_helper=grid_helper) # ax1 will have a ticks and gridlines defined by the given # transform (+ transData of the Axes). Note that the transform of the Axes # itself (i.e., transData) is not affected by the given transform. ax1.imshow(np.arange(25).reshape(5, 5), vmax=50, cmap=plt.cm.gray_r, origin="lower")
def curvelinear_test1(fig): """ Grid for custom transform. """ def tr(x, y): return x, y - x def inv_tr(x, y): return x, y + x grid_helper = GridHelperCurveLinear((tr, inv_tr)) ax1 = fig.add_subplot(1, 2, 1, axes_class=Axes, grid_helper=grid_helper) # ax1 will have ticks and gridlines defined by the given transform (+ # transData of the Axes). Note that the transform of the Axes itself # (i.e., transData) is not affected by the given transform. xx, yy = tr(np.array([3, 6]), np.array([5, 10])) ax1.plot(xx, yy) ax1.set_aspect(1) ax1.set_xlim(0, 10) ax1.set_ylim(0, 10) ax1.axis["t"] = ax1.new_floating_axis(0, 3) ax1.axis["t2"] = ax1.new_floating_axis(1, 7) ax1.grid(True, zorder=0)
def test_custom_transform(): class MyTransform(Transform): input_dims = output_dims = 2 def __init__(self, resolution): """ Resolution is the number of steps to interpolate between each input line segment to approximate its path in transformed space. """ Transform.__init__(self) self._resolution = resolution def transform(self, ll): x, y = ll.T return np.column_stack([x, y - x]) transform_non_affine = transform def transform_path(self, path): ipath = path.interpolated(self._resolution) return Path(self.transform(ipath.vertices), ipath.codes) transform_path_non_affine = transform_path def inverted(self): return MyTransformInv(self._resolution) class MyTransformInv(Transform): input_dims = output_dims = 2 def __init__(self, resolution): Transform.__init__(self) self._resolution = resolution def transform(self, ll): x, y = ll.T return np.column_stack([x, y + x]) def inverted(self): return MyTransform(self._resolution) fig = plt.figure() SubplotHost = host_subplot_class_factory(Axes) tr = MyTransform(1) grid_helper = GridHelperCurveLinear(tr) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) fig.add_subplot(ax1) ax2 = ParasiteAxes(ax1, tr, viewlim_mode="equal") ax1.parasites.append(ax2) ax2.plot([3, 6], [5.0, 10.]) ax1.set_aspect(1.) ax1.set_xlim(0, 10) ax1.set_ylim(0, 10) ax1.grid(True)
def plotCorrelation(tauArray,kappaMatrix,kappaLower=None,kappaUpper=None,CI=None,amplify=1): """Plots Pearson Correlation Coefficient K(t,tau) with rotated axis to indicate absolute t, and relative time shift tau, between two signals x(t),y(t). Specified matrix has to be square with values -1 < p < +1 with corresponding time array giving the absolute time, t of the centers of each correlated window.""" # defining tranformation for relative time shifts def R(x, y): x, y = asarray(x), asarray(y) #return x,y return (2*x - y)/2, (y + 2*x)/2 def Rt(x, y): x, y = asarray(x), asarray(y) #return x,y return x + y, x - y # create figure with rotated axes fig = figure(figsize=(10, 10),frameon=False) grid_locator = angle_helper.LocatorDMS(20) grid_helper = GridHelperCurveLinear((R, Rt), grid_locator1=grid_locator, grid_locator2=grid_locator) ax = Subplot(fig, 1, 1, 1, grid_helper=grid_helper) fig.add_subplot(ax);ax.axis('off'); # copying over matrix K = array(kappaMatrix) # zero out correlations if confidence intervals overlap zero if all(kappaLower != None) and all(kappaUpper != None) : K[ (kappaLower<0) * (0<kappaUpper) ] = 0 # zero out statistically insignificant correlations if all(CI != None) : K[ abs(kappaMatrix) < CI ] = 0 # display pearson correlation matrix with +ive in red and -ive in blue ax.imshow(K,cmap="RdBu_r",interpolation="none",origin="bottom", extent = (tauArray[0],tauArray[-1],tauArray[0],tauArray[-1]),vmin=-1.0/amplify,vmax=1.0/amplify) # display rotated axes time,t and time delay,tau ax.axis["tau"] = tau = ax.new_floating_axis(0,0) ax.axis["t"] = t = ax.new_floating_axis(1,0) # setting axes options ax.set_xlim(tauArray[0],tauArray[-1]) ax.set_ylim(tauArray[0],tauArray[-1]) ax.grid(which="both") ax.set_aspect(1) return fig
def create_axes(self, rect=111): """ Create a special AxisArtist to overlay grid coordinates. Much of this taken from the examples here: http://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html """ # from curved coordinate to rectlinear coordinate. def tr(x, y): x, y = np.asarray(x), np.asarray(y) return self(x, y) # from rectlinear coordinate to curved coordinate. def inv_tr(x, y): x, y = np.asarray(x), np.asarray(y) return self(x, y, inverse=True) # Cycle the coordinates extreme_finder = angle_helper.ExtremeFinderCycle(20, 20) # Find a grid values appropriate for the coordinate. # The argument is a approximate number of grid lines. grid_locator1 = angle_helper.LocatorD(8, include_last=False) grid_locator2 = angle_helper.LocatorD(6, include_last=False) # Format the values of the grid tick_formatter1 = FormatterFgcm() tick_formatter2 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear( (tr, inv_tr), extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2, ) fig = plt.gcf() ax = axisartist.Subplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax) ax.axis['left'].major_ticklabels.set_visible(True) ax.axis['right'].major_ticklabels.set_visible(True) ax.axis['bottom'].major_ticklabels.set_visible(True) ax.axis['top'].major_ticklabels.set_visible(True) ax.set_xlabel("Right Ascension") ax.set_ylabel("Declination") return fig, ax
def curvelinear_test2(fig): """ Polar projection, but in a rectangular box. """ # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi/180, 1) + PolarAxes.PolarTransform() # Polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). extreme_finder = angle_helper.ExtremeFinderCycle( nx=20, ny=20, # Number of sampling points in each direction. lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) # Find grid values appropriate for the coordinate (degree, minute, second). grid_locator1 = angle_helper.LocatorDMS(12) # Use an appropriate formatter. Note that the acceptable Locator and # Formatter classes are a bit different than that of Matplotlib, which # cannot directly be used here (this may be possible in the future). tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear( tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1) ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper) # make ticklabels of right and top axis visible. ax1.axis["right"].major_ticklabels.set_visible(True) ax1.axis["top"].major_ticklabels.set_visible(True) # let right axis shows ticklabels for 1st coordinate (angle) ax1.axis["right"].get_helper().nth_coord_ticks = 0 # let bottom axis shows ticklabels for 2nd coordinate (radius) ax1.axis["bottom"].get_helper().nth_coord_ticks = 1 fig.add_subplot(ax1) ax1.set_aspect(1) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True, zorder=0) # A parasite axes with given transform ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") # note that ax2.transData == tr + ax1.transData # Anything you draw in ax2 will match the ticks and grids of ax1. ax1.parasites.append(ax2) ax2.plot(np.linspace(0, 30, 51), np.linspace(10, 10, 51), linewidth=2)
def create_axes_nonorthogonal(self, transform): self.clear_figure() self.set_nonorthogonal_transform(transform) self.ax = CurveLinearSubPlot(self.fig, 1, 1, 1, grid_helper=GridHelperCurveLinear( (self.nonortho_tr, transform.inv_tr))) self.set_grid_on() self.fig.add_subplot(self.ax) self.plot_MDH = self.plot_MDH_nonorthogonal self.canvas.draw_idle()
def create_axes_nonorthogonal(self, transform): self.clear_figure() self.set_nonorthogonal_transform(transform) self.ax = CurveLinearSubPlot(self.fig, 1, 1, 1, grid_helper=GridHelperCurveLinear( (transform.tr, transform.inv_tr))) # don't redraw on zoom as the data is rebinned and has to be redrawn again anyway self.enable_zoom_on_mouse_scroll(redraw=False) self.set_grid_on() self.fig.add_subplot(self.ax) self.plot_MDH = self.plot_MDH_nonorthogonal self.canvas.draw_idle()
def setup_axes1(self, fig, T_ticks, subplotshape=None): """ A simple one. """ deg = -45. self.tr = Affine2D().rotate_deg(deg) theta_ticks = [] #np.arange(theta_min, theta_max, d_T) grid_helper = GridHelperCurveLinear( self.tr, grid_locator1=FixedLocator(T_ticks), grid_locator2=FixedLocator(theta_ticks)) if subplotshape is None: subplotshape = (1, 1, 1) ax1 = Subplot(fig, *subplotshape, grid_helper=grid_helper) # ax1 will have a ticks and gridlines defined by the given # transform (+ transData of the Axes). Note that the transform of # the Axes itself (i.e., transData) is not affected by the given # transform. fig.add_subplot(ax1) # SW, SE, NE, NW corners = np.array([[-25., -20.], [30., 40.], [-40., 120.], [-105., 60.]]) corners_t = self._tf(corners[:, 0], corners[:, 1]) # ax1.set_aspect(1.) x_min, x_max = self.x_range ax1.set_xlim(x_min, x_max) ax1.set_ylim(*self.y_range) ax1.set_xlabel('Temperature [C]') ax1.set_aspect(1) #ax1.axis["t"]=ax1.new_floating_axis(0, 0.) #T_axis = ax1.axis['t'] #theta_axis = ax1.axis["t2"]=ax1.new_floating_axis(1, 0.) # plot.draw() # plot.show() self.ax1 = ax1
def curvelinear_test1(fig): """ grid for custom transform. """ def tr(x, y): sgn = np.sign(x) x, y = np.abs(np.asarray(x)), np.asarray(y) return sgn * x**.5, y def inv_tr(x, y): sgn = np.sign(x) x, y = np.asarray(x), np.asarray(y) return sgn * x**2, y extreme_finder = angle_helper.ExtremeFinderCycle( 20, 20, lon_cycle=None, lat_cycle=None, # (0, np.inf), lon_minmax=None, lat_minmax=None, ) grid_helper = GridHelperCurveLinear((tr, inv_tr), extreme_finder=extreme_finder) ax1 = Subplot(fig, 111, grid_helper=grid_helper) # ax1 will have a ticks and gridlines defined by the given # transform (+ transData of the Axes). Note that the transform of # the Axes itself (i.e., transData) is not affected by the given # transform. fig.add_subplot(ax1) ax1.imshow(np.arange(25).reshape(5, 5), vmax=50, cmap=plt.cm.gray_r, interpolation="nearest", origin="lower") # tick density grid_helper.grid_finder.grid_locator1._nbins = 6 grid_helper.grid_finder.grid_locator2._nbins = 6
def compare(c1, c2): fig = plt.figure() fig.set_size_inches(5, 5) fig.set_dpi(150) def tr(x, y): return c2.T.dot([x, y]) def inv_tr(x, y): v = c2.T.T.dot([x, y]) return v[0], v[1] grid_helper = GridHelperCurveLinear((tr, inv_tr)) # Instruct matplotlib to create object from AxisArtist instead ax1 = fig.add_subplot(1, 2, 1, axes_class=Axes) ax2 = fig.add_subplot(1, 2, 2, axes_class=Axes, grid_helper=grid_helper) # Add axis that (in general) have transformed ax2.axis["t1"] = ax2.new_floating_axis(nth_coord=0, value=0) ax2.axis["t2"] = ax2.new_floating_axis(nth_coord=1, value=0) ax2.axis['top'].set_visible(False) ax2.axis['bottom'].set_visible(False) ax2.axis['left'].set_visible(False) ax2.axis['right'].set_visible(False) c1.plot(ax1) c2.plot(ax2) print(' c1 c2') print('') print(f' e1 {c1.e1} {c2.e1}') print(f' e2 {c1.e2} {c2.e2}') print('') print(f'||e1|| {np.linalg.norm(c1.e1)} {np.linalg.norm(c2.e1)}') print(f'||e2|| {np.linalg.norm(c1.e2)} {np.linalg.norm(c2.e2)}') print('') print(f'||T|| {np.linalg.norm(c1.v)} {np.linalg.norm(c2.v)}') print('') print(f' Tx {c1.v.x} {c2.v.x}') print(f' Ty {c1.v.y} {c1.v.y}')
def curvelinear_test1(fig): """ Grid for custom transform. """ def tr(x, y): x, y = numpy.asarray(x), numpy.asarray(y) return x, y - (2 * x) # return x + (5 * y), (7 * y) + (3 * x) def inv_tr(x, y): x, y = numpy.asarray(x), numpy.asarray(y) return x, y + (2 * x) grid_helper = GridHelperCurveLinear((tr, inv_tr)) ax1 = Subplot(fig, 1, 1, 1, grid_helper=grid_helper) # ax1 will have a ticks and gridlines defined by the given # transform (+ transData of the Axes). Note that the transform of # the Axes itself (i.e., transData) is not affected by the given # transform. fig.add_subplot(ax1) xx, yy = tr([0, 1], [0, 2]) ax1.plot(xx, yy, linewidth=2.0) ax1.set_aspect(1) ax1.set_xlim(-3, 3) ax1.set_ylim(-3, 3) ax1.axis["t"] = ax1.new_floating_axis( 0, 0 ) # first argument appears to be slope, second argument appears to be starting point on vertical ax1.axis["t2"] = ax1.new_floating_axis(1, 0) ax1.axhline(y=0, color='r') ax1.axvline(x=0, color='r') ax1.grid(True, zorder=0)
def setup_axes(fig, rect): """ polar projection, but in a rectangular box. """ # 细节可以参考前面“曲线网格”的例子 tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform() extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) grid_locator2 = grid_finder.MaxNLocator(5) tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1 ) ax1 = axisartist.Subplot(fig, rect, grid_helper=grid_helper) ax1.axis[:].toggle(ticklabels=False) fig.add_subplot(ax1) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) return ax1
x_thetas = [ x_from_Tp(Bolton.theta_dry(theta_i, p_all), p_all) for theta_i in theta_levels ] x_mixing_ratios = [ x_from_Tp((Bolton.mixing_ratio_line(p_all, MRi) + C_to_K), p_all) for MRi in mixing_ratios ] mesh_T, mesh_p = np.meshgrid( np.arange(-60.0, T_levels.max() - C_to_K + 0.1, 0.1), p_all) theta_ep_mesh = Bolton.theta_ep_field(mesh_T, mesh_p) # Plotting Code! skew_grid_helper = GridHelperCurveLinear((from_thermo, to_thermo)) fig = plt.figure() ax = Subplot(fig, 1, 1, 1, grid_helper=skew_grid_helper) fig.add_subplot(ax) for yi in y_p_levels: ax.plot((x_min, x_max), (yi, yi), color=(1.0, 0.8, 0.8)) for x_T in x_T_levels: ax.plot(x_T, y_all_p, color=(1.0, 0.5, 0.5)) for x_theta in x_thetas: ax.plot(x_theta, y_all_p, color=(1.0, 0.7, 0.7)) for x_mixing_ratio in x_mixing_ratios:
def __init__(self, ol=None, parent=None): # pylint: disable=unused-argument,super-on-old-class super(DGSPlannerGUI, self).__init__(parent) #OrientedLattice if ValidateOL(ol): self.ol = ol else: self.ol = mantid.geometry.OrientedLattice() self.masterDict = dict() #holds info about instrument and ranges self.updatedInstrument = False self.updatedOL = False self.wg = None #workspace group self.instrumentWidget = InstrumentSetupWidget.InstrumentSetupWidget( self) self.setLayout(QtGui.QHBoxLayout()) controlLayout = QtGui.QVBoxLayout() controlLayout.addWidget(self.instrumentWidget) self.ublayout = QtGui.QHBoxLayout() self.classic = ClassicUBInputWidget.ClassicUBInputWidget(self.ol) self.ublayout.addWidget(self.classic, alignment=QtCore.Qt.AlignTop, stretch=1) self.matrix = MatrixUBInputWidget.MatrixUBInputWidget(self.ol) self.ublayout.addWidget(self.matrix, alignment=QtCore.Qt.AlignTop, stretch=1) controlLayout.addLayout(self.ublayout) self.dimensionWidget = DimensionSelectorWidget.DimensionSelectorWidget( self) controlLayout.addWidget(self.dimensionWidget) plotControlLayout = QtGui.QGridLayout() self.plotButton = QtGui.QPushButton("Plot", self) self.oplotButton = QtGui.QPushButton("Overplot", self) self.helpButton = QtGui.QPushButton("?", self) self.colorLabel = QtGui.QLabel('Color by angle', self) self.colorButton = QtGui.QCheckBox(self) self.colorButton.toggle() self.aspectLabel = QtGui.QLabel('Aspect ratio 1:1', self) self.aspectButton = QtGui.QCheckBox(self) self.saveButton = QtGui.QPushButton("Save Figure", self) plotControlLayout.addWidget(self.plotButton, 0, 0) plotControlLayout.addWidget(self.oplotButton, 0, 1) plotControlLayout.addWidget(self.colorLabel, 0, 2, QtCore.Qt.AlignRight) plotControlLayout.addWidget(self.colorButton, 0, 3) plotControlLayout.addWidget(self.aspectLabel, 0, 4, QtCore.Qt.AlignRight) plotControlLayout.addWidget(self.aspectButton, 0, 5) plotControlLayout.addWidget(self.helpButton, 0, 6) plotControlLayout.addWidget(self.saveButton, 0, 7) controlLayout.addLayout(plotControlLayout) self.layout().addLayout(controlLayout) #figure self.figure = Figure() self.figure.patch.set_facecolor('white') self.canvas = FigureCanvas(self.figure) self.grid_helper = GridHelperCurveLinear((self.tr, self.inv_tr)) self.trajfig = Subplot(self.figure, 1, 1, 1, grid_helper=self.grid_helper) self.trajfig.hold(True) self.figure.add_subplot(self.trajfig) self.layout().addWidget(self.canvas) self.needToClear = False self.saveDir = '' #connections self.matrix.UBmodel.changed.connect(self.updateUB) self.matrix.UBmodel.changed.connect(self.classic.updateOL) self.classic.changed.connect(self.matrix.UBmodel.updateOL) self.classic.changed.connect(self.updateUB) self.instrumentWidget.changed.connect(self.updateParams) self.dimensionWidget.changed.connect(self.updateParams) self.plotButton.clicked.connect(self.updateFigure) self.oplotButton.clicked.connect(self.updateFigure) self.helpButton.clicked.connect(self.help) self.saveButton.clicked.connect(self.save) #force an update of values self.instrumentWidget.updateAll() self.dimensionWidget.updateChanges() #help self.assistantProcess = QtCore.QProcess(self) # pylint: disable=protected-access self.collectionFile = os.path.join(mantid._bindir, '../docs/qthelp/MantidProject.qhc') version = ".".join(mantid.__version__.split(".")[:2]) self.qtUrl = 'qthelp://org.sphinx.mantidproject.' + version + '/doc/interfaces/DGSPlanner.html' self.externalUrl = 'http://docs.mantidproject.org/nightly/interfaces/DGSPlanner.html' #control for cancel button self.iterations = 0 self.progress_canceled = False
# The following is taken from: # http://matplotlib.org/examples/axes_grid/demo_curvelinear_grid.html from mpl_toolkits.axisartist import Subplot from mpl_toolkits.axisartist.grid_helper_curvelinear import \ GridHelperCurveLinear def tr(x, y): # source (data) to target (rectilinear plot) coordinates x, y = numpy.asarray(x), numpy.asarray(y) return x + 0.2 * y, y - x def inv_tr(x, y): x, y = numpy.asarray(x), numpy.asarray(y) return x - 0.2 * y, y + x grid_helper = GridHelperCurveLinear((tr, inv_tr)) ax6 = Subplot(fig, nrow, ncol, 6, grid_helper=grid_helper) fig.add_subplot(ax6) ax6.set_title('non-ortho axes') xx, yy = tr([3, 6], [5.0, 10.]) ax6.plot(xx, yy) ax6.set_aspect(1.) ax6.set_xlim(0, 10.) ax6.set_ylim(0, 10.) ax6.axis["t"] = ax6.new_floating_axis(0, 3.) ax6.axis["t2"] = ax6.new_floating_axis(1, 7.) ax6.grid(True)
def __init__(self, parent=None, window_flags=None, ol=None): # pylint: disable=unused-argument,super-on-old-class super(DGSPlannerGUI, self).__init__(parent) if window_flags: self.setWindowFlags(window_flags) # OrientedLattice if ValidateOL(ol): self.ol = ol else: self.ol = mantid.geometry.OrientedLattice() self.masterDict = dict() # holds info about instrument and ranges self.updatedInstrument = False self.instrumentWAND = False self.updatedOL = False self.wg = None # workspace group self.instrumentWidget = InstrumentSetupWidget.InstrumentSetupWidget( self) self.setLayout(QtWidgets.QHBoxLayout()) controlLayout = QtWidgets.QVBoxLayout() geometryBox = QtWidgets.QGroupBox("Instrument Geometry") plotBox = QtWidgets.QGroupBox("Plot Axes") geometryBoxLayout = QtWidgets.QVBoxLayout() geometryBoxLayout.addWidget(self.instrumentWidget) geometryBox.setLayout(geometryBoxLayout) controlLayout.addWidget(geometryBox) self.ublayout = QtWidgets.QHBoxLayout() self.classic = ClassicUBInputWidget.ClassicUBInputWidget(self.ol) self.ublayout.addWidget(self.classic, alignment=QtCore.Qt.AlignTop, stretch=1) self.matrix = MatrixUBInputWidget.MatrixUBInputWidget(self.ol) self.ublayout.addWidget(self.matrix, alignment=QtCore.Qt.AlignTop, stretch=1) sampleBox = QtWidgets.QGroupBox("Sample") sampleBox.setLayout(self.ublayout) controlLayout.addWidget(sampleBox) self.dimensionWidget = DimensionSelectorWidget.DimensionSelectorWidget( self) plotBoxLayout = QtWidgets.QVBoxLayout() plotBoxLayout.addWidget(self.dimensionWidget) plotControlLayout = QtWidgets.QGridLayout() self.plotButton = QtWidgets.QPushButton("Plot", self) self.oplotButton = QtWidgets.QPushButton("Overplot", self) self.helpButton = QtWidgets.QPushButton("?", self) self.colorLabel = QtWidgets.QLabel('Color by angle', self) self.colorButton = QtWidgets.QCheckBox(self) self.colorButton.toggle() self.aspectLabel = QtWidgets.QLabel('Aspect ratio 1:1', self) self.aspectButton = QtWidgets.QCheckBox(self) self.saveButton = QtWidgets.QPushButton("Save Figure", self) plotControlLayout.addWidget(self.plotButton, 0, 0) plotControlLayout.addWidget(self.oplotButton, 0, 1) plotControlLayout.addWidget(self.colorLabel, 0, 2, QtCore.Qt.AlignRight) plotControlLayout.addWidget(self.colorButton, 0, 3) plotControlLayout.addWidget(self.aspectLabel, 0, 4, QtCore.Qt.AlignRight) plotControlLayout.addWidget(self.aspectButton, 0, 5) plotControlLayout.addWidget(self.helpButton, 0, 6) plotControlLayout.addWidget(self.saveButton, 0, 7) plotBoxLayout.addLayout(plotControlLayout) plotBox = QtWidgets.QGroupBox("Plot Axes") plotBox.setLayout(plotBoxLayout) controlLayout.addWidget(plotBox) self.layout().addLayout(controlLayout) # figure self.figure = Figure() self.figure.patch.set_facecolor('white') self.canvas = FigureCanvas(self.figure) self.grid_helper = GridHelperCurveLinear((self.tr, self.inv_tr)) self.trajfig = Subplot(self.figure, 1, 1, 1, grid_helper=self.grid_helper) if matplotlib.compare_versions('2.1.0', matplotlib.__version__): self.trajfig.hold( True) # hold is deprecated since 2.1.0, true by default self.figure.add_subplot(self.trajfig) self.toolbar = MantidNavigationToolbar(self.canvas, self) figureLayout = QtWidgets.QVBoxLayout() figureLayout.addWidget(self.toolbar, 0) figureLayout.addWidget(self.canvas, 1) self.layout().addLayout(figureLayout) self.needToClear = False self.saveDir = '' # connections self.matrix.UBmodel.changed.connect(self.updateUB) self.matrix.UBmodel.changed.connect(self.classic.updateOL) self.classic.changed.connect(self.matrix.UBmodel.updateOL) self.classic.changed.connect(self.updateUB) self.instrumentWidget.changed.connect(self.updateParams) self.instrumentWidget.getInstrumentComboBox().activated[str].connect( self.instrumentUpdateEvent) self.instrumentWidget.getEditEi().textChanged.connect( self.eiWavelengthUpdateEvent) self.dimensionWidget.changed.connect(self.updateParams) self.plotButton.clicked.connect(self.updateFigure) self.oplotButton.clicked.connect(self.updateFigure) self.helpButton.clicked.connect(self.help) self.saveButton.clicked.connect(self.save) # force an update of values self.instrumentWidget.updateAll() self.dimensionWidget.updateChanges() # help self.assistant_process = QtCore.QProcess(self) # pylint: disable=protected-access self.mantidplot_name = 'DGS Planner' # control for cancel button self.iterations = 0 self.progress_canceled = False # register startup mantid.UsageService.registerFeatureUsage( mantid.kernel.FeatureType.Interface, "DGSPlanner", False)
def createRLUAxes(self,figure=None,ids=[1, 1, 1],basex=None,basey=None): """Create a reciprocal lattice plot for a given DataSet object. Args: - Dataset (DataSet): DataSet object for which the RLU plot is to be made. Kwargs: - figure: Matplotlib figure in which the axis is to be put (default None) - ids (array): List of integer numbers provided to the SubplotHost ids attribute (default [1,1,1]) - basex (float): Ticks are positioned at multiples of this value along x (default None) - basey (float): Ticks are positioned at multiples of this value along y (default None) Returns: - ax (Matplotlib axes): Axes containing the RLU plot. .. note:: When rlu axis is created, the orientation of Qx and Qy is assumed to be rotated as well. This is to be done in the self.View3D method call! .. note:: When using python 2 the changing of tick marks is not supported due to limitations in matplotlib. However, if python 3 is used, the number of ticks and their location can be change after the initialization using the set_xticks_number, set_yticks_number chaning the wanted number of tick marks, or the set_xticks_base or set_yticks_base to change the base number, see RLU tutorial under Tools. As default a sufficient base number is found and will update when zooming. """ sample = copy.deepcopy(self.sample) for samp in sample: samp.convert = np.einsum('ij,j...->i...',samp.RotMat,samp.convert) #sample.convert = np.einsum('ij,j...->i...',sample.RotMat,sample.convert) samp.convertinv = np.linalg.inv(samp.convert) # Convert from Qx, Qy to projX, projY samp.orientationMatrix = np.dot(samp.RotMat3D,samp.orientationMatrix) samp.orientationMatrixINV = np.linalg.inv(samp.orientationMatrix) samp.theta = 0.0 if figure is None: fig = plt.figure(figsize=(7, 4)) else: fig = figure def calculateTicks(ticks,angle,round=True): val = ticks/np.tan(angle/2.0) if round: return np.array(np.round(val),dtype=int) else: return val if pythonVersion==3: # Only for python 3 if not basex is None or not basey is None: # Either basex or basey is provided (or both) if basex is None: basex = calculateTicks(basey,sample[0].projectionAngle,round=False) elif basey is None: basey = basex/calculateTicks(1.0,sample[0].projectionAngle,round=False) grid_locator1 = MultipleLocator(base=basex) grid_locator2 = MultipleLocator(base=basey) else: basex = 0.5 basey = 0.5 grid_locator1 = MultipleLocator(base=basex) grid_locator2 = MultipleLocator(base=basey) grid_helper = GridHelperCurveLinear((sample[0].inv_tr, sample[0].tr),grid_locator1=grid_locator1,grid_locator2=grid_locator2) else: # Python 2 grid_helper = GridHelperCurveLinear((sample[0].inv_tr, sample[0].tr)) ax = SubplotHost(fig, *ids, grid_helper=grid_helper) ax.sample = sample[0] if pythonVersion==3: # Only for python 3 ax.basex = basex ax.basey = basey def set_axis(ax,v1,v2,*args): if not args is (): points = np.concatenate([[v1,v2],[x for x in args]],axis=0) else: points = np.array([v1,v2]) if points.shape[1] == 3: points = ax.sample.calculateHKLtoProjection(points[:,0],points[:,1],points[:,2]).T boundaries = np.array([ax.sample.inv_tr(x[0],x[1]) for x in points]) ax.set_xlim(boundaries[:,0].min(),boundaries[:,0].max()) ax.set_ylim(boundaries[:,1].min(),boundaries[:,1].max()) if pythonVersion == 3: # Only possible in python 3 ax.forceGridUpdate() fig.add_subplot(ax) ax.set_aspect(1.) ax.grid(True, zorder=0) if not np.isclose(ax.sample.projectionAngle,np.pi/2.0,atol=0.001): ax.axis["top"].major_ticklabels.set_visible(True) ax.axis["right"].major_ticklabels.set_visible(True) ax.format_coord = ax.sample.format_coord ax.set_axis = lambda v1,v2,*args: set_axis(ax,v1,v2,*args) def beautifyLabel(vec): Vec = [x.astype(int) if np.isclose(x.astype(float)-x.astype(int),0.0) else x.astype(float) for x in vec] return '{} [RLU]'.format(', '.join([str(x) for x in Vec])) ax.set_xlabel(beautifyLabel(ax.sample.projectionVector1)) ax.set_ylabel(beautifyLabel(ax.sample.projectionVector2)) if pythonVersion==3: # Only for python 3 ax.calculateTicks = lambda value:calculateTicks(value,ax.sample.projectionAngle) ax.forceGridUpdate = lambda:forceGridUpdate(ax) ax._oldXlimDiff = np.diff(ax.get_xlim()) ax._oldYlimDiff = np.diff(ax.get_ylim()) ax.get_aspect_ratio = lambda: get_aspect(ax) ax.callbacks.connect('xlim_changed', axisChanged) ax.callbacks.connect('ylim_changed', axisChanged) ax.callbacks.connect('draw_event',lambda ax: axisChanged(ax,forceUpdate=True)) ax.axisChanged = lambda direction='both': axisChanged(ax,forceUpdate=True,direction=direction) @updateAxisDecorator(ax=ax,direction='x') def set_xticks_base(xBase,ax=ax): """Setter of the base x ticks to be used for plotting Args: - xBase (float): Base of the tick marks """ if not isinstance(ax._grid_helper.grid_finder.grid_locator1,MultipleLocator): l1 = MultipleLocator(base=xBase) ax._grid_helper.update_grid_finder(grid_locator1=l1) ax.xbase = xBase @updateAxisDecorator(ax=ax,direction='y') def set_yticks_base(yBase,ax=ax): """Setter of the base y ticks to be used for plotting Args: - yBase (float): Base of the tick marks """ if not isinstance(ax._grid_helper.grid_finder.grid_locator2,MultipleLocator): l2 = MultipleLocator(base=yBase) ax._grid_helper.update_grid_finder(grid_locator2=l2) ax.ybase = yBase @updateAxisDecorator(ax=ax,direction='x') def set_xticks_number(xNumber,ax=ax): """Setter of the number of x ticks to be used for plotting Args: - xNumber (int): Number of x tick marks """ if not isinstance(ax._grid_helper.grid_finder.grid_locator1,MaxNLocator): l1 = MaxNLocator(nbins=xNumber) ax._grid_helper.update_grid_finder(grid_locator1=l1) ax.xticks = xNumber @updateAxisDecorator(ax=ax,direction='y') def set_yticks_number(yNumber,ax=ax): """Setter of the number of y ticks to be used for plotting Args: - yNumber (int): Number of y tick marks """ if not isinstance(ax._grid_helper.grid_finder.grid_locator2,MaxNLocator): l2 = MaxNLocator(nbins=yNumber) ax._grid_helper.update_grid_finder(grid_locator2=l2) ax.yticks = yNumber ax.set_xticks_base = set_xticks_base ax.set_yticks_base = set_yticks_base ax.set_xticks_number = set_xticks_number ax.set_yticks_number = set_yticks_number return ax
def createQEAxes(DataSet=None,axis=0,figure = None, projectionVector1 = None, projectionVector2 = None): """Function to create Q E plot Kwargs: - DataSet (DataSet): If provided and no projections vectors creates QE axis for main direction (default None) - axis (int): Whether to create axis 0 or 1 (projection vector 0 or orthogonal to this, default 0) - figure (figure): If provided, this is used to create the axis within (default None) - projectionVector1 (vec): Projection vector along which data is plotted. If not provided sample vector is used (default None) - projectionVector2 (vec): Projection vector orthogonal to data. If not provided sample vector is used (default None) """ if projectionVector1 is None or projectionVector2 is None: v1 = DataSet.sample[0].projectionVector1 v2 = DataSet.sample[0].projectionVector2 angle = DataSet.sample[0].projectionAngle orientationMatrix = DataSet.sample[0].orientationMatrix else: v1 = np.array(projectionVector1) v2 = np.array(projectionVector2) if not np.all([x.shape==(3,) for x in [v1,v2]]) or not np.all([len(x.shape)==1 for x in [v1,v2]]): raise AttributeError('Provided vector(s) is not 3D: projectionVector1.shape={} or projectionVector2.shape={}'.format(v1.shape,v2.shape)) angle = np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))) orientationMatrix = np.ones(3) sample = copy.deepcopy(DataSet.sample) v1,v2 = sample[0].projectionVector1,sample[0].projectionVector2 angle = np.sign(np.dot(np.cross(v1,v2),sample[0].planeNormal))*sample[0].projectionAngle v2Length = np.linalg.norm(v2)/np.linalg.norm(v1) projectionMatrix = np.linalg.inv(np.array([[1,0],[np.cos(angle)*v2Length,np.sin(angle)*v2Length]]).T) projectionVectorQX = np.dot(np.dot(projectionMatrix,[1,0]),np.array([v1,v2])) projectionVectorQY = np.dot(np.dot(projectionMatrix,[0,1]),np.array([v1,v2])) projectionVectorQX = _tools.LengthOrder(projectionVectorQX) projectionVectorQY = _tools.LengthOrder(projectionVectorQY) projectionVectorQXLength = np.linalg.norm(np.dot(orientationMatrix,projectionVectorQY)) projectionVectorQYLength = np.linalg.norm(np.dot(orientationMatrix,projectionVectorQX)) projectionVectorQXFormated = ', '.join(['{:.3f}'.format(x) for x in projectionVectorQX]) projectionVectorQYFormated = ', '.join(['{:.3f}'.format(x) for x in projectionVectorQY]) if axis == 0: projectionVectorLength = projectionVectorQYLength projectionVectorLengthORthogonal = projectionVectorQXLength projectionVectorFormated = projectionVectorQXFormated projectionVector = projectionVectorQX projectionVectorOrthogonal = projectionVectorQY elif axis == 1: projectionVectorLength = projectionVectorQXLength projectionVectorFormated = projectionVectorQYFormated projectionVectorLengthORthogonal = projectionVectorQYLength projectionVector = projectionVectorQY projectionVectorOrthogonal = projectionVectorQX else: raise AttributeError('Provided axis of {} is not allowed. Should be either 0 or 1.'.format(axis)) if figure is None: figure = plt.figure(figsize=(7, 4)) else: figure.clf() def inv_tr(l,x,y): return x*l,y def tr(l,x,y): return x/l,y if pythonVersion == 3: grid_locator1 = MultipleLocator(base=1.0) # Standard X ticks is multiple locator grid_helper = GridHelperCurveLinear((lambda x,y:inv_tr(projectionVectorLength,x,y), lambda x,y:tr(projectionVectorLength,x,y)),grid_locator1=grid_locator1) else: grid_helper = GridHelperCurveLinear((lambda x,y:inv_tr(projectionVectorLength,x,y), lambda x,y:tr(projectionVectorLength,x,y))) ax = SubplotHost(figure, 1, 1, 1, grid_helper=grid_helper) ax.sample = sample[0] figure.add_subplot(ax) #ax.set_aspect(1.) ax.grid(True, zorder=0) def calculateRLU(l,v1,x,y,v,step): return np.asarray(x)/l*v1+v*step, np.asarray(y) def format_coord(x,y): # pragma: no cover # x is H,K,L and y is energy xformated = ', '.join(['{} = {}'.format(Y[0],Y[1]) for Y in zip(['h','k','l'],['{:.4f}'.format(X) for X in x])]) return '{}, E={:.4f}'.format(xformated,y) ax.set_xlabel('{} [RLU]'.format(projectionVectorFormated)) ax.set_ylabel('E [meV]') ax._length = projectionVectorLengthORthogonal ax._projectionVector = projectionVector ax._projectionVectorOrthogonal = projectionVectorOrthogonal ax._step = 0.0 ax.calculateRLU = lambda x,y: calculateRLU(projectionVectorLength,ax._projectionVector,x,y,ax._projectionVectorOrthogonal,ax._step) ax.format_coord = lambda x,y: format_coord(*ax.calculateRLU(x,y)) if pythonVersion == 3: ax.forceGridUpdate = lambda:forceGridUpdate(ax) ax.xticks = 7 def xAxisChanged(axis, forceUpdate=False): locator = axis._grid_helper.grid_finder.grid_locator1 xlim = axis.get_xlim() xlimDiff = np.diff(xlim) if isinstance(locator,MultipleLocator): if hasattr(axis,'xBase'): base = axis.xBase else: base = calculateBase(locator,xlimDiff,axis.xticks) locator.set_params(base=base) elif isinstance(locator,MaxNLocator): if hasattr(axis,'xTicks'): ticks = getattr(axis,'xTicks') else: ticks = 7 locator.set_params(nbins = ticks) else: return axis.forceGridUpdate() ax.callbacks.connect('xlim_changed', xAxisChanged) ax.callbacks.connect('draw_event',lambda ax: xAxisChanged(ax,forceUpdate=True)) ax.xAxisChanged = lambda: xAxisChanged(ax,forceUpdate=True) @updateXAxisDecorator(ax=ax) def set_xticks_base(xBase=None,ax=ax): """Setter of the base x ticks to be used for plotting Kwargs: - xBase (float): Base of the tick marks (default automatic) """ if not isinstance(ax._grid_helper.grid_finder.grid_locator1,MultipleLocator): l1 = MultipleLocator(base=xBase) ax._grid_helper.update_grid_finder(grid_locator1=l1) if xBase is None: if hasattr(ax,'xBase'): delattr(ax,'xBase') else: ax.xBase = xBase @updateXAxisDecorator(ax=ax) def set_xticks_number(xNumber = None,ax=ax): """Setter of the number of x ticks to be used for plotting Kwargs: - xNumber (int): Number of x tick marks (default 7) """ if xNumber is None: xNumber = 7 if not isinstance(ax._grid_helper.grid_finder.grid_locator1,MaxNLocator): l1 = MaxNLocator(nbins=xNumber) ax._grid_helper.update_grid_finder(grid_locator1=l1) ax.xTicks = xNumber ax.set_xticks_base = set_xticks_base ax.set_xticks_number = set_xticks_number return ax
def curvelinear_test2(fig): """ polar projection, but in a rectangular box. """ # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). # 20, 20 : number of sampling points along x, y direction extreme_finder = angle_helper.ExtremeFinderCycle( 20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) # Find a grid values appropriate for the coordinate (degree, # minute, second). tick_formatter1 = angle_helper.FormatterDMS() # And also uses an appropriate formatter. Note that,the # acceptable Locator and Formatter class is a bit different than # that of mpl's, and you cannot directly use mpl's Locator and # Formatter here (but may be possible in the future). grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1) ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper) # make ticklabels of right and top axis visible. ax1.axis["right"].major_ticklabels.set_visible(True) ax1.axis["top"].major_ticklabels.set_visible(True) # let right axis shows ticklabels for 1st coordinate (angle) ax1.axis["right"].get_helper().nth_coord_ticks = 0 # let bottom axis shows ticklabels for 2nd coordinate (radius) ax1.axis["bottom"].get_helper().nth_coord_ticks = 1 fig.add_subplot(ax1) # A parasite axes with given transform ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") # note that ax2.transData == tr + ax1.transData # Anthing you draw in ax2 will match the ticks and grids of ax1. ax1.parasites.append(ax2) intp = cbook.simple_linear_interpolation ax2.plot(intp(np.array([0, 30]), 50), intp(np.array([10., 10.]), 50), linewidth=2.0) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True, zorder=0)
def create_axes(self, rect=111): """ Create a special AxisArtist to overlay grid coordinates. Much of this taken from the examples here: http://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html """ # from curved coordinate to rectlinear coordinate. def tr(x, y): return self(x, y) # from rectlinear coordinate to curved coordinate. def inv_tr(x, y): return self(x, y, inverse=True) # Cycle the coordinates extreme_finder = angle_helper.ExtremeFinderCycle(20, 20) # Find a grid values appropriate for the coordinate. # The argument is a approximate number of grid lines. grid_locator1 = angle_helper.LocatorD(9, include_last=False) # grid_locator1 = angle_helper.LocatorD(8, include_last=False) grid_locator2 = angle_helper.LocatorD(6, include_last=False) # Format the values of the grid tick_formatter1 = self.create_tick_formatter() tick_formatter2 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear( (tr, inv_tr), extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2, ) fig = plt.gcf() rect = self.ax.get_position() ax = axisartist.Axes(fig, rect, grid_helper=grid_helper, frameon=False) fig.add_axes(ax) # Coordinate formatter def format_coord(x, y): return 'lon=%1.4f, lat=%1.4f' % inv_tr(x, y) ax.format_coord = format_coord ax.axis['left'].major_ticklabels.set_visible(True) ax.axis['right'].major_ticklabels.set_visible(False) ax.axis['bottom'].major_ticklabels.set_visible(True) ax.axis['top'].major_ticklabels.set_visible(True) ax.axis['bottom'].label.set(text="Right Ascension", size=18) ax.axis['left'].label.set(text="Declination", size=18) self.aa = ax # Set the current axis back to the SkyAxes fig.sca(self.ax) return fig, ax
def main(): origin = [0, 0] xCoord = [1, -1] yCoord = [1, 2] transformation = [[1, 3], [5, 2]] [eigenvalue1, eigenvalue2], [eigenvector1, eigenvector2] = LA.eig(transformation) print eigenvalue1, eigenvalue2, (3 - sqrt(61)) / 2, (3 + sqrt(61)) / 2 eigenvector1 = eigenvector1 / dot(eigenvector1, eigenvector1) eigenvector2 = eigenvector2 / dot(eigenvector2, eigenvector2) eigenCoord1 = zip(origin, 3 * eigenvalue1 * eigenvector1) print eigenvector1 fig, ax = plt.subplots() x_grid_locator = MaxNLocator(3 // 0.0125) y_grid_locator = MaxNLocator(3 // 0.00625) ax = AA.Axes( fig, [0.1, 0.1, 0.8, 0.8], grid_helper=GridHelperCurveLinear( (tr, inv_tr), grid_locator1=x_grid_locator, grid_locator2=y_grid_locator)) # This appears to be your margins fig.add_axes(ax) ax.axis["right"].set_visible(False) ax.axis["top"].set_visible(False) ax.axis["left"].set_visible(False) ax.axis["bottom"].set_visible(False) ax.grid(True, zorder=0) # ax.set_xticks([0.01, 0.02, 0.03]) ax.axis["t"] = ax.new_floating_axis( 0, 0 ) # first argument appears to be slope, second argument appears to be starting point on vertical ax.axis["t2"] = ax.new_floating_axis(1, 0) # ax.axis["t"].set_xticks([1, 2, 3, 4, 5, 6]) # ax.axis["t"].label.set_pad(2) ax.plot([0, 1], [0, 1]) # ax.axis["y=0"] = ax.new_floating_axis(nth_coord=0, value=0) # # ax.axis["x=0"] = ax.new_floating_axis(nth_coord=0, value=0) # ax.axis["right2"] = ax.new_fixed_axis(loc="right", offset=(-184, 0)) # ax.axis["t"] = ax.new_floating_axis(0, 0) # first argument appears to be slope, second argument appears to be starting point on vertical # ax.axis["t2"] = ax.new_floating_axis(1, 0) scalingFactor = (24 * sqrt(29)) / 5 otherFactor = 12 * sqrt(5) print scalingFactor / 3 print otherFactor / 3 ax.set_xlim(-scalingFactor, scalingFactor) ax.set_ylim(-otherFactor, otherFactor) ax.quiver(origin, origin, xCoord, yCoord, color=[colorDefault(0), colorDefault(3)], angles='xy', scale_units='xy', scale=1) ax.grid(True, which='both') ax.axhline(y=0, color='k') ax.axvline(x=0, color='k') # axis_to_data = ax.transAxes + ax.transData.inverted() # points_data = axis_to_data.transform((2, 3)) # data_to_axis = axis_to_data.inverted() # numpy.testing.assert_allclose((2, 3), data_to_axis.transform(points_data)) plt.xlim(-8, 8) plt.ylim(-8, 8) plt.figure() plt.quiver(origin, origin, xCoord, yCoord, color=[colorDefault(0), colorDefault(3)], angles='xy', scale_units='xy', scale=1) plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') # axis_to_data = ax.transAxes + ax.transData.inverted() # points_data = axis_to_data.transform((2, 3)) # data_to_axis = axis_to_data.inverted() # numpy.testing.assert_allclose((2, 3), data_to_axis.transform(points_data)) plt.xlim(-8, 8) plt.ylim(-8, 8) fig = plt.figure() x_grid_locator = MaxNLocator(3 // 0.0125) y_grid_locator = MaxNLocator(3 // 0.00625) ax = AA.Axes( fig, [0.1, 0.1, 0.8, 0.8], grid_helper=GridHelperCurveLinear( (tr, inv_tr), grid_locator1=x_grid_locator, grid_locator2=y_grid_locator)) # This appears to be your margins fig.add_axes(ax) ax.axis["right"].set_visible(False) ax.axis["top"].set_visible(False) ax.axis["left"].set_visible(False) ax.axis["bottom"].set_visible(False) ax.grid(True, zorder=0) # ax.set_xticks([0.01, 0.02, 0.03]) ax.axis["t"] = ax.new_floating_axis( 0, 0 ) # first argument appears to be slope, second argument appears to be starting point on vertical ax.axis["t2"] = ax.new_floating_axis(1, 0) # ax.axis["t"].set_xticks([1, 2, 3, 4, 5, 6]) # ax.axis["t"].label.set_pad(2) ax.plot([0, 1], [0, 1]) # ax.axis["y=0"] = ax.new_floating_axis(nth_coord=0, value=0) # # ax.axis["x=0"] = ax.new_floating_axis(nth_coord=0, value=0) # ax.axis["right2"] = ax.new_fixed_axis(loc="right", offset=(-184, 0)) # ax.axis["t"] = ax.new_floating_axis(0, 0) # first argument appears to be slope, second argument appears to be starting point on vertical # ax.axis["t2"] = ax.new_floating_axis(1, 0) scalingFactor = (24 * sqrt(29)) / 5 otherFactor = 12 * sqrt(5) print scalingFactor / 3 print otherFactor / 3 ax.set_xlim(-scalingFactor, scalingFactor) ax.set_ylim(-otherFactor, otherFactor) plt.show()
def test_axis_direction(): fig = plt.figure(figsize=(5, 5)) # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). # 20, 20 : number of sampling points along x, y direction extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) for axis in ax1.axis.values(): axis.set_visible(False) fig.add_subplot(ax1) ax1.axis["lat1"] = axis = grid_helper.new_floating_axis( 0, 130, axes=ax1, axis_direction="left") axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 0.001, 10 ax1.axis["lat2"] = axis = grid_helper.new_floating_axis( 0, 50, axes=ax1, axis_direction="right") axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 0.001, 10 ax1.axis["lon"] = axis = grid_helper.new_floating_axis( 1, 10, axes=ax1, axis_direction="bottom") axis.label.set_text("Test 2") axis.get_helper()._extremes = 50, 130 axis.major_ticklabels.set_axis_direction("top") axis.label.set_axis_direction("top") grid_helper.grid_finder.grid_locator1.den = 5 grid_helper.grid_finder.grid_locator2._nbins = 5 ax1.set_aspect(1.) ax1.set_xlim(-8, 8) ax1.set_ylim(-4, 12) ax1.grid(True)
def test_axis_direction(): fig = plt.figure(figsize=(5, 5)) # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). # 20, 20 : number of sampling points along x, y direction extreme_finder = angle_helper.ExtremeFinderCycle( 20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) for axis in ax1.axis.values(): axis.set_visible(False) fig.add_subplot(ax1) ax1.axis["lat1"] = axis = grid_helper.new_floating_axis( 0, 130, axes=ax1, axis_direction="left") axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 0.001, 10 ax1.axis["lat2"] = axis = grid_helper.new_floating_axis( 0, 50, axes=ax1, axis_direction="right") axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 0.001, 10 ax1.axis["lon"] = axis = grid_helper.new_floating_axis( 1, 10, axes=ax1, axis_direction="bottom") axis.label.set_text("Test 2") axis.get_helper()._extremes = 50, 130 axis.major_ticklabels.set_axis_direction("top") axis.label.set_axis_direction("top") grid_helper.grid_finder.grid_locator1.den = 5 grid_helper.grid_finder.grid_locator2._nbins = 5 ax1.set_aspect(1.) ax1.set_xlim(-8, 8) ax1.set_ylim(-4, 12) ax1.grid(True)
def create_axes(self,rect=111): """ Create a special AxisArtist to overlay grid coordinates. Much of this taken from the examples here: http://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html """ # from curved coordinate to rectlinear coordinate. def tr(x, y): x, y = np.asarray(x), np.asarray(y) return self(x,y) # from rectlinear coordinate to curved coordinate. def inv_tr(x,y): x, y = np.asarray(x), np.asarray(y) return self(x,y,inverse=True) # Cycle the coordinates extreme_finder = angle_helper.ExtremeFinderCycle(20, 20) # Find a grid values appropriate for the coordinate. # The argument is a approximate number of grid lines. grid_locator1 = angle_helper.LocatorD(9,include_last=False) #grid_locator1 = angle_helper.LocatorD(8,include_last=False) grid_locator2 = angle_helper.LocatorD(6,include_last=False) # Format the values of the grid tick_formatter1 = self.create_tick_formatter() tick_formatter2 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear((tr, inv_tr), extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2, ) fig = plt.gcf() if rect is None: # This doesn't quite work. Need to remove the existing axis... rect = plt.gca().get_position() plt.gca().axis('off') ax = axisartist.Axes(fig,rect,grid_helper=grid_helper) fig.add_axes(ax) else: ax = axisartist.Subplot(fig,rect,grid_helper=grid_helper) fig.add_subplot(ax) ## Coordinate formatter def format_coord(x, y): return 'lon=%1.4f, lat=%1.4f'%inv_tr(x,y) ax.format_coord = format_coord ax.axis['left'].major_ticklabels.set_visible(True) ax.axis['right'].major_ticklabels.set_visible(False) ax.axis['bottom'].major_ticklabels.set_visible(True) ax.axis['top'].major_ticklabels.set_visible(True) ax.set_xlabel("Right Ascension") ax.set_ylabel("Declination") #self.set_axes_limits() self.axisartist = ax return fig,ax
def sgrid(): # From matplotlib demos: # https://matplotlib.org/gallery/axisartist/demo_curvelinear_grid.html # https://matplotlib.org/gallery/axisartist/demo_floating_axis.html # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). # 20, 20 : number of sampling points along x, y direction sampling_points = 20 extreme_finder = ModifiedExtremeFinderCycle(sampling_points, sampling_points, lon_cycle=360, lat_cycle=None, lon_minmax=(90,270), lat_minmax=(0, np.inf),) grid_locator1 = angle_helper.LocatorDMS(15) tick_formatter1 = FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1 ) fig = plt.figure() ax = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) # make ticklabels of right invisible, and top axis visible. visible = True ax.axis[:].major_ticklabels.set_visible(visible) ax.axis[:].major_ticks.set_visible(False) ax.axis[:].invert_ticklabel_direction() ax.axis["wnxneg"] = axis = ax.new_floating_axis(0, 180) axis.set_ticklabel_direction("-") axis.label.set_visible(False) ax.axis["wnxpos"] = axis = ax.new_floating_axis(0, 0) axis.label.set_visible(False) ax.axis["wnypos"] = axis = ax.new_floating_axis(0, 90) axis.label.set_visible(False) axis.set_axis_direction("left") ax.axis["wnyneg"] = axis = ax.new_floating_axis(0, 270) axis.label.set_visible(False) axis.set_axis_direction("left") axis.invert_ticklabel_direction() axis.set_ticklabel_direction("-") # let left axis shows ticklabels for 1st coordinate (angle) ax.axis["left"].get_helper().nth_coord_ticks = 0 ax.axis["right"].get_helper().nth_coord_ticks = 0 ax.axis["left"].get_helper().nth_coord_ticks = 0 ax.axis["bottom"].get_helper().nth_coord_ticks = 0 fig.add_subplot(ax) ### RECTANGULAR X Y AXES WITH SCALE #par2 = ax.twiny() #par2.axis["top"].toggle(all=False) #par2.axis["right"].toggle(all=False) #new_fixed_axis = par2.get_grid_helper().new_fixed_axis #par2.axis["left"] = new_fixed_axis(loc="left", # axes=par2, # offset=(0, 0)) #par2.axis["bottom"] = new_fixed_axis(loc="bottom", # axes=par2, # offset=(0, 0)) ### FINISH RECTANGULAR ax.grid(True, zorder=0,linestyle='dotted') _final_setup(ax) return ax, fig