def preparePlot(self): """Prepare the plotting window""" plt.hot() self.figure = plt.figure(self.figNr) self.figure.clear() # this is black magic that makes the legend work with two axes if self.hasSubplotHost: self.axis1 = SubplotHost(self.figure, 111) self.figure.add_subplot(self.axis1) else: self.axis1 = self.figure.add_subplot(111) self.axis1.set_xlabel(self.xlabel) self.axis1.set_ylabel(self.ylabel) if len(self.alternate) > 0: self.axis2 = self.axis1.twinx() self.axis2.set_ylabel(self.ylabel2) try: if self.spec.logscale: self.axis1.set_yscale("log") if self.axis2: self.axis2.set_yscale("log") except AttributeError: pass
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 curvelinear_test2(fig): """ 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) 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) ax1.axis["right"].major_ticklabels.set_visible(True) ax1.axis["top"].major_ticklabels.set_visible(True) ax1.axis["right"].get_helper().nth_coord_ticks=0 ax1.axis["bottom"].get_helper().nth_coord_ticks=1 fig.add_subplot(ax1) ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") ax1.parasites.append(ax2) intp = cbook.simple_linear_interpolation ax2.plot(intp(np.array([0, 30]), 50), intp(np.array([10., 10.]), 50)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
def curvelinear_test2(fig): """ polar projection, but in a rectangular box. """ global ax1 import numpy as np import angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost, \ ParasiteAxesAuxTrans import matplotlib.cbook as cbook 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(5) 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) ax1.axis["right"].get_helper().nth_coord_ticks=0 ax1.axis["bottom"].get_helper().nth_coord_ticks=1 fig.add_subplot(ax1) grid_helper = ax1.get_grid_helper() ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 60, axes=ax1) axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes=2, 10 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 ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") ax1.parasites.append(ax2) intp = cbook.simple_linear_interpolation ax2.plot(intp(np.array([0, 30]), 50), intp(np.array([10., 10.]), 50)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
def setup_rot_axes(fig, rect): tr = Affine2D().rotate_deg(90.0) grid_helper = gh.GridHelperCurveLinear(tr) ax1 = SubplotHost(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax1) ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") ax1.set_ylim([end, start]) ax1.set_xlim([-8, 4]) ax2 = ax1.get_aux_axes(tr) ax1.set_aspect('auto') ax1.axis['top', 'right', 'left', 'bottom'].set_visible(False) return ax1, ax2
def preparePlot(self): """Prepare the plotting window""" plt.hot() self.figure=plt.figure(self.figNr) self.figure.clear() # this is black magic that makes the legend work with two axes if self.hasSubplotHost: self.axis1=SubplotHost(self.figure,111) self.figure.add_subplot(self.axis1) else: self.axis1=self.figure.add_subplot(111) self.axis1.set_xlabel(self.xlabel) self.axis1.set_ylabel(self.ylabel) if len(self.alternate)>0: self.axis2=self.axis1.twinx() self.axis2.set_ylabel(self.ylabel2) try: if self.spec.logscale: self.axis1.set_yscale("log") if self.axis2: self.axis2.set_yscale("log") except AttributeError: pass
def __init__(self, height, width, X, LY, Xlabel, LYlabel, linecolor, set_marker, set_linestyle, fontsize, set_markersize, set_linewidth, set_mfc, set_mew, set_mec): self.X = X fig = plt.figure(figsize=(height, width)) self.host = SubplotHost(fig, 111) plt.rc("font", size=fontsize) self.host.set_xlabel(Xlabel) self.host.set_ylabel(LYlabel) p1, = self.host.plot(X, LY, color=linecolor, marker=set_marker, ls=set_linestyle, ms=set_markersize, lw=set_linewidth, mfc=set_mfc, mew=set_mew, mec=set_mec) fig.add_axes(self.host) self.host.axis["left"].label.set_color(p1.get_color()) self.host.tick_params(axis='y', color=p1.get_color())
def get_axis_two_scales(fig, scale_x, scale_y, \ ax2_xlabel = None, ax2_ylabel = None, \ subplot = 111, sharex = None, sharey = None): kargs = {} if (sharex != None): kargs['sharex'] = sharex if (sharey != None): kargs['sharey'] = sharey ax1 = SubplotHost(fig, subplot, **kargs) ax1_to_2 = mtransforms.Affine2D().scale(1.0 / scale_x, 1.0 / scale_y) ax2 = ax1.twin(ax1_to_2) ax2.set_viewlim_mode("transform") fig.add_subplot(ax1) if (ax2_xlabel != None): ax2.set_xlabel(ax2_xlabel) if (ax2_ylabel != None): ax2.set_ylabel(ax2_ylabel) if (scale_x == 1.0): ax2.get_xaxis().set_visible(False) if (scale_y == 1.0): ax2.get_yaxis().set_visible(False) return ax1, ax2
def get_axis_two_scales(fig, scale_x, scale_y, \ ax2_xlabel = None, ax2_ylabel = None, \ subplot = 111, sharex = None, sharey = None): kargs = {} if (sharex != None): kargs['sharex'] = sharex if (sharey != None): kargs['sharey'] = sharey ax1 = SubplotHost(fig, subplot, **kargs) ax1_to_2 = mtransforms.Affine2D().scale(1.0/scale_x, 1.0/scale_y) ax2 = ax1.twin(ax1_to_2) ax2.set_viewlim_mode("transform") fig.add_subplot(ax1) if (ax2_xlabel != None): ax2.set_xlabel(ax2_xlabel) if (ax2_ylabel != None): ax2.set_ylabel(ax2_ylabel) if (scale_x == 1.0): ax2.get_xaxis().set_visible(False) if (scale_y == 1.0): ax2.get_yaxis().set_visible(False) return ax1, ax2
class multiY(): def __init__(self, height, width, X, LY, Xlabel, LYlabel, linecolor, set_marker, set_linestyle, fontsize, set_markersize, set_linewidth, set_mfc, set_mew, set_mec): self.X = X fig = plt.figure(figsize=(height, width)) self.host = SubplotHost(fig, 111) plt.rc("font", size=fontsize) self.host.set_xlabel(Xlabel) self.host.set_ylabel(LYlabel) p1, = self.host.plot(X, LY, color=linecolor, marker=set_marker, ls=set_linestyle, ms=set_markersize, lw=set_linewidth, mfc=set_mfc, mew=set_mew, mec=set_mec) fig.add_axes(self.host) self.host.axis["left"].label.set_color(p1.get_color()) self.host.tick_params(axis='y', color=p1.get_color()) def parasites(self, set_offset, PY, PYlabel, side, Plinecolor, Pset_marker, Pset_linestyle, Pset_markersize, Pset_linewidth, Pset_mfc, Pset_mew, Pset_mec): par = self.host.twinx() par.axis["right"].set_visible(False) offset = (set_offset, 0) new_axisline = par.get_grid_helper().new_fixed_axis par.axis["side"] = new_axisline(loc=side, axes=par, offset=offset) par.axis["side"].label.set_visible(True) par.axis["side"].set_label(PYlabel) p2, = par.plot(self.X, PY,color=Plinecolor, marker=Pset_marker, ls=Pset_linestyle, ms=Pset_markersize, lw=Pset_linewidth, mfc=Pset_mfc, mew=Pset_mew, mec=Pset_mec) par.axis["side"].label.set_color(p2.get_color()) par.tick_params(axis='y', colors=p2.get_color())
def test3(): import numpy as np from matplotlib.transforms import Transform from matplotlib.path import Path class MyTransform(Transform): input_dims = 2 output_dims = 2 is_separable = False def __init__(self, resolution): """ Create a new Aitoff transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved Aitoff space. """ Transform.__init__(self) self._resolution = resolution def transform(self, ll): x = ll[:, 0:1] y = ll[:, 1:2] return np.concatenate((x, y - x), 1) transform.__doc__ = Transform.transform.__doc__ transform_non_affine = transform transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def transform_path(self, path): vertices = path.vertices ipath = path.interpolated(self._resolution) return Path(self.transform(ipath.vertices), ipath.codes) transform_path.__doc__ = Transform.transform_path.__doc__ transform_path_non_affine = transform_path transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__ def inverted(self): return MyTransformInv(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ class MyTransformInv(Transform): input_dims = 2 output_dims = 2 is_separable = False def __init__(self, resolution): Transform.__init__(self) self._resolution = resolution def transform(self, ll): x = ll[:, 0:1] y = ll[:, 1:2] return np.concatenate((x, y + x), 1) transform.__doc__ = Transform.transform.__doc__ def inverted(self): return MyTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ import matplotlib.pyplot as plt fig = plt.figure(1) fig.clf() tr = MyTransform(1) grid_helper = GridHelperCurveLinear(tr) from mpl_toolkits.axes_grid1.parasite_axes import host_subplot_class_factory from .axislines import Axes SubplotHost = host_subplot_class_factory(Axes) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) fig.add_subplot(ax1) ax2 = ParasiteAxesAuxTrans(ax1, tr, "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) plt.draw()
def multiplot(metaAry, size=(10, 7.5), dpi=75, grid=True, \ legend=0, fontsize=15, real_label=None, imag_label=None, \ fig=None, host=None, par=None): """ metaArray function to do a simple 1D plot of complex array as real and imaginary parts. legend: 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 """ if legend is None: legend = 0 if real_label is None: real_label = "Real" if imag_label is None: imag_label = "Imaginary" axis = metaAry['range'] rdata = metaAry.data.real idata = metaAry.data.imag # Load the plotting ranges and units x0 = axis['begin'][0] x1 = axis['end'][0] ry0 = min(rdata) ry1 = max(rdata) iy0 = min(idata) iy1 = max(idata) xunit = axis['unit'][0] ryunit = metaAry['unit'] iyunit = metaAry['unit'] # Leave 10% margin in the y axis rmean = np.average((ry0, ry1)) rreach = np.abs(ry0 - ry1) / 2 / 0.9 ry0 = np.sign(ry0 - rmean) * rreach + rmean ry1 = np.sign(ry1 - rmean) * rreach + rmean imean = np.average((iy0, iy1)) ireach = np.abs(iy0 - iy1) / 2 / 0.9 iy0 = np.sign(iy0 - imean) * ireach + imean iy1 = np.sign(iy1 - imean) * ireach + imean # Apply unit prefix if unit is defined xunit, x0, x1, xscale = prettyunit(xunit, x0, x1) ryunit, ry0, ry1, ryscale = prettyunit(ryunit, ry0, ry1) iyunit, iy0, iy1, iyscale = prettyunit(iyunit, iy0, iy1) if ryscale != 1: rdata = rdata.copy() * ryscale if iyscale != 1: idata = idata.copy() * iyscale xlabl = lbl_repr(axis['label'][0], xunit) rylabl = lbl_repr(metaAry['label'], ryunit, real_label + ' part') iylabl = lbl_repr(metaAry['label'], iyunit, imag_label + ' part') title = metaAry['name'] fig = figure(figsize=size, dpi=dpi) host = SubplotHost(fig, 111) fig.add_subplot(host) par = host.twinx() #if axis['log'][0] == False: # x = linspace(x0, x1, len(metaAry)) #else: # raise NotImplemented, "Log axis is not yet implemented." x = metaAry.get_axis() host.plot(x, rdata, 'b-', label=lbl_repr(axis['label'][0], '', real_label)) par.plot(x, idata, 'r--', label=lbl_repr(axis['label'][0], '', real_label)) host.grid(grid) host.set_xlabel(xlabl, fontsize=fontsize) host.set_ylabel(rylabl, fontsize=fontsize) par.set_ylabel(iylabl, fontsize=fontsize) host.set_xlim([x0, x1]) host.set_ylim([ry0, ry1]) par.set_ylim([iy0, iy1]) if fontsize is not None: host.set_title(title, fontsize=int(fontsize * 1.3)) else: host.set_title(title) if legend >= 0: host.legend(loc=legend) return fig, host, par
def curvelinear_test3(fig): """ polar projection, but in a rectangular box. """ global ax1, axis import numpy as np from . import angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost # 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, 1, 1, grid_helper=grid_helper) for axis in list(six.itervalues(ax1.axis)): axis.set_visible(False) fig.add_subplot(ax1) grid_helper = ax1.get_grid_helper() 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 grid_helper = ax1.get_grid_helper() 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 # # 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)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
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)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
## list: species (y-axis) ## list: number of individuals > 3 (x-axis) ## list: number of pictures > 3 (x-axis) ## value: mean number of pictures genus (horizontal line) ## value: mean number of pictures species (excluding sp.) (horizontal line) ## code runs in pythontex ## read the data from pkl file with open('/home/stine/repositories/MSCCode/dictinventory.pkl', 'rb') as di: dictgenusspecies, dictspeciesspnr, dictspnrpath = pickle.load(di) ## initialize figure1 and two with given sizes ## initialize four axes objects, with right y-axis invisible fig1 = plt.figure(figsize=(10, 4)) ax1 = SubplotHost(fig1, 121) ax1.axis["right"].set_visible(False) ax2 = SubplotHost(fig1, 122) ax2.axis["right"].set_visible(False) fig2 = plt.figure(figsize=(10, 10)) ax3 = SubplotHost(fig2, 121) ax3.axis["right"].set_visible(False) ax4 = SubplotHost(fig2, 122) ax4.axis["right"].set_visible(False) ## add axes objects to figures fig1.add_subplot(ax1) fig1.add_subplot(ax2)
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)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
def curvelinear_test2(fig): """ polar projection, but in a rectangular box. """ global ax1 import numpy as np import mpl_toolkits.axes_grid.angle_helper as angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost from mpl_toolkits.axes_grid.grid_helper_curvelinear import GridHelperCurveLinear # 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) 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) fig.add_subplot(ax1) # Now creates floating axis #grid_helper = ax1.get_grid_helper() # floating axis whose first coordinate (theta) is fixed at 60 ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60) axis.label.set_text(r"$\theta = 60^{\circ}$") axis.label.set_visible(True) # floating axis whose second coordinate (r) is fixed at 6 ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6) axis.label.set_text(r"$r = 6$") ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
def test_custom_transform(): class MyTransform(Transform): input_dims = 2 output_dims = 2 is_separable = False 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 = ll[:, 0:1] y = ll[:, 1:2] return np.concatenate((x, y - x), 1) transform_non_affine = transform def transform_path(self, path): vertices = path.vertices 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 = 2 output_dims = 2 is_separable = False def __init__(self, resolution): Transform.__init__(self) self._resolution = resolution def transform(self, ll): x = ll[:, 0:1] y = ll[:, 1:2] return np.concatenate((x, y+x), 1) 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 = ParasiteAxesAuxTrans(ax1, tr, "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 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 draw_heart_temp(): fig = plt.figure(1) host = SubplotHost(fig, 111) par1 = host.twinx() par1.axis["right"].set_visible(True) #offset = 60, 0 fig.add_axes(host) plt.subplots_adjust(right=0.75) host.set_xlabel("Time") host.set_ylabel("HeartRate [bpm]") par1.set_ylabel("Temperature [℃]") host.set_xlim(time_s[0], time_s[len(time_s) - 1]) host.set_ylim(0, 100) par1.set_ylim(0, 35) p1, = host.plot(time_h, heart, label="HeartRate") p2, = par1.plot(time_t, temp, color="r", label="Temperature") host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) days = mdates.AutoDateLocator() daysFmt = mdates.DateFormatter("%H:%M") host.xaxis.set_major_locator(days) host.xaxis.set_major_formatter(daysFmt) par1.xaxis.set_major_locator(days) par1.xaxis.set_major_formatter(daysFmt) plt.show()
f"m1 Pearson Length Conf Low: {percentage} %"])[4] ], [list(new_data[f"m1 Pearson Length: {percentage} %"])[4]]) ]] + [[ x - y for x, y in zip([ list(new_data[ f"m1 Pearson Length Conf High: {percentage} %"])[2] ], [list(new_data[f"m1 Pearson Length: {percentage} %"])[2]]) ] + [ x - y for x, y in zip([ list(new_data[ f"m1 Pearson Length Conf High: {percentage} %"])[4] ], [list(new_data[f"m1 Pearson Length: {percentage} %"])[4]]) ]]) fig = plt.figure(figsize=(5, 5)) ax = SubplotHost(fig, 111) fig.add_subplot(ax) ax.axhline(0.0, color="grey", ls="--") ax.errorbar([1, 2], ydata, yerr=0, fmt="none", capsize=20, color="black") ax.errorbar([1, 2], ydata, yerr=yerr, fmt="none", capsize=10, color="black")
def plotcomplexpolar(metaAry, size = (10, 7.5), dpi = 75, grid = True, legend = 0, fontsize = 15): """ metaArray function to do a simple 1D plot of complex array as magnitude and phase angle. legend: 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 """ if legend is None: legend = 0 axis = metaAry['range'] mag = abs(metaAry.data) pha = angle(metaAry.data, deg=True) # Load the plotting ranges and units x0 = axis['begin'][0] x1 = axis['end'][0] my0 = min(mag) my1 = max(mag) py0 = min(pha) py1 = max(pha) xunit = axis['unit'][0] myunit = metaAry['unit'] pyunit = 'Degree' # Leave 10% margin in the y axis mmean = average((my0, my1)) mreach = abs(my0-my1) / 2 / 0.9 my0 = sign(my0-mmean) * mreach + mmean my1 = sign(my1-mmean) * mreach + mmean pmean = average((py0, py1)) preach = abs(py0-py1) / 2 / 0.9 py0 = sign(py0-pmean) * preach + pmean py1 = sign(py1-pmean) * preach + pmean # Apply unit prefix if unit is defined xunit, x0, x1, xscale = prettyunit(xunit, x0, x1) myunit, my0, my1, myscale = prettyunit(myunit, my0, my1) pyunit, py0, py1, pyscale = prettyunit(pyunit, py0, py1) if myscale != 1: mag = mag * myscale if pyscale != 1: pha = pha.copy() * pyscale xlabl = lbl_repr(axis['label'][0], xunit) mylabl = lbl_repr(metaAry['label'], myunit, "Magnitude") pylabl = lbl_repr(metaAry['label'], pyunit, "Phase angle") title = metaAry['name'] fig = figure(figsize=size, dpi = dpi) host = SubplotHost(fig, 111) fig.add_subplot(host) par = host.twinx() if axis['log'][0] is False: x = linspace(x0, x1, len(metaAry)) else: raise NotImplemented, "Log axis is not yet implemented." host.plot(x, mag, 'b-', label=lbl_repr(axis['label'][0], '', "Magnitude")) par.plot(x, pha, 'r--', label=lbl_repr(axis['label'][0], '', "Phase")) host.grid(grid) host.set_xlabel(xlabl, fontsize=fontsize) host.set_ylabel(mylabl, fontsize=fontsize) par.set_ylabel(pylabl, fontsize=fontsize) host.set_xlim([x0, x1]) host.set_ylim([my0, my1]) par.set_ylim([py0, py1]) if fontsize is not None: host.set_title(title, fontsize=int(fontsize*1.3)) else: host.set_title(title) if legend >= 0: host.legend(loc=legend) return fig, host, par
def plotcomplex(metaAry, size = (10, 7.5), dpi = 75, grid = True, legend = 0, fontsize = 15): """ metaArray function to do a simple 1D plot of complex array as real and imaginary parts. legend: 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 """ if legend is None: legend = 0 axis = metaAry['range'] rdata = metaAry.data.real idata = metaAry.data.imag # Load the plotting ranges and units x0 = axis['begin'][0] x1 = axis['end'][0] ry0 = min(rdata) ry1 = max(rdata) iy0 = min(idata) iy1 = max(idata) xunit = axis['unit'][0] ryunit = metaAry['unit'] iyunit = metaAry['unit'] # Leave 10% margin in the y axis rmean = average((ry0, ry1)) rreach = abs(ry0-ry1) / 2 / 0.9 ry0 = sign(ry0-rmean) * rreach + rmean ry1 = sign(ry1-rmean) * rreach + rmean imean = average((iy0, iy1)) ireach = abs(iy0-iy1) / 2 / 0.9 iy0 = sign(iy0-imean) * ireach + imean iy1 = sign(iy1-imean) * ireach + imean # Apply unit prefix if unit is defined xunit, x0, x1, xscale = prettyunit(xunit, x0, x1) ryunit, ry0, ry1, ryscale = prettyunit(ryunit, ry0, ry1) iyunit, iy0, iy1, iyscale = prettyunit(iyunit, iy0, iy1) if ryscale != 1: rdata = rdata.copy() * ryscale if iyscale != 1: idata = idata.copy() * iyscale xlabl = lbl_repr(axis['label'][0], xunit) rylabl = lbl_repr(metaAry['label'], ryunit, "Real part") iylabl = lbl_repr(metaAry['label'], iyunit, "Imaginary part") title = metaAry['name'] fig = figure(figsize=size, dpi = dpi) host = SubplotHost(fig, 111) fig.add_subplot(host) par = host.twinx() if axis['log'][0] is False: x = linspace(x0, x1, len(metaAry)) else: raise NotImplemented, "Log axis is not yet implemented." host.plot(x, rdata, 'b-', label=lbl_repr(axis['label'][0], '', "Real")) par.plot(x, idata, 'r--', label=lbl_repr(axis['label'][0], '', "Imaginary")) host.grid(grid) host.set_xlabel(xlabl, fontsize=fontsize) host.set_ylabel(rylabl, fontsize=fontsize) par.set_ylabel(iylabl, fontsize=fontsize) host.set_xlim([x0, x1]) host.set_ylim([ry0, ry1]) par.set_ylim([iy0, iy1]) if fontsize is not None: host.set_title(title, fontsize=int(fontsize*1.3)) else: host.set_title(title) if legend >= 0: host.legend(loc=legend) return fig, host, par
from scipy.constants import physical_constants kB=physical_constants['Boltzmann constant in eV/K'][0] import numpy as np arange=np.arange exp=np.exp tt=arange(18.,501.) vv=exp(-0.02/(kB*tt)) import matplotlib.pylab as plt from mpl_toolkits.axes_grid.parasite_axes import SubplotHost fig=plt.figure(1) ax1=SubplotHost(fig, 111) fig.add_subplot(ax1) ax1.plot(1./tt,vv) ax1.set_yscale('log') ax1.set_xlabel('Reciprocal temperature (1/K)') ax2=ax1.twin() # ax2 is responsible for "top" axis and "right" axis tticks=np.array([20.,30.,50.,100.,300.]) ax2.set_xticks( [ 1/t for t in tticks ] ) ax2.set_xticklabels(tticks) ax2.axis["top"].label.set_visible(True) ax2.set_xlabel('Temperature (K)') ax2.set_yticks([]) plt.show()
def curvelinear_test3(fig): """ polar projection, but in a rectangular box. """ global ax1, axis import numpy as np from . import angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost # 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, 1, 1, grid_helper=grid_helper) for axis in list(six.itervalues(ax1.axis)): axis.set_visible(False) fig.add_subplot(ax1) grid_helper = ax1.get_grid_helper() 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 grid_helper = ax1.get_grid_helper() 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 # # 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)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost import matplotlib.pyplot as plt fig = plt.figure(1) host = SubplotHost(fig, 111) fig.add_subplot(host) par = host.twinx() host.set_xlabel("Distance") host.set_ylabel("Density") par.set_ylabel("Temperature") p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density") p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature") host.axis["left"].label.set_color(p1.get_color()) par.axis["right"].label.set_color(p2.get_color()) host.legend() plt.show()
def curvelinear_test2(fig): """ polar projection, but in a rectangular box. """ global ax1 import numpy as np import mpl_toolkits.axes_grid.angle_helper as angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost from mpl_toolkits.axes_grid.grid_helper_curvelinear import GridHelperCurveLinear # 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) 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) fig.add_subplot(ax1) # Now creates floating axis #grid_helper = ax1.get_grid_helper() # floating axis whose first coordinate (theta) is fixed at 60 ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60) axis.label.set_text(r"$\theta = 60^{\circ}$") axis.label.set_visible(True) # floating axis whose second coordinate (r) is fixed at 6 ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6) axis.label.set_text(r"$r = 6$") ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
cooutf, cutoff=[50, 100, 150], binsize=[0.1, 0.5, 1.0], lmin=-10.5, lmax=90.5) cobinpt1 = readcol(prefix + 'cofillfact_v1.0.2_binsize0.10.txt', asStruct=True) cobinpt5 = readcol(prefix + 'cofillfact_v1.0.2_binsize0.50.txt', asStruct=True) cobin1 = readcol(prefix + 'cofillfact_v1.0.2_binsize1.00.txt', asStruct=True) fig = figure(1) clf() from mpl_toolkits.axes_grid.parasite_axes import SubplotHost host = SubplotHost(fig, 111) rcParams['xtick.labelsize'] = 24 rcParams['ytick.labelsize'] = 24 rcParams['font.size'] = 24 import scipy.stats as stats sig3 = 1 - stats.halfnorm.cdf(3) host.plot(bin1.longitude_bin100, bin1.fraction_over_300 - sig3, 'k', drawstyle='steps-mid') host.set_xlim(-10.5, 90.5) host.set_ylim(0, 0.35) host.set_xlabel("Galactic Longitude", fontsize='24') host.set_ylabel("Fraction above 3$\sigma$ ", fontsize='24') ax2 = host.twinx() ax2.plot(cobin1.longitude_bin100,
def draw_sleep_humid(): fig = plt.figure(1) host = SubplotHost(fig, 111) par1 = host.twinx() par1.axis["right"].set_visible(True) #offset = 60, 0 fig.add_axes(host) plt.subplots_adjust(right=0.75) host.set_xlabel("Time") host.set_ylabel("State") par1.set_ylabel("Humidity [%]") host.set_xlim(time_s[0], time_s[len(time_s) - 1]) host.yaxis.set_major_locator(MultipleLocator(1)) par1.set_ylim(0, 90) p1, = host.plot(time_s, state, label="State") p2, = par1.plot(time_t, humid, color="r", label="Humidity") host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) days = mdates.AutoDateLocator() daysFmt = mdates.DateFormatter("%H:%M") host.xaxis.set_major_locator(days) host.xaxis.set_major_formatter(daysFmt) par1.xaxis.set_major_locator(days) par1.xaxis.set_major_formatter(daysFmt) plt.show()
def curvelinear_test3(fig): """ polar projection, but in a rectangular box. """ global ax1, axis import numpy as np import angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost 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) 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.itervalues(): axis.set_visible(False) fig.add_subplot(ax1) grid_helper = ax1.get_grid_helper() 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 grid_helper = ax1.get_grid_helper() 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(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
import matplotlib.transforms as mtransforms import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.parasite_axes import SubplotHost obs = [["01_S1", 3.88, 0.14, 1970, 63], ["01_S4", 5.6, 0.82, 1622, 150], ["02_S1", 2.4, 0.54, 1570, 40], ["03_S1", 4.1, 0.62, 2380, 170]] fig = plt.figure() ax_kms = SubplotHost(fig, 1, 1, 1, aspect=1.) # angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc pm_to_kms = 1. / 206265. * 2300 * 3.085e18 / 3.15e7 / 1.e5 aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.) ax_pm = ax_kms.twin(aux_trans) ax_pm.set_viewlim_mode("transform") fig.add_subplot(ax_kms) for n, ds, dse, w, we in obs: time = ((2007 + (10. + 4 / 30.) / 12) - 1988.5) v = ds / time * pm_to_kms ve = dse / time * pm_to_kms ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k") ax_kms.axis["bottom"].set_label("Linear velocity at 2.3 kpc [km/s]") ax_kms.axis["left"].set_label("FWHM [km/s]") ax_pm.axis["top"].set_label("Proper Motion [$^{''}$/yr]") ax_pm.axis["top"].label.set_visible(True) ax_pm.axis["right"].major_ticklabels.set_visible(False)
class MatplotlibTimelines(GeneralPlotTimelines): """This class opens a matplotlib window and plots a timelines-collection in it""" figureNr=1 def __init__(self, timelines, custom, showWindow=True, registry=None): """@param timelines: The timelines object @type timelines: TimeLineCollection @param custom: A CustomplotInfo-object. Values in this object usually override the other options """ self.hasSubplotHost=True try: global plt,matplotlib,firstTimeImport,SubplotHost import matplotlib if not showWindow and firstTimeImport: # matplotlib.use("MacOSX") matplotlib.use("agg") firstTimeImport=False import matplotlib.pyplot as plt try: from mpl_toolkits.axes_grid.parasite_axes import SubplotHost except ImportError: self.hasSubplotHost=False warning("Matplotlib-Version does not support SubplotHost") except ImportError: error("Matplotlib not installed.") GeneralPlotTimelines.__init__(self,timelines,custom,showWindow=showWindow,registry=registry) self.figNr=MatplotlibTimelines.figureNr MatplotlibTimelines.figureNr+=1 self.figure=None self.title="" self.xlabel="" self.ylabel="" self.ylabel2="" try: if self.spec.xlabel: self.setXLabel(self.spec.xlabel) except AttributeError: pass try: if self.spec.ylabel: self.setYLabel(self.spec.ylabel) except AttributeError: pass try: if self.spec.y2label: self.setYLabel2(self.spec.y2label) except AttributeError: pass self.axis1=None self.axis2=None self.setTitle(self.spec.theTitle) self.with_=self.spec.with_ if not self.with_ in ['lines','points','dots','steps','linespoints']: warning("'with'-style",self.with_,"not implemented, using 'lines'") self.with_='lines' self.redo() def buildData(self,times,name,title,lastValid): """Build the implementation specific data @param times: The vector of times for which data exists @param name: the name under which the data is stored in the timeline @param title: the title under which this will be displayed""" a=self.axis1 if name in self.alternate: a=self.axis2 data=self.data.getValues(name) tm=times if len(tm)>0 and not lastValid: tm=tm[:-1] data=data[:-1] plotIt=True try: if self.spec.logscale and min(data)<=0: plotIt=False except AttributeError: pass if self.spec.start!=None or self.spec.end!=None: start=self.spec.start end=self.spec.end if start==None: start=tm[0] if end==None: end=tm[-1] self.axis1.set_xbound(lower=start,upper=end) self.axis1.set_autoscalex_on(False) if self.axis2: self.axis2.set_xbound(lower=start,upper=end) self.axis2.set_autoscalex_on(False) drawstyle='default' marker='' linestyle='-' if self.with_=='lines': pass elif self.with_=='steps': drawstyle='steps' elif self.with_=='points': linestyle='' marker='*' elif self.with_=='dots': linestyle='' marker='.' elif self.with_=='linespoints': marker='*' else: warning("'with'-style",self.with_,"not implemented, using 'lines'") if plotIt: a.plot(tm, data, label=title, drawstyle=drawstyle, marker=marker, linestyle=linestyle) def preparePlot(self): """Prepare the plotting window""" plt.hot() self.figure=plt.figure(self.figNr) self.figure.clear() # this is black magic that makes the legend work with two axes if self.hasSubplotHost: self.axis1=SubplotHost(self.figure,111) self.figure.add_subplot(self.axis1) else: self.axis1=self.figure.add_subplot(111) self.axis1.set_xlabel(self.xlabel) self.axis1.set_ylabel(self.ylabel) if len(self.alternate)>0: self.axis2=self.axis1.twinx() self.axis2.set_ylabel(self.ylabel2) try: if self.spec.logscale: self.axis1.set_yscale("log") if self.axis2: self.axis2.set_yscale("log") except AttributeError: pass def doReplot(self): """Replot the whole data""" if self.hasSubplotHost: l=self.axis1.legend(fancybox=True) else: l=plt.legend(fancybox=True) # l.get_frame().set_fill(False) if l: l.get_frame().set_alpha(0.7) l.get_texts()[0].set_size(10) plt.suptitle(self.title) plt.grid(True) plt.draw() # plt.show() def actualSetTitle(self,title): """Sets the title""" self.title=title def setXLabel(self,title): """Sets the label on the X-Axis""" self.xlabel=title def setYLabel(self,title): """Sets the label on the first Y-Axis""" self.ylabel=title def setYLabel2(self,title): """Sets the label on the second Y-Axis""" self.ylabel2=title def doHardcopy(self,filename,form): """Write the contents of the plot to disk @param filename: Name of the file without type extension @param form: String describing the format""" self.figure.savefig(filename+"."+form,format=form)
import matplotlib.transforms as mtransforms import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.parasite_axes import SubplotHost obs = [["01_S1", 3.88, 0.14, 1970, 63], ["01_S4", 5.6, 0.82, 1622, 150], ["02_S1", 2.4, 0.54, 1570, 40], ["03_S1", 4.1, 0.62, 2380, 170]] fig = plt.figure() ax_kms = SubplotHost(fig, 1,1,1, aspect=1.) # angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5 aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.) ax_pm = ax_kms.twin(aux_trans) ax_pm.set_viewlim_mode("transform") fig.add_subplot(ax_kms) for n, ds, dse, w, we in obs: time = ((2007+(10. + 4/30.)/12)-1988.5) v = ds / time * pm_to_kms ve = dse / time * pm_to_kms ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k") ax_kms.axis["bottom"].set_label("Linear velocity at 2.3 kpc [km/s]")
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.parasite_axes import SubplotHost import numpy as np fig = plt.figure(1, (4,3)) ax = SubplotHost(fig, 111) fig.add_subplot(ax) xx = np.arange(0, 2*np.pi, 0.01) ax.plot(xx, np.sin(xx)) ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi]) ax2.set_xticklabels(["0", r"$\frac{1}{2}\pi$", r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"]) ax2.axis["right"].major_ticklabels.set_visible(False) plt.draw() plt.show()
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.parasite_axes import SubplotHost import numpy as np fig = plt.figure(1, (4, 3)) ax = SubplotHost(fig, 111) fig.add_subplot(ax) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis ax2.set_xticks([0., .5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi]) ax2.set_xticklabels( ["0", r"$\frac{1}{2}\pi$", r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"]) ax2.axis["right"].major_ticklabels.set_visible(False) plt.draw() plt.show()
16724, 20660 ] kill_ret = [ 1, 0, 1, 0, 0, 2, 2, 3, 2, 0, 3, 1, 0, 1, 0, 3, 0, 2, 3, 7, 0, 1, 6, 1, 4, 2, 2, 1, 0, 0, 1, 4, 2, 0 ] dead_ret = [ 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 2, 0, 2, 0, 0, 1, 0, 0, 1, 2, 0, 0, 2, 0, 1, 2, 2, 0, 0, 2, 1 ] _len = len(dam_player_ret) _range = range(0, _len) fig = matplotlib.pyplot.figure(1) host = SubplotHost(fig, 111) par1 = host.twinx() par2 = host.twinx() par1.axis["right"].set_visible(True) offset = 60, 0 new_axisline = par2.get_grid_helper().new_fixed_axis par2.axis["right2"] = new_axisline(loc="right", axes=par2, offset=offset) par2.axis["right2"].label.set_visible(True) par2.axis["right2"].set_label("dead") fig.add_axes(host) matplotlib.pyplot.subplots_adjust(right=0.75) host.set_xlim(0, _len) host.set_ylim(0, 40000)
class MatplotlibTimelines(GeneralPlotTimelines): """This class opens a matplotlib window and plots a timelines-collection in it""" figureNr = 1 def __init__(self, timelines, custom, showWindow=True, quiet=False, registry=None): """:param timelines: The timelines object :type timelines: TimeLineCollection :param custom: A CustomplotInfo-object. Values in this object usually override the other options """ self.hasSubplotHost = True try: global plt, matplotlib, firstTimeImport, SubplotHost import matplotlib if not showWindow and firstTimeImport: # matplotlib.use("MacOSX") matplotlib.use("agg") firstTimeImport = False import matplotlib.pyplot as plt try: from mpl_toolkits.axes_grid.parasite_axes import SubplotHost except ImportError: self.hasSubplotHost = False warning("Matplotlib-Version does not support SubplotHost") except ImportError: error("Matplotlib not installed.") GeneralPlotTimelines.__init__(self, timelines, custom, showWindow=showWindow, registry=registry) self.figNr = MatplotlibTimelines.figureNr MatplotlibTimelines.figureNr += 1 self.figure = None self.title = "" self.xlabel = "" self.ylabel = "" self.ylabel2 = "" try: if self.spec.xlabel: self.setXLabel(self.spec.xlabel) except AttributeError: pass try: if self.spec.ylabel: self.setYLabel(self.spec.ylabel) except AttributeError: pass try: if self.spec.y2label: self.setYLabel2(self.spec.y2label) except AttributeError: pass self.axis1 = None self.axis2 = None self.setTitle(self.spec.theTitle) self.with_ = self.spec.with_ if not self.with_ in [ 'lines', 'points', 'dots', 'steps', 'linespoints' ]: warning("'with'-style", self.with_, "not implemented, using 'lines'") self.with_ = 'lines' self.redo() def buildData(self, times, name, title, lastValid): """Build the implementation specific data :param times: The vector of times for which data exists :param name: the name under which the data is stored in the timeline :param title: the title under which this will be displayed""" a = self.axis1 if self.testAlternate(name): a = self.axis2 data = self.data.getValues(name) tm = times if len(tm) > 0 and not lastValid: tm = tm[:-1] data = data[:-1] plotIt = True try: if self.spec.logscale and min(data) <= 0: plotIt = False except AttributeError: pass if self.spec.start != None or self.spec.end != None: start = self.spec.start end = self.spec.end if start == None: start = tm[0] if end == None: end = tm[-1] self.axis1.set_xbound(lower=start, upper=end) self.axis1.set_autoscalex_on(False) if self.axis2: self.axis2.set_xbound(lower=start, upper=end) self.axis2.set_autoscalex_on(False) drawstyle = 'default' marker = '' linestyle = '-' if self.with_ == 'lines': pass elif self.with_ == 'steps': drawstyle = 'steps' elif self.with_ == 'points': linestyle = '' marker = '*' elif self.with_ == 'dots': linestyle = '' marker = '.' elif self.with_ == 'linespoints': marker = '*' else: warning("'with'-style", self.with_, "not implemented, using 'lines'") if plotIt: a.plot(tm, data, label=title, drawstyle=drawstyle, marker=marker, linestyle=linestyle) def preparePlot(self): """Prepare the plotting window""" plt.hot() self.figure = plt.figure(self.figNr) self.figure.clear() # this is black magic that makes the legend work with two axes if self.hasSubplotHost: self.axis1 = SubplotHost(self.figure, 111) self.figure.add_subplot(self.axis1) else: self.axis1 = self.figure.add_subplot(111) self.axis1.set_xlabel(self.xlabel) self.axis1.set_ylabel(self.ylabel) if len(self.alternate) > 0: self.axis2 = self.axis1.twinx() self.axis2.set_ylabel(self.ylabel2) try: if self.spec.logscale: self.axis1.set_yscale("log") if self.axis2: self.axis2.set_yscale("log") except AttributeError: pass def doReplot(self): """Replot the whole data""" if self.hasSubplotHost: l = self.axis1.legend(fancybox=True) else: l = plt.legend(fancybox=True) # l.get_frame().set_fill(False) if l: l.get_frame().set_alpha(0.7) l.get_texts()[0].set_size(10) plt.suptitle(self.title) plt.grid(True) plt.draw() # plt.show() def actualSetTitle(self, title): """Sets the title""" self.title = title def setXLabel(self, title): """Sets the label on the X-Axis""" self.xlabel = title def setYLabel(self, title): """Sets the label on the first Y-Axis""" self.ylabel = title def setYLabel2(self, title): """Sets the label on the second Y-Axis""" self.ylabel2 = title def doHardcopy(self, filename, form, termOpts=None): """Write the contents of the plot to disk :param filename: Name of the file without type extension :param form: String describing the format""" self.figure.savefig(filename + "." + form, format=form)
def draw_sleep_discomfort(): for i in range(0, len(time_t)): tmp_t = float(temp[i]) tmp_h = float(humid[i]) value = 0.81 * tmp_t + 0.01 * tmp_h * (0.99 * tmp_t - 14.3) + 46.3 discomfort.append(value) fig = plt.figure(1) host = SubplotHost(fig, 111) par1 = host.twinx() par1.axis["right"].set_visible(True) #offset = 60, 0 fig.add_axes(host) plt.subplots_adjust(right=0.75) host.set_xlabel("Time") host.set_ylabel("State") par1.set_ylabel("Discomfort Index") host.set_xlim(time_s[0], time_s[len(time_s) - 1]) host.yaxis.set_major_locator(MultipleLocator(1)) par1.set_ylim(0, 100) p1, = host.plot(time_s, state, label="State") p2, = par1.plot(time_t, discomfort, color="r", label="Discomfort Index") host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) days = mdates.AutoDateLocator() daysFmt = mdates.DateFormatter("%H:%M") host.xaxis.set_major_locator(days) host.xaxis.set_major_formatter(daysFmt) par1.xaxis.set_major_locator(days) par1.xaxis.set_major_formatter(daysFmt) plt.show() print(discomfort)