def register_gps_scale(scale_class): """Register a new GPS scale. ``scale_class`` must be a subclass of `GPSScale`. """ register_scale(scale_class) GPS_SCALES[scale_class.name] = scale_class
def PlotSetScale(): mscale.register_scale(RRYScale) pyplot.grid(b=True,which='major',axis='y') pyplot.grid(b=True,which='both',axis='x') pyplot.gca().set_yscale('rry') pyplot.gca().set_xscale('log') pyplot.gca().invert_yaxis()
def addPluginMethod(descriptor): """ Adds a transform method to the list of available methods. :@type descriptor: tuple :@param descriptor: Each tuple contains the following information in order: - ID (str) - ID (int) - name (string) - description (string) - transform method - scale class (if applicable) """ global methods descriptor = list(descriptor) descriptor.append(True) methods[descriptor[0]] = tuple(descriptor) # custom scales are available, see: # http://matplotlib.sourceforge.net/examples/api/custom_scale_example.html if descriptor[-2] is not None: mscale.register_scale(descriptor[-2])
super(GPSScale, self).__init__(unit=unit, epoch=epoch) self._transform = self.GPSTransform(unit=self.unit, epoch=self.epoch) def get_transform(self): return self._transform def set_default_locators_and_formatters(self, axis): axis.set_major_locator(GPSAutoLocator(unit=self.unit, epoch=self.epoch)) axis.set_major_formatter(GPSFormatter(unit=self.unit, epoch=self.epoch)) axis.set_minor_locator(GPSAutoMinorLocator(epoch=self.epoch)) axis.set_minor_formatter(ticker.NullFormatter()) register_scale(GPSScale) class AutoGPSScale(GPSScale): """Automagic GPS scaling based on visible data """ name = 'auto-gps' register_scale(AutoGPSScale) # register all the astropy time units that have sensible long names def gps_scale_factory(unit): class FixedGPSScale(GPSScale): name = str('%ss' % unit.long_names[0])
def limit_range_for_scale(self, vmin, vmax, minpos): return max(0., vmin), vmax class SquareTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True def transform_non_affine(self, a): return np.array(a)**2 def inverted(self): return SquareScale.InvertedSquareTransform() class InvertedSquareTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True def transform(self, a): return np.array(a)**.5 def inverted(self): return SquareScale.SquareTransform() def get_transform(self): return self.SquareTransform() mscale.register_scale(SquareRootScale) mscale.register_scale(SquareScale)
return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): if vmax < vmin: vmin, vmax = vmax, vmin tmin = math.copysign(math.sqrt(abs(vmin)), vmin) tmax = math.copysign(math.sqrt(abs(vmax)), vmax) delta = (tmax - tmin) / self._nbins locs = numpy.arange(tmin, tmax, self._base.ge(delta)) if self._symmetric and numpy.sign(tmin) != numpy.sign(tmax): locs -= locs[numpy.argmin(numpy.abs(locs))] locs = numpy.sign(locs) * locs**2 return self.raise_if_exceeds(locs) def view_limits(self, dmin, dmax): """ Set the view limits to the nearest multiples of base that contain the data """ vmin = self._base.le(math.copysign(math.sqrt(abs(dmin)), dmin)) vmax = self._base.ge(math.sqrt(dmax)) if vmin == vmax: vmin -= 1 vmax += 1 return mtransforms.nonsingular(math.copysign(vmin**2, vmin), vmax**2) # register new scale to matplotlib mscale.register_scale(SqrtAllowNegScale)
"""Format major and minor ticks with a single `Formatter`. This is just a swap between the `MinorLogFormatterMathtext` and the GWpyLogFormatterMathtext` depending on whether the tick in question is a decade (0.1, 1, 10, 100, ...) or not. This is useful for things like colorbars, which use a single formatter for all ticks. """ def __call__(self, x, pos=None): if is_decade(x, self._base): # pylint: disable=bad-super-call return super(MinorLogFormatterMathtext, self).__call__(x, pos=pos) return super(CombinedLogFormatterMathtext, self).__call__(x, pos=pos) class GWpyLogScale(LogScale): """GWpy version of the matplotlib `LogScale`. This scale overrides the default to use the new GWpy formatters for major and minor ticks. """ def set_default_locators_and_formatters(self, axis): axis.set_major_locator(LogLocator(self.base)) axis.set_major_formatter(GWpyLogFormatterMathtext(self.base)) axis.set_minor_locator(LogLocator(self.base, self.subs)) axis.set_minor_formatter(MinorLogFormatterMathtext(self.base)) register_scale(GWpyLogScale)
# These are used by the transformation framework to do some # error checking and prevent incompatible transformations from # being connected together. When defining transforms for a # scale, which are, by definition, separable and have only one # dimension, these members should always be set to 1. input_dims = 1 output_dims = 1 is_separable = True def __init__(self, power): mtransforms.Transform.__init__(self) self.power = power def transform_non_affine(self, a): """ This transform takes an Nx1 ``numpy`` array and returns a transformed copy. """ return a**self.power def inverted(self): """ Override this method so matplotlib knows how to get the inverse transform for this transform. """ return PowerScale.PowerTransform(1./self.power) # Now that the Scale class has been defined, it must be registered so # that ``matplotlib`` can find it. mscale.register_scale(PowerScale)
def plot(self): # general plot settings mscale.register_scale(SquareRootScale) sns.set_style("white") sns.set_style("ticks") # figure generation fig, ax = plt.subplots(figsize=self.size) ax.set_xscale('log', basex=10) ax.set_yscale('squareroot') ### figure variables ### # data if self.dat: self.data.plot(ax=ax, drawstyle='steps-post', color='black', lw=3) self.calc[0].plot(ax=ax, color='black', lw=3) self.calc[-1].plot(ax=ax, color='grey', lw=3, style='--') for series in sch_hist.calc[1:-1]: series.plot(ax=ax, color='black', lw=1) # x-axis xmax = int(np.log10( self.mxtime)) # magic again, 'last before' base 10 log xmin = int(np.log10(self.mntime)) # magic again, first base 10 log if self.xrange: ax.set_xlim(self.xrange) else: ax.set_xlim([10**xmin, 10**(xmax + 1)]) # y-axis ymax = int(self.meven** 0.5) # magic need 'last before' power function argument if ymax % 2 == 1: ymax += 1 if self.yrange: ax.set_ylim(self.yrange) else: ax.set_ylim([0, (ymax + 2)**2]) ys = [(x * 2)**2 for x in range(0, int(ymax / 2 + 2)) ] # magick scale if +2 so w need /2 and +2 for additional entry yms = [x**2 for x in np.arange(0, ymax + 2, 0.5) ] # magick scale is not divided so only +2 for additional entry if self.yrange: ys = [y for y in ys if y < self.yrange[1]] yms = [ym for ym in yms if ym < self.yrange[1]] last = ys[-1] if len( ys) % 2 == 1 else 0 # too many ys? reduce, but preserve last lastm = yms[-1] if len(yms) % 2 == 1 else 0 if len(ys) > 10: ys = ys[0:-1:4] yms = yms[0:-1:4] if len(ys) > 5: ys = ys[0:-1:2] yms = yms[0:-1:2] if last != 0: ys.append(last) if lastm != 0: yms.append(lastm) ax.set_yticks(ys) ax.set_yticks(yms, minor=True) if self.ticks: plt.locator_params(axis='x', numticks=self.ticks) ax.tick_params(labelsize=self.fontsize[0]) # overwrite labels and legend ax.set_xlabel('apparent open time [ms] (log scale)', fontsize=self.fontsize[1]) ax.set_ylabel('frequency density (square root scale)', fontsize=self.fontsize[1]) if self.legend: ax.legend([ 'observed', 'fit', 'missed event correction', 'components fits' ], loc='best', fontsize=self.fontsize[1]) else: ax.legend_.remove() sns.despine() plt.tight_layout() plt.show() fig.savefig(self.fname.split('.')[0] + ".png")
class InvertedTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True def __init__(self, nines): mtransforms.Transform.__init__(self) self.nines = nines def transform_non_affine(self, a): return 1. - 10**(-a) def inverted(self): return CloseToOne.Transform(self.nines) mscale.register_scale(CloseToOne) matplotlib.rcParams['ps.fonttype'] = 42 matplotlib.rcParams['pdf.fonttype'] = 42 nodeKind = ['-', '--', '-.', '^:', 'X-', 'V--', '>-.', '<:'] def parse (f): infile = open (f, "r") started = False data = [] for line in infile.readlines (): if not started: if line.strip().startswith("Value"): started = True else:
def __init__(self, a, b, n, name, pa=0.1, pb=0.9, lognormal=False, Plot=True): mscale.register_scale(ProbitScale) if Plot: fig = plt.figure(facecolor="white") ax1 = fig.add_subplot(121, axisbelow=True) ax2 = fig.add_subplot(122, axisbelow=True) ax1.set_xlabel(name) ax1.set_ylabel("ECDF and Best Fit CDF") prop = matplotlib.font_manager.FontProperties(size=8) if lognormal: sigma = (log(b) - log(a)) / ((erfinv(2 * pb - 1) - erfinv(2 * pa - 1)) * (2 ** 0.5)) mu = log(a) - erfinv(2 * pa - 1) * sigma * (2 ** 0.5) cdf = arange(0.001, 1.000, 0.001) ppf = map(lambda v: lognorm.ppf(v, sigma, scale=exp(mu)), cdf) x = lognorm.rvs(sigma, scale=exp(mu), size=n) x.sort() print "generating lognormal %s, p50 %0.3f, size %s" % (name, exp(mu), n) x_s, ecdf_x = ecdf(x) best_fit = lognorm.cdf(x, sigma, scale=exp(mu)) if Plot: ax1.set_xscale("log") ax2.set_xscale("log") hist_y = lognorm.pdf(x_s, std(log(x)), scale=exp(mu)) else: sigma = (b - a) / ((erfinv(2 * pb - 1) - erfinv(2 * pa - 1)) * (2 ** 0.5)) mu = a - erfinv(2 * pa - 1) * sigma * (2 ** 0.5) cdf = arange(0.001, 1.000, 0.001) ppf = map(lambda v: norm.ppf(v, mu, scale=sigma), cdf) print "generating normal %s, p50 %0.3f, size %s" % (name, mu, n) x = norm.rvs(mu, scale=sigma, size=n) x.sort() x_s, ecdf_x = ecdf(x) best_fit = norm.cdf((x - mean(x)) / std(x)) hist_y = norm.pdf(x_s, loc=mean(x), scale=std(x)) pass if Plot: ax1.plot(ppf, cdf, "r-", linewidth=2) ax1.set_yscale("probit") ax1.plot(x_s, ecdf_x, "o") ax1.plot(x, best_fit, "r--", linewidth=2) n, bins, patches = ax2.hist(x, normed=1, facecolor="green", alpha=0.75) bincenters = 0.5 * (bins[1:] + bins[:-1]) ax2.plot(x_s, hist_y, "r--", linewidth=2) ax2.set_xlabel(name) ax2.set_ylabel("Histogram and Best Fit PDF") ax1.grid(b=True, which="both", color="black", linestyle="-", linewidth=1) # ax1.grid(b=True, which='major', color='black', linestyle='--') ax2.grid(True) return
self.cofactor = cofactor # To use the symmetricalLog style formatters, we need these properties self.base = base self.linthresh = linthresh self.linscale = linscale def transform_non_affine(self, a): return np.arcsinh(self.cofactor * a) def inverted(self): return ArcsinhScale.InvertedArcsinhTransform(self.cofactor) class InvertedArcsinhTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True def __init__(self, cofactor): mtransforms.Transform.__init__(self) self.cofactor = cofactor def transform_non_affine(self, a): return np.sinh(a / self.cofactor) def inverted(self): return ArcsinhScale.ArcsinhTransform(self.cofactor) mscale.register_scale(ArcsinhScale)
for x, y in major_tick_pairs ] minor_ticks = [item for sublist in minor_ticks_lol for item in sublist] return (minor_ticks) def view_limits(self, data_min, data_max): 'Try to choose the view limits intelligently' if data_max < data_min: data_min, data_max = data_max, data_min # get the nearest tenth-decade that contains the data if data_max > 0: logs = np.ceil(np.log10(data_max)) vmax = np.ceil(data_max / (10**(logs - 1))) * (10**(logs - 1)) else: vmax = 100 if data_min >= 0: vmin = 0 else: logs = np.ceil(np.log10(-1.0 * data_min)) vmin = np.floor(data_min / (10**(logs - 1))) * (10**(logs - 1)) return mtransforms.nonsingular(vmin, vmax) mscale.register_scale(LogicleScale)
input_dims = 1 output_dims = 1 is_separable = True def __init__(self, nines): mtransforms.Transform.__init__(self) self.nines = nines def transform_non_affine(self, a): return 1. - 10**(-a) def inverted(self): return TailLog.Transform(self.nines) mscale.register_scale(TailLog) def __get_error_factor(k, confidence): return t.ppf(confidence / 2 + 0.5, k - 1) / sqrt(k - 1) def __compute_sample_mean_and_error(bucket_list, confidence): means, mins, maxs = [], [], [] z_cache = {} for i, bucket in enumerate(bucket_list): # get the error factor from the student's t distribution # and cache the result to minimize the number of ppf lookups k = len(bucket) z = z_cache.setdefault(k, __get_error_factor(k, confidence))
def register(): mscale.register_scale(ResponseScale)
self.cofactor = cofactor # To use the symmetricalLog style formatters, we need these properties self.base = base self.linthresh = linthresh self.linscale = linscale def transform_non_affine(self, a): return np.arcsinh(self.cofactor*a) def inverted(self): return ArcsinhScale.InvertedArcsinhTransform(self.cofactor) class InvertedArcsinhTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True def __init__(self, cofactor): mtransforms.Transform.__init__(self) self.cofactor = cofactor def transform_non_affine(self, a): return np.sinh(a / self.cofactor) def inverted(self): return ArcsinhScale.ArcsinhTransform(self.cofactor) mscale.register_scale(ArcsinhScale)
class CombinedLogFormatterMathtext(MinorLogFormatterMathtext): """Format major and minor ticks with a single `Formatter`. This is just a swap between the `MinorLogFormatterMathtext` and the GWpyLogFormatterMathtext` depending on whether the tick in question is a decade (0.1, 1, 10, 100, ...) or not. """ def __call__(self, x, pos=None): if is_decade(x, self._base): return super(MinorLogFormatterMathtext, self).__call__(x, pos=pos) else: return super(CombinedLogFormatterMathtext, self).__call__(x, pos=pos) class GWpyLogScale(LogScale): """GWpy version of the matplotlib `LogScale`. This scale overrides the default to use the new GWpy formatters for major and minor ticks. """ def set_default_locators_and_formatters(self, axis): if isinstance(axis, XAxis): axis.set_tick_params(which='both', pad=7) axis.labelpad = 8 axis.set_major_locator(LogLocator(self.base)) axis.set_major_formatter(GWpyLogFormatterMathtext(self.base)) axis.set_minor_locator(LogLocator(self.base, self.subs)) axis.set_minor_formatter(MinorLogFormatterMathtext(self.base)) register_scale(GWpyLogScale)
input_dims = 1 output_dims = 1 is_separable = True has_inverse = True def __init__(self): mtransforms.Transform.__init__(self) def transform_non_affine(self,a): return unit_convert.mel2hz(a) def inverted(self): return MelScale.MelTransform() mscale.register_scale(MelScale) def example(): """Example import numpy as np import matplotlib.pyplot as plt x = np.arange(100,2000,100) y = x fig,ax = plt.subplots(1,1) ax.plot(x,y) ax.set_yscale('mel') ax.set_xlabel('Frequency(hz)') ax.set_ylabel('Mel scale(Hz)') ax.grid(True) savefig.savefig(fig,fig_name='mel_scale',fig_dir='./images')
def limit_range_for_scale(self, vmin, vmax, minpos): return vmin, vmax class BandTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True has_inverse = False def __init__(self): mtransforms.Transform.__init__(self) def transform_non_affine(self, a): return np.log10(a+1) mscale.register_scale(OctaveBandScale) class ThirdBandScale(mscale.ScaleBase): """ Third-octave band scale. """ name = 'third' def __init__(self, axis, **kwargs): mscale.ScaleBase.__init__(self) def get_transform(self): return self.BandTransform() def set_default_locators_and_formatters(self, axis):
return vmin, vmax class BandTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True has_inverse = False def __init__(self): mtransforms.Transform.__init__(self) def transform_non_affine(self, a): return np.log10(a + 1) mscale.register_scale(OctaveBandScale) class ThirdBandScale(mscale.ScaleBase): """ Third-octave band scale. """ name = 'third' def __init__(self, axis, **kwargs): mscale.ScaleBase.__init__(self) def get_transform(self): return self.BandTransform() def set_default_locators_and_formatters(self, axis):
def transform(self, a): return sqrt(a) def inverted(self): return SquaredScale.SquaredTransform() def get_transform(self): """Set the actual transform for the axis coordinates. """ return self.SquaredTransform() mscale.register_scale(SquaredScale) ################################################### # # Definition of data fitting models # ################################################### def guinier(q,param): """Function that returns a Guinier model The parameter set list should contain i0, Rg, and background in that
has_inverse = True def __init__(self): Transform.__init__(self) def transform_non_affine(self, a): return np.sqrt(np.abs(a)) * np.sign(a) def inverted(self): return QuadTransform() class QuadTransform(Transform): input_dims = 1 output_dims = 1 is_separable = True has_inverse = True def __init__(self): Transform.__init__(self) def transform_non_affine(self, a): return a**2 * np.sign(a) def inverted(self): return SqrtTransform() register_scale(SqrtScale)
from matplotlib.scale import register_scale from .misc import * from .probscale import ProbScale from . import figutils from wqio.testing import NoseWrapper test = NoseWrapper().test register_scale(ProbScale)
else: return np.log10((a - self.zero) * self.sign) / np.log10 (self.base) def inverted(self): """ Override this method so matplotlib knows how to get the inverse transform for this transform. """ return ShiftLogScale.InvertedShiftLogTransform(self.base, self.sign, self.zero) class InvertedShiftLogTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True def __init__(self, base, sign, zero): mtransforms.Transform.__init__(self) self.base = base self.sign = sign self.zero = zero def transform_non_affine(self, a): return np.power(self.base, a) * self.sign + self.zero def inverted(self): return ShiftLogScale.ShiftLogTransform(self.base, self.sign, self.zero) # Now that the Scale class has been defined, it must be registered so # that ``matplotlib`` can find it. mscale.register_scale(ShiftLogScale)
has_inverse = True def __init__(self): Transform.__init__(self) def transform_non_affine(self, a): return np.sqrt(np.abs(a))*np.sign(a) def inverted(self): return QuadTransform() class QuadTransform(Transform): input_dims = 1 output_dims = 1 is_separable = True has_inverse = True def __init__(self): Transform.__init__(self) def transform_non_affine(self, a): return a**2*np.sign(a) def inverted(self): return SqrtTransform() register_scale(SqrtScale)
self.L = L self.k = k self.x0 = x0 self.upper_bound = upper_bound def transform_non_affine(self, a): return self.L / (1 + np.exp(-self.k * (a - self.x0))) def inverted(self): return ProbabilityScale.ProbabilityTransform( self.lower_bound, self.upper_bound, self.L, self.k, self.x0) # Now that the Scale class has been defined, it must be registered so # that ``matplotlib`` can find it. mscale.register_scale(ProbabilityScale) # if __name__ == '__main__': # import matplotlib.pyplot as plt # x = np.linspace(.1, 100, 1000) # points = np.array([.2,.5,1,2,5,10,20,30,40,50,60,70,80,90,95,98]) # plt.plot(x, x) # plt.gca().set_xscale('probability', points = points, vmin = .01) # plt.grid(True) # plt.show() import numpy as np from matplotlib import scale as mscale from matplotlib import transforms as mtransforms
"""Package for fast and efficient plotting of scientific data on a world map.""" __author__ = "Eric Jansen" __email__ = "*****@*****.**" from matplotlib.scale import register_scale from matplotlib.projections import register_projection from .scale import MercatorScale from .axes import MercatorAxes from .marker import pin register_projection(MercatorAxes) register_scale(MercatorScale)
def graph_performance(graph_type='histogram', tickers=[], start='2012-01-01', end='2020-01-01', performance_test_period=24, data_type='price', early_stop=False, min_recommendations=21, convert_type='simple', verbose=False): if early_stop and graph_type == 'histogram': raise ValueError( 'Can only suppot graph type histogram when early stop is false') if graph_type != '1d' and graph_type != 'histogram' and graph_type != '2d' and graph_type != 'cdf': raise ValueError('Invalid graph_type') convert_keys = get_convert_type_keys(convert_type=convert_type) if isinstance(min_recommendations, dict): if convert_type == 'normal' and len(min_recommendations) != 5: raise ValueError( 'Normal recommendation convertion has 5 types need min recommendation dictionary to have 5 integer values' ) if convert_type == 'reduced' and len(min_recommendations) != 5: raise ValueError( 'Reduced recommendation convertion has 5 types need min recommendation dictionary to have 5 integer values' ) if convert_type == 'simple' and len(min_recommendations) != 3: raise ValueError( 'Simple recommendation convertion has 3 types need min recommendation dictionary to have 3 integer values' ) if set(min_recommendations.keys()) != set(convert_keys): raise ValueError('Invalid value for some min_recommendation key') if (not isinstance(performance_test_period, int)) or performance_test_period <= 0: raise ValueError('Invalid performance_test_period') df_firm_perf, df_time_total = get_recommendations_performance( tickers=tickers, start=start, end=end, performance_test_period=performance_test_period, early_stop=early_stop, data_type=data_type, convert_type=convert_type, verbose=verbose) df_new_firm_perf = df_firm_perf.copy() if graph_type == 'histogram': plt.style.use('seaborn-deep') for firm_name, firm_perf in df_firm_perf.iterrows(): #count number of recommendations found = False if isinstance(min_recommendations, dict): for rec in min_recommendations: if not isinstance(firm_perf[rec], np.ndarray): if min_recommendations[rec] > 0: df_new_firm_perf.drop([firm_name], inplace=True) found = True break elif len(firm_perf[rec]) < min_recommendations[rec]: df_new_firm_perf.drop([firm_name], inplace=True) found = True break if isinstance(min_recommendations, int): total_recommendations = 0 for rec in convert_keys: if isinstance(firm_perf[rec], np.ndarray): total_recommendations = total_recommendations + len( firm_perf[rec]) if total_recommendations < min_recommendations: df_new_firm_perf.drop([firm_name], inplace=True) found = True if found: continue if graph_type == '2d': plt.figure(figsize=(10, 6)) plt.title(firm_name) colors = {} if len(convert_keys) == 5: colors = { 'Strong Sell': 'darkred', 'Sell': 'red', 'Hold': 'gold', 'Buy': 'lightgreen', 'Strong Buy': 'green' } if len(convert_keys) == 3: colors = {'Sell': 'red', 'Hold': 'gold', 'Buy': 'green'} inc = 0 patches = [] for rec in convert_keys: if isinstance(firm_perf[rec], np.ndarray): price_sum_log_values = np.array([0.0]) time_sum_values = np.array([0.0]) #array of performances based on recommendation perf_array = firm_perf[rec] time_array = df_time_total.at[firm_name, rec] #get total time in seconds time_of_investments = np.sum(df_time_total.at[firm_name, rec]) derivative_array = np.array([]) for perf, time in zip(perf_array, time_array): if time == 0.0: derivative_array = np.append(derivative_array, 0.1) else: derivative_array = np.append( derivative_array, perf / time) zipped = zip(perf_array, time_array, derivative_array) res = sorted(zipped, key=lambda x: x[2], reverse=True) last_value = 1 for perf, time, der in res: price_sum_log_values = np.append( price_sum_log_values, price_sum_log_values[-1] + np.log(perf + 1)) time_sum_values = np.append( time_sum_values, time_sum_values[-1] + time / time_of_investments) if last_value >= 0.0 and np.log(perf + 1) < 0.0: plt.axvline(x=time_sum_values[-2], color=colors[rec], linestyle='--', linewidth=.5) last_value = np.log(perf + 1) seconds_in_year = 31622400.0 price_geo_avg_log_values = price_sum_log_values * seconds_in_year / time_of_investments price_geo_avg_values = np.exp(price_geo_avg_log_values) #price_geo_avg_values = price_geo_avg_values-1.0 #plot data patch = mpatches.Patch(color=colors[rec], label=rec) patches.append(patch) plt.plot(time_sum_values, price_geo_avg_values, color=colors[rec]) # Draw a horizontal line inc = inc + 1 plt.yscale('log') plt.gca().yaxis.set_minor_formatter( matplotlib.ticker.ScalarFormatter()) plt.legend(handles=patches) plt.show() elif graph_type == 'cdf': plt.figure(figsize=(10, 6)) plt.title(firm_name) mscale.register_scale(CustomScale) colors = {} if len(convert_keys) == 5: colors = { 'Strong Sell': 'darkred', 'Sell': 'red', 'Hold': 'gold', 'Buy': 'lightgreen', 'Strong Buy': 'green' } if len(convert_keys) == 3: colors = {'Sell': 'red', 'Hold': 'gold', 'Buy': 'green'} inc = 0 patches = [] min_x = 1.0 max_x = -1.0 for rec in convert_keys: if isinstance(firm_perf[rec], np.ndarray): cdf_values = np.array([]) time_sum_values = np.array([]) #array of performances based on recommendation perf_array = firm_perf[rec] time_array = df_time_total.at[firm_name, rec] #get total time in seconds time_of_investments = np.sum(df_time_total.at[firm_name, rec]) derivative_array = np.array([]) seconds_in_year = 31622400.0 for perf, time in zip(perf_array, time_array): if time == 0.0: derivative_array = np.append(derivative_array, 1.0) else: derivative_array = np.append( derivative_array, np.exp( np.log(perf + 1) * time / seconds_in_year) - 1) zipped = zip(time_array, derivative_array) res = sorted(zipped, key=lambda x: x[1]) for time, der in res: if der < min_x: min_x = der if der > max_x: max_x = der if len(cdf_values) == 0: cdf_values = np.append(cdf_values, der) time_sum_values = np.append(time_sum_values, 0) cdf_values = np.append(cdf_values, der) time_sum_values = np.append( time_sum_values, time / time_of_investments) else: cdf_values = np.append(cdf_values, der) time_sum_values = np.append( time_sum_values, time_sum_values[-1]) cdf_values = np.append(cdf_values, der) time_sum_values = np.append( time_sum_values, time_sum_values[-1] + time / time_of_investments) #price_geo_avg_values = price_geo_avg_values-1.0 #plot data patch = mpatches.Patch(color=colors[rec], label=rec) patches.append(patch) plt.plot(cdf_values, time_sum_values, color=colors[rec]) # Draw a horizontal line inc = inc + 1 plt.ylabel("Fraction of the Total Time of All Investments") plt.xlabel("Annualize Rate of Return") plt.gca().set_xscale('custom') axes = plt.gca() axes.set_xlim([min_x, max_x]) axes.set_ylim([0.0, 1.0]) plt.minorticks_on() plt.grid(True) plt.legend(handles=patches) plt.show() elif graph_type == '1d': plt.figure() plt.title(firm_name) colors = {} if len(convert_keys) == 5: colors = { 'Strong Sell': 'darkred', 'Sell': 'red', 'Hold': 'gold', 'Buy': 'lightgreen', 'Strong Buy': 'green' } if len(convert_keys) == 3: colors = {'Sell': 'red', 'Hold': 'gold', 'Buy': 'green'} inc = 0 patches = [] for rec in convert_keys: if isinstance(firm_perf[rec], np.ndarray): #array of performances based on recommendation perf_array = firm_perf[rec] #calculate average rate of return needs arr = np.array([]) #get yearly rate of return for perf in perf_array: ret = np.power(perf + 1.0, 12.0 / performance_test_period) - 1.0 arr = np.append(arr, ret) patch = mpatches.Patch(color=colors[rec], label=rec) patches.append(patch) plt.vlines(arr, 0, 5 - inc, colors=colors[rec]) # Draw a horizontal line inc = inc + 1 plt.legend(handles=patches) plt.xlim(-1, 2) frame1 = plt.gca() frame1.axes.get_yaxis().set_visible(False) plt.show() elif graph_type == 'histogram': color_dict = {} plots = None fig = None if len(convert_keys) == 5: color_dict = { 'Strong Sell': '#8b0000', 'Sell': '#ff0000', 'Hold': '#daa520', 'Buy': '#90ee2c', 'Strong Buy': '#00ff00' } fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(1, 5, figsize=(25, 7)) plots = (ax1, ax2, ax3, ax4, ax5) elif len(convert_keys) == 3: color_dict = { 'Sell': '#ff0000', 'Hold': '#daa520', 'Buy': '#00ff00' } fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(25, 7)) plots = (ax1, ax2, ax3) inc = 0 patches = [] rec_values = [] weights = [] fig.suptitle(firm_name) inc = 0 for rec in convert_keys: if isinstance(firm_perf[rec], np.ndarray): #array of performances based on recommendation perf_array = firm_perf[rec] patch = mpatches.Patch(color=color_dict[rec], label=rec) patches.append(patch) #calculate average rate of return needs x = np.array([]) #get yearly rate of return for perf in perf_array: ret = np.power(perf + 1.0, 12.0 / performance_test_period) - 1.0 x = np.append(x, ret) #get weight x_w = np.empty(x.shape) x_w.fill(1 / x.shape[0]) #get mean me = np.mean(x) #set sub plot title plots[inc].set(xlabel=rec + " Avg: " + str(me)) #graph histogram plots[inc].hist(x, 60, weights=x_w, color=color_dict[rec]) inc = inc + 1 #plt.legend(handles=patches) plt.show()
def __init__(self, nines): mtransforms.Transform.__init__(self) self.nines = nines def transform_non_affine(self, a): masked = ma.masked_where(a > 1-10**(-1-self.nines), a) if masked.mask.any(): return -ma.log10(1-a) else: return -np.log10(1-a) def inverted(self): return CloseToOne.InvertedTransform(self.nines) class InvertedTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True def __init__(self, nines): mtransforms.Transform.__init__(self) self.nines = nines def transform_non_affine(self, a): return 1. - 10**(-a) def inverted(self): return CloseToOne.Transform(self.nines) mscale.register_scale(CloseToOne)
self.base = base self.subs = subs def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to specialized versions for log scaling. """ axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter()) def get_transform(self): """ Return a :class:`~matplotlib.transforms.Transform` instance appropriate for the given logarithm base. """ return self._transform def limit_range_for_scale(self, vmin, vmax, minpos): """ Limit the domain to positive values. """ return (vmin <= -1.0 and minpos or vmin, vmax <= -1.0 and minpos or vmax) register_scale(Log1pScale)
is_separable = True has_inverse = True def __init__(self,thresh,exp): mtransforms.Transform.__init__(self) self.thresh = thresh self.exp = exp def transform_non_affine(self, a): return np.power(a,self.exp) def inverted(self): return SqrtScale.SqrtTransform(self.thresh,self.exp) if __name__ == "__main__": # Now that the Scale class has been defined, it must be registered so # that ``matplotlib`` can find it. mscale.register_scale(SqrtScale) import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,100,100) plt.plot(x, 2*x, '-', lw=2) plt.gca().set_xscale('sqrt') plt.gca().grid(True) plt.show()
def __init__(self, zval, zfrac): mtransforms.Transform.__init__(self) self.zval = zval self.zfrac = zfrac def transform_non_affine(self, a): #return np.arctan(np.sinh(a)) #return 0.5*(np.array(a)-1000.) return np.interp(a, self.zfrac, -self.zval) def inverted(self): return VerticalSplitScale.VerticalSplitScaleTransform(self.zval, self.zfrac) # Now that the Scale class has been defined, it must be registered so # that ``matplotlib`` can find it. mscale.register_scale(VerticalSplitScale) if __name__ == '__main__': import matplotlib.pyplot as plt z = np.linspace(-6500., 0., 43) s = -1. * z plt.plot(s, z, '.-', lw=2) plt.axhline(-1000.) plt.gca().set_yscale('splitscale', zval=[0.,-1000.,-9000.]) plt.xlabel('Depth') plt.ylabel('Z') plt.grid(True)
is_separable = True def __init__(self, thresh): mtransforms.Transform.__init__(self) self.thresh = thresh def transform_non_affine(self, a): return 10**(a*1.5) def inverted(self): return ExpScale.InvertedCustomTransform(self.thresh) class InvertedCustomTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = True def __init__(self, thresh): mtransforms.Transform.__init__(self) self.thresh = thresh def transform_non_affine(self, a): return log10(a) def inverted(self): return ExpScale.CustomTransform(self.thresh) mscale.register_scale(ExpScale)
import numpy from matplotlib import pyplot from matplotlib import scale from scipy import stats from .probscale import ProbScale, _minimal_norm scale.register_scale(ProbScale) def _check_ax_obj(ax): """ Checks if a value if an Axes. If None, a new one is created. """ if ax is None: fig, ax = pyplot.subplots() elif isinstance(ax, pyplot.Axes): fig = ax.figure else: msg = "`ax` must be a matplotlib Axes instance or None" raise ValueError(msg) return fig, ax def _check_fit_arg(arg, argname): valid_args = ['x', 'y', 'both', None] if arg not in valid_args: msg = 'Invalid value for {} ({}). Must be on of {}.' raise ValueError(msg.format(argname, arg, valid_args))
return vmax, vmin else: return vmin, vmax class BoundedScale(mscale.LinearScale): """ Linear scale with set bounds that can't be exceeded. Gives a "stretchy" panning effect. """ name = 'bounded' def __init__(self, axis, vmin=None, vmax=None): self.vmin = vmin self.vmax = vmax mscale.LinearScale.__init__(self, axis) def limit_range_for_scale(self, vmin, vmax, minpos): inverted = vmin > vmax if inverted: vmax, vmin = vmin, vmax vmin = max(vmin, self.vmin) vmax = min(vmax, self.vmax) if inverted: return vmax, vmin else: return vmin, vmax mscale.register_scale(PiecewiseLinearScale) mscale.register_scale(BoundedScale)
def finalize(): '''Finalize the module by registering its components import matplotlib''' mscale.register_scale(LogitScale)
from matplotlib import scale from .viz import * from .probscale import ProbScale from .tests import test scale.register_scale(ProbScale)
is_separable = True has_inverse = True def transform_non_affine(self, a): lower = a[np.where(a <= factor * np.log10(change))] greater = a[np.where(a > factor * np.log10(change))] if lower.size: if isinstance(lower, ma.MaskedArray): lower = ma.power(10.0, lower / float(factor)) else: lower = np.power(10.0, lower / float(factor)) if greater.size: greater = (greater + change - factor * np.log10(change)) # Only low if not (greater.size): return lower # Only high if not (lower.size): return greater return np.concatenate((lower, greater)) def inverted(self): return PlanckTransform() # Finished. Register the scale! mscale.register_scale(PlanckScale) if __name__ == '__main__': sys.exit(main())
output_dims = 1 is_separable = True has_inverse = True def transform_non_affine(self, a): lower = a[np.where(a<=factor*np.log10(change))] greater = a[np.where(a> factor*np.log10(change))] if lower.size: if isinstance(lower, ma.MaskedArray): lower = ma.power(10.0, lower/float(factor)) else: lower = np.power(10.0, lower/float(factor)) if greater.size: greater = (greater + change - factor*np.log10(change)) # Only low if not(greater.size): return lower # Only high if not(lower.size): return greater return np.concatenate((lower, greater)) def inverted(self): return PlanckTransform() # Finished. Register the scale! mscale.register_scale(PlanckScale) if __name__ == '__main__': sys.exit(main())
is_separable = True has_inverse = True def __init__(self, thresh): mtransforms.Transform.__init__(self) self.thresh = thresh def transform_non_affine(self, a): return np.arctan(np.sinh(a)) def inverted(self): return MercatorLatitudeScale.MercatorLatitudeTransform(self.thresh) # Now that the Scale class has been defined, it must be registered so # that ``matplotlib`` can find it. mscale.register_scale(MercatorLatitudeScale) if __name__ == '__main__': import matplotlib.pyplot as plt t = np.arange(-180.0, 180.0, 0.1) s = np.radians(t)/2. plt.plot(t, s, '-', lw=2) plt.gca().set_yscale('mercator') plt.xlabel('Longitude') plt.ylabel('Latitude') plt.title('Mercator: Projection of the Oppressor') plt.grid(True)
break super(GPSScale, self).__init__(unit=unit, epoch=epoch) self._transform = self.GPSTransform(unit=self.unit, epoch=self.epoch) def get_transform(self): return self._transform def set_default_locators_and_formatters(self, axis): axis.set_major_locator(GPSAutoLocator(unit=self.unit, epoch=self.epoch)) axis.set_major_formatter(GPSFormatter(unit=self.unit, epoch=self.epoch)) axis.set_minor_locator(GPSAutoMinorLocator(epoch=self.epoch)) axis.set_minor_formatter(ticker.NullFormatter()) register_scale(GPSScale) class AutoGPSScale(GPSScale): """Automagic GPS scaling based on visible data """ name = 'auto-gps' register_scale(AutoGPSScale) # register all the astropy time units that have sensible long names def gps_scale_factory(unit): class FixedGPSScale(GPSScale): name = str('%ss' % unit.long_names[0])
def __init__(self, mu, sigma): mtransforms.Transform.__init__(self) self.mu = mu self.sigma = sigma def transform_non_affine(self, a): inverseCumLogLaplaceVectorized = np.vectorize(inversefunc(cumLogLaplaceMaker(self.mu, \ self.sigma), domain=[1e-5, float("Inf")])) return inverseCumLogLaplaceVectorized(a) def inverted(self): return LogLaplaceScale.LogLaplaceTransform(self.mu, self.sigma) """ old debugging code mscale.register_scale(LogLaplaceScale) p.plot(xRange, xRange) ax = p.gca() ax.set_ylim(0.01, 10) ax.set_xlim(0.01, 10) ax.set_yscale("log_laplace", mu=0, sigma=0.04) p.yticks([0.5, 0.9, 0.99, 1.01, 1.1, 2]) p.show()
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright © 2017 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source, # Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantid package # # """ Functionality for unpacking mantid objects for plotting with matplotlib. """ # This file should be left free of PyQt imports to allow quick importing # of the main package. from collections.abc import Iterable # noqa: F401 from matplotlib.projections import register_projection from matplotlib.scale import register_scale from mantid.plots import datafunctions, axesfunctions, axesfunctions3D # noqa: F401 from mantid.plots.legend import LegendProperties # noqa: F401 from mantid.plots.datafunctions import get_normalize_by_bin_width # noqa: F401 from mantid.plots.scales import PowerScale, SquareScale # noqa: F401 from mantid.plots.mantidaxes import MantidAxes, MantidAxes3D, WATERFALL_XOFFSET_DEFAULT, WATERFALL_YOFFSET_DEFAULT # noqa: F401 from mantid.plots.utility import artists_hidden, autoscale_on_update, convert_color_to_hex, legend_set_draggable, MantidAxType # noqa: F401 register_projection(MantidAxes) register_projection(MantidAxes3D) register_scale(PowerScale) register_scale(SquareScale)
def __init__(self, exponent): self.exponent = exponent def __call__(self, x, pos=None): return '%.3g' % x class PowerTransform(Transform): input_dims = 1 output_dims = 1 is_separable = True def __init__(self, exponent): Transform.__init__(self) self.exponent = exponent def transform(self, a): return a ** self.exponent def inverted(self): return PowerTransform(1.0 / self.exponent) register_scale(PowerScale) if __name__ == '__main__': from pylab import * import numpy as np tau = 20 beta = 0.5 x = np.linspace(0,100, num=10) y = np.exp(-(x / tau) ** beta) plot(x, y, 'o ', mfc='none', mew=2) xscale('power', exponent=beta) yscale('log', basey=10) show()
for d in target_dists: f.write("1 {} {}\n".format(func(d, *target_params), func(d, *nontarget_params))) for d in nontarget_dists: f.write("2 {} {}\n".format(func(d, *target_params), func(d, *nontarget_params))) # ============================================================================ if __name__ == '__main__': import matplotlib.pyplot as plt import matplotlib.scale as mscale from tools.ProbitScale import ProbitScale mscale.register_scale(ProbitScale) data_path = sys.argv[1] data = pickle.load(open(data_path, 'rb')) # data = {'0000': data['0000'], '0000_f': data['0000_f']} # ============================================================================ target_dists = genuine_genuine_dists(data, AVG) target_dists = np.concatenate( [target_dists[k].ravel() for k in target_dists.keys()]) nontarget_dists = genuine_forgeries_dists(data, AVG) nontarget_dists = np.concatenate( [nontarget_dists[k].ravel() for k in nontarget_dists.keys()])
self._transform = self.Log1pTransform(base, nonpos) self.base = base self.subs = subs def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to specialized versions for log scaling. """ axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter()) def get_transform(self): """ Return a :class:`~matplotlib.transforms.Transform` instance appropriate for the given logarithm base. """ return self._transform def limit_range_for_scale(self, vmin, vmax, minpos): """ Limit the domain to positive values. """ return (vmin <= -1.0 and minpos or vmin, vmax <= -1.0 and minpos or vmax) register_scale(Log1pScale)