To plot formatter
972973
def toplot(ts,
           filename=None,
           grid=True,
           legend=True,
           pargs=(),
           **kwargs):
    ''''''
    fig = plt.figure()
    ax = fig.add_subplot(111)
    dates = list(ts.dates())
    ax.plot(dates, ts.values(), *pargs)
    ax.grid(grid)

    # rotates and right aligns the x labels, and moves the bottom of the
    # axes up to make room for them
    fig.autofmt_xdate()

    # add legend or title
    names = ts.name.split('__')
    if len(names) == 1:
        title = names[0]
        fontweight = kwargs.get('title_fontweight', 'bold')
        ax.set_title(title, fontweight=fontweight)#,fontsize=fontsize,
    elif legend:
        ##add legend
        loc = kwargs.get('legend_location','best')
        ncol = kwargs.get('legend_ncol', 2)
        ax.legend(names, loc=loc, ncol=ncol)

    return plt
790795
def twoDimensionalScatter(title, title_x, title_y,
                          x, y,
                          lim_x = None, lim_y = None,
                          color = 'b', size = 20, alpha=None):
    
    plt.figure()

    plt.scatter(x, y, c=color, s=size, alpha=alpha, edgecolors='none')
    
    plt.xlabel(title_x)
    plt.ylabel(title_y)
    plt.title(title)
    if type(color) is not str:
        plt.colorbar()

    if lim_x:
        plt.xlim(lim_x[0], lim_x[1])
    if lim_y:
        plt.ylim(lim_y[0], lim_y[1])
26772
function(){

    var a = this.axes,
        options = this.options,
        series = this.series,
        margin = options.grid.labelMargin,
        T = this._text,
        x = a.x,
        x2 = a.x2,
        y = a.y,
        y2 = a.y2,
        maxOutset = options.grid.outlineWidth,
        i, j, l, dim;

    // TODO post refactor, fix this
    _.each(a, function (axis) {
      axis.calculateTicks();
      axis.calculateTextDimensions(T, options);
    });

    // Title height
    dim = T.dimensions(
      options.title,
      {size: options.fontSize*1.5},
      'font-size:1em;font-weight:bold;',
      'flotr-title'
    );
    this.titleHeight = dim.height;

    // Subtitle height
    dim = T.dimensions(
      options.subtitle,
      {size: options.fontSize},
      'font-size:smaller;',
      'flotr-subtitle'
    );
    this.subtitleHeight = dim.height;

    for(j = 0; j < options.length; ++j){
      if (series[j].points.show){
        maxOutset = Math.max(maxOutset, series[j].points.radius + series[j].points.lineWidth/2);
      }
    }

    var p = this.plotOffset;
    if (x.options.margin === false) {
      p.bottom = 0;
      p.top    = 0;
    } else {
      p.bottom += (options.grid.circular ? 0 : (x.used && x.options.showLabels ?  (x.maxLabel.height + margin) : 0)) +
                  (x.used && x.options.title ? (x.titleSize.height + margin) : 0) + maxOutset;

      p.top    += (options.grid.circular ? 0 : (x2.used && x2.options.showLabels ? (x2.maxLabel.height + margin) : 0)) +
                  (x2.used && x2.options.title ? (x2.titleSize.height + margin) : 0) + this.subtitleHeight + this.titleHeight + maxOutset;
    }
    if (y.options.margin === false) {
      p.left  = 0;
      p.right = 0;
    } else {
      p.left   += (options.grid.circular ? 0 : (y.used && y.options.showLabels ?  (y.maxLabel.width + margin) : 0)) +
                  (y.used && y.options.title ? (y.titleSize.width + margin) : 0) + maxOutset;

      p.right  += (options.grid.circular ? 0 : (y2.used && y2.options.showLabels ? (y2.maxLabel.width + margin) : 0)) +
                  (y2.used && y2.options.title ? (y2.titleSize.width + margin) : 0) + maxOutset;
    }

    p.top = Math.floor(p.top); // In order the outline not to be blured

    this.plotWidth  = this.canvasWidth - p.left - p.right;
    this.plotHeight = this.canvasHeight - p.bottom - p.top;

    // TODO post refactor, fix this
    x.length = x2.length = this.plotWidth;
    y.length = y2.length = this.plotHeight;
    y.offset = y2.offset = this.plotHeight;
    x.setScale();
    x2.setScale();
    y.setScale();
    y2.setScale();
  }
124255
def make_plots(self, prefix, mcube_map=None, **kwargs):
        """"""

        #mcube_maps = kwargs.pop('mcube_maps', None)
        if mcube_map is None:
            mcube_map = self.model_counts_map()

        plotter = plotting.AnalysisPlotter(self.config['plotting'],
                                           fileio=self.config['fileio'],
                                           logging=self.config['logging'])
        plotter.run(self, mcube_map, prefix=prefix, **kwargs)
227897
def set_default_locators_and_formatters(self, axis):
        
        axis.set_major_locator(_LogicleLocator(self._transform))
        axis.set_minor_locator(_LogicleLocator(self._transform,
                                               subs=np.arange(2.0, 10.)))
        axis.set_major_formatter(matplotlib.ticker.LogFormatterSciNotation(
            labelOnlyBase=True))
1158808
function formatLinesWith (formatter, str) {
  return str
    .split('\n')
    .map(function (line) {
      return line.length ? formatter(line) : ''
    })
    .join('\n')
}
241520
function plot(options) {
  /* Required Options */
  if (!options.data || !options.filename) {
    throw("The options object must have 'data' and 'filename' properties!");
    return;
  }
  /* Translate data into an object if needs be */
  if (_.isArray(options.data)) {
    /* If it's a one-dimentional array */
    if (_.isEqual(_.flatten(options.data), options.data)) {
      options.data = { 'Series 1': options.data };
    }
  }

  /* Defaults */
  if (!options.style) {
    options.style = 'lines'; /* Default to lines */
  }

  /* Apply moving averages and maximums */
  if (options.moving_avg) {
    options.data = apply_moving_filter(options.data, moving_average, options.moving_avg);
  }
  if (options.moving_max) {
    options.data = apply_moving_filter(options.data, moving_maximum, options.moving_max);
  }

  /* Execute Gnuplot specifing a function to be called when it terminates */
  if (options.format === 'pdf') { /* Special setup for pdf */
    gnuplot = exec('gnuplot | ps2pdf - ' + options.filename,
		   (options.exec ? options.exec : {}),
		   options.finish || post_gnuplot_processing);

  } else { /* Default for everything else */
    gnuplot = exec('gnuplot > ' + options.filename,
		   (options.exec ? options.exec : {}),
		   options.finish || post_gnuplot_processing);
  }

  /* Sets up gnuplot based on the properties we've been given in the
   * options object */
  setup_gnuplot(gnuplot, options);

  /* Get an array containing all the series */
  var series = _.keys(options.data);
  /* Reject series that are functions or come from higher up the protoype chain */
  var i;
  for (i = 0; i < series.length; i += 1) {
    if (!options.data.hasOwnProperty(series[i]) ||
	typeof options.data[series[i]] === 'function') {
      delete series[i]; /* undefine this element */
    }
  }
  /* Filter out any undefined elements */
  series = _.filter(series, function() { return true; });

  /* Print the command to actually do the plot */
  gnuplot.stdin.write('plot');
  for (i = 1; i <= series.length; i += 1) { /* For each series */
    /* Instruct gnuplot to plot this series */
    gnuplot.stdin.write('\'-\' using 1:2 title\'' + series[i - 1] +
			'\' with ' + options.style + ' lt 1 lc ' + i);
    /* If another series is to follow, add a comma */
    if (i < series.length) { gnuplot.stdin.write(','); }
  }
  gnuplot.stdin.write('\n');

  /* Print out the data */
  for (i = 0; i < series.length; i += 1) { /* For each series */
    for (key in options.data[series[i]]) {
      gnuplot.stdin.write(key + ' ' + options.data[series[i]][key] + '\n');
    }
    /* Terminate the data */
    gnuplot.stdin.write('e\n');
  }

  gnuplot.stdin.end();
}
1130878
def plot(self, data, w=800, h=420):
        """"""
        return HTML(
            self.iframe.format(
                source=self.render(
                    data=data, div_id="chart", head=self.head),
                w=w,
                h=h))
771923
def plotGraph(self,mode="plain",nodes=None,filename="tgraph.png"):
        
        if nodes==None:
            nodes=self.nodes
        else:
            nodes=[i for i in self.nodes if i in nodes]
        for node in self.nodes:
            n_=self.A.get_node(node)
            if mode=="plain":
                nmode=1
            else:
                nmode=-1
            pos="{},{}".format(self.xi[::nmode][self.nm.nodes_.index(node)],self.yi[::nmode][self.nm.nodes_.index(node)])
            n_.attr["pos"]=pos
            n_.attr["pin"]=True
            color='#%02x%02x%02x' % tuple([255*i for i in self.cm[int(self.clustering[n_]*255)][:-1]])
            n_.attr['fillcolor']= color
            n_.attr['fixedsize']=True
            n_.attr['width']=  abs(.1*(self.nm.degrees[n_]+  .5))
            n_.attr['height']= abs(.1*(self.nm.degrees[n_]+.5))
            n_.attr["label"]=""
            if node not in nodes:
                n_.attr["style"]="invis"
            else:
                n_.attr["style"]="filled"
        for e in self.edges:
            e.attr['penwidth']=3.4
            e.attr["arrowsize"]=1.5
            e.attr["arrowhead"]="lteeoldiamond"
            e.attr["style"]=""
            if sum([i in nodes for i in (e[0],e[1])])==2:
                e.attr["style"]=""
            else:
                e.attr["style"]="invis"
        tname="{}{}".format(self.basedir,filename)
        print(tname)
        self.A.draw(tname,prog="neato")
1002715
def plotit(self, x, y, fields, colors=[]):
        ''''''
        pylab.ion()
        fig = pylab.figure(num=1, figsize=(12,6))
        ax1 = fig.gca()
        ax2 = None
        xrange = 0.0
        for i in range(0, len(fields)):
            if len(x[i]) == 0: continue
            if self.lowest_x is None or x[i][0] < self.lowest_x:
                self.lowest_x = x[i][0]
            if self.highest_x is None or x[i][-1] > self.highest_x:
                self.highest_x = x[i][-1]
        if self.highest_x is None or self.lowest_x is None:
            return
        xrange = self.highest_x - self.lowest_x
        xrange *= 24 * 60 * 60
        self.formatter = matplotlib.dates.DateFormatter('%H:%M:%S')
        interval = 1
        intervals = [ 1, 2, 5, 10, 15, 30, 60, 120, 240, 300, 600,
                      900, 1800, 3600, 7200, 5*3600, 10*3600, 24*3600 ]
        for interval in intervals:
            if xrange / interval < 15:
                break
        locator = matplotlib.dates.SecondLocator(interval=interval)
        if not self.xaxis:
            ax1.xaxis.set_major_locator(locator)
            ax1.xaxis.set_major_formatter(self.formatter)
        empty = True
        ax1_labels = []
        ax2_labels = []

        for i in range(0, len(fields)):
            if len(x[i]) == 0:
                print("Failed to find any values for field %s" % fields[i])
                continue
            if i < len(colors):
                color = colors[i]
            else:
                color = 'red'
                (tz, tzdst) = time.tzname

            if self.axes[i] == 2:
                if ax2 == None:
                    ax2 = ax1.twinx()
                    ax2.format_coord = self.make_format(ax2, ax1)
                ax = ax2
                if not self.xaxis:
                    ax2.xaxis.set_major_locator(locator)
                    ax2.xaxis.set_major_formatter(self.formatter)
                label = fields[i]
                if label.endswith(":2"):
                    label = label[:-2]
                ax2_labels.append(label)
            else:
                ax1_labels.append(fields[i])
                ax = ax1
            
            if self.xaxis:
                if self.marker is not None:
                    marker = self.marker
                else:
                    marker = '+'
                if self.linestyle is not None:
                    linestyle = self.linestyle
                else:
                    linestyle = 'None'
                ax.plot(x[i], y[i], color=color, label=fields[i],
                        linestyle=linestyle, marker=marker)
            else:
                if self.marker is not None:
                    marker = self.marker
                else:
                    marker = 'None'
                if self.linestyle is not None:
                    linestyle = self.linestyle
                else:
                    linestyle = '-'
                ax.plot_date(x[i], y[i], color=color, label=fields[i],
                             linestyle=linestyle, marker=marker, tz=None)

            empty = False
            if self.flightmode is not None:
                for i in range(len(self.modes)-1):
                    c = colourmap[self.flightmode].get(self.modes[i][1], edge_colour)
                    ax1.axvspan(self.modes[i][0], self.modes[i+1][0], fc=c, ec=edge_colour, alpha=0.1)
                c = colourmap[self.flightmode].get(self.modes[-1][1], edge_colour)
                ax1.axvspan(self.modes[-1][0], ax1.get_xlim()[1], fc=c, ec=edge_colour, alpha=0.1)

            if ax1_labels != []:
                ax1.legend(ax1_labels,loc=self.legend)
            if ax2_labels != []:
                ax2.legend(ax2_labels,loc=self.legend2)
            if empty:
                print("No data to graph")
                return
1212870
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
    """"""
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position(yticks_position)
    ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
                             pad=tick_padding, length=2, width=0.5)
    ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
                             pad=tick_padding, length=2, width=0.5)
    ax.xaxis.labelpad = label_padding
    ax.yaxis.labelpad = label_padding
    ax.xaxis.label.set_size(fontsize)
    ax.yaxis.label.set_size(fontsize)
491108
function () {
			var plotLine = this,
				options = plotLine.options,
				optionsLabel = options.label,
				label = plotLine.label,
				width = options.width,
				to = options.to,
				from = options.from,
				value = options.value,
				toPath, // bands only
				dashStyle = options.dashStyle,
				svgElem = plotLine.svgElem,
				path = [],
				addEvent,
				eventType,
				xs,
				ys,
				x,
				y,
				color = options.color,
				zIndex = options.zIndex,
				events = options.events,
				attribs;

			// logarithmic conversion
			if (isLog) {
				from = log2lin(from);
				to = log2lin(to);
				value = log2lin(value);
			}

			// plot line
			if (width) {
				path = getPlotLinePath(value, width);
				attribs = {
					stroke: color,
					'stroke-width': width
				};
				if (dashStyle) {
					attribs.dashstyle = dashStyle;
				}
			} else if (defined(from) && defined(to)) { // plot band
				// keep within plot area
				from = mathMax(from, min);
				to = mathMin(to, max);

				toPath = getPlotLinePath(to);
				path = getPlotLinePath(from);
				if (path && toPath) {
					path.push(
						toPath[4],
						toPath[5],
						toPath[1],
						toPath[2]
					);
				} else { // outside the axis area
					path = null;
				}
				attribs = {
					fill: color
				};
			} else {
				return;
			}
			// zIndex
			if (defined(zIndex)) {
				attribs.zIndex = zIndex;
			}

			// common for lines and bands
			if (svgElem) {
				if (path) {
					svgElem.animate({
						d: path
					}, null, svgElem.onGetPath);
				} else {
					svgElem.hide();
					svgElem.onGetPath = function () {
						svgElem.show();
					};
				}
			} else if (path && path.length) {
				plotLine.svgElem = svgElem = renderer.path(path)
					.attr(attribs).add();

				// events
				if (events) {
					addEvent = function (eventType) {
						svgElem.on(eventType, function (e) {
							events[eventType].apply(plotLine, [e]);
						});
					};
					for (eventType in events) {
						addEvent(eventType);
					}
				}
			}

			// the plot band/line label
			if (optionsLabel && defined(optionsLabel.text) && path && path.length && plotWidth > 0 && plotHeight > 0) {
				// apply defaults
				optionsLabel = merge({
					align: horiz && toPath && 'center',
					x: horiz ? !toPath && 4 : 10,
					verticalAlign : !horiz && toPath && 'middle',
					y: horiz ? toPath ? 16 : 10 : toPath ? 6 : -4,
					rotation: horiz && !toPath && 90
				}, optionsLabel);

				// add the SVG element
				if (!label) {
					plotLine.label = label = renderer.text(
							optionsLabel.text,
							0,
							0
						)
						.attr({
							align: optionsLabel.textAlign || optionsLabel.align,
							rotation: optionsLabel.rotation,
							zIndex: zIndex
						})
						.css(optionsLabel.style)
						.add();
				}

				// get the bounding box and align the label
				xs = [path[1], path[4], pick(path[6], path[1])];
				ys = [path[2], path[5], pick(path[7], path[2])];
				x = mathMin.apply(math, xs);
				y = mathMin.apply(math, ys);

				label.align(optionsLabel, false, {
					x: x,
					y: y,
					width: mathMax.apply(math, xs) - x,
					height: mathMax.apply(math, ys) - y
				});
				label.show();

			} else if (label) { // move out of sight
				label.hide();
			}

			// chainable
			return plotLine;
		}
201342
def define_format(self, plotStyle, plotSize):

        #Default sizes for computer
        sizing_dict = {}
        sizing_dict['figure.figsize'] = (14, 8)
        sizing_dict['legend.fontsize'] = 15
        sizing_dict['axes.labelsize'] = 20
        sizing_dict['axes.titlesize'] = 24
        sizing_dict['xtick.labelsize'] = 14
        sizing_dict['ytick.labelsize'] = 14
        
        self.colorVector = {
        'iron':'#4c4c4c',
        'silver':'#cccccc',                  
        'dark blue':'#0072B2',
        'green':'#009E73', 
        'orangish':'#D55E00',
        'pink':'#CC79A7',
        'yellow':'#F0E442',
        'cyan':'#56B4E9',
        'olive':'#bcbd22',
        'grey':'#7f7f7f',
        'skin':'#FFB5B8'}

        #sizing_dict['text.usetex'] = True
        
        #--Update the colors/format
        if plotStyle == None:
            self.ColorVector = [None, None, None]
        
        elif plotStyle == 'dark':
            plt.style.use('dark_background')

        elif plotStyle == 'night':
            
            plt.style.use('seaborn-colorblind')
            
            iron_color = '#4c4c4c' #Iron: (76 76 76)
            silver_color = '#cccccc' #Silver: (204 204 204) 
            sizing_dict['axes.facecolor']   = iron_color
            sizing_dict['figure.facecolor'] = iron_color
            sizing_dict['axes.edgecolor']   = silver_color
            sizing_dict['text.color']       = silver_color
            sizing_dict['axes.labelcolor']  = silver_color
            sizing_dict['xtick.color']      = silver_color
            sizing_dict['ytick.color']      = silver_color
            sizing_dict['axes.edgecolor']   = silver_color

            
            #'plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']) + cycler('linestyle', ['-', '--', ':', '-.'])))'
            #This should be the set up for the cycler we just need to add the colors
            #axes.prop_cycle : cycler('color', 'bgrcmyk')

        elif plotStyle == 'colorblind':
            plt.style.use('seaborn-colorblind')

        else:
            plt.style.use(plotStyle)
        
        #--Load particular configuration for this plot
        if plotSize == 'medium':            
            rcParams.update(sizing_dict)
        
        elif type(plotSize) is dict:
            sizing_dict.update(plotSize)
            rcParams.update(sizing_dict)

        '''
        
        '''
 
    
        '''
        Matplotlib default palete
        #17becf dark blue
        #bcbd22 orange
        #2ca02c green
        #e377c2 red
        #8c564b purple
        #9467bd brown
        #d62728 pink
        #7f7f7f grey
        #ff7f0e olive
        #1f77b4 cyan
        '''


  
        '''
        --These are matplotlib styles
        seaborn-darkgrid
        seaborn-notebook
        classic
        seaborn-ticks
        grayscale
        bmh
        seaborn-talk
        dark_background
        ggplot
        fivethirtyeight
        seaborn-colorblind
        seaborn-deep
        seaborn-whitegrid
        seaborn-bright
        seaborn-poster
        seaborn-muted
        seaborn-paper
        seaborn-white
        seaborn-pastel
        seaborn-dark
        seaborn
        seaborn-dark-palette
        '''
1293
def plot_rhat(self, ax, xt_labelsize, titlesize, markersize):
        """"""
        for plotter in self.plotters.values():
            for y, r_hat, color in plotter.r_hat():
                if r_hat is not None:
                    ax.plot(r_hat, y, "o", color=color, markersize=markersize, markeredgecolor="k")
        ax.set_xlim(left=0.9, right=2.1)
        ax.set_xticks([1, 2])
        ax.tick_params(labelsize=xt_labelsize)
        ax.set_title("r_hat", fontsize=titlesize, wrap=True)
        return ax
149670
def guess_formatter(values, precision=1, commas=True, parens=True, nan='nan', prefix=None, pcts=0,
                    trunc_dot_zeros=0):
    
    formatter_args = dict(precision=precision, commas=commas, parens=parens, nan=nan, prefix=prefix,
                          trunc_dot_zeros=trunc_dot_zeros)

    try:
        if isinstance(values, pd.datetime) and values.hour == 0 and values.minute == 0:
            return new_datetime_formatter()
        elif is_datetime_arraylike(values):
            # basic date formatter if no hours or minutes
            if hasattr(values, 'dt'):
                if (values.dt.hour == 0).all() and (values.dt.minute == 0).all():
                    return new_datetime_formatter()
            elif isinstance(values, pd.Series):
                if values.dropna().apply(lambda d: d.hour == 0).all() and values.apply(lambda d: d.minute == 0).all():
                    return new_datetime_formatter()
            elif isinstance(values, pd.DataFrame):
                if values.dropna().applymap(lambda d: d != d or (d.hour == 0 and d.minute == 0)).all().all():
                    return new_datetime_formatter()

        elif isinstance(values, pd.Series):
            aval = values.abs()
            vmax, vmin = aval.max(), aval.min()
        elif isinstance(values, np.ndarray):
            if values.ndim == 2:
                avalues = pd.DataFrame(values).abs()
                vmax = avalues.max().max()
                vmin = avalues.min().min()
            elif values.ndim == 1:
                aval = pd.Series(values).abs()
                vmax, vmin = aval.max(), aval.min()
            else:
                raise ValueError('cannot accept frame with more than 2-dimensions')
        elif isinstance(values, pd.DataFrame):
            avalues = values.abs()
            vmax = avalues.max().max()
            vmin = avalues.min().min()
        elif isinstance(values, (list, tuple)):
            vmax = max(values)
            vmin = min(values)
        else:
            vmax = vmin = abs(values)

        if np.isnan(vmin):
            return new_float_formatter(**formatter_args)
        else:
            min_digits = 0 if vmin == 0 else math.floor(math.log10(vmin))
            # max_digits = math.floor(math.log10(vmax))
            if min_digits >= 12:
                return new_trillions_formatter(**formatter_args)
            elif min_digits >= 9:
                return new_billions_formatter(**formatter_args)
            elif min_digits >= 6:
                return new_millions_formatter(**formatter_args)
            elif min_digits >= 3:
                return new_thousands_formatter(**formatter_args)
            elif pcts and min_digits < 0 and vmax < 1:
                return new_percent_formatter(**formatter_args)
            else:
                if isinstance(vmax, int):
                    formatter_args.pop('precision')
                    return new_int_formatter(**formatter_args)
                else:
                    return new_float_formatter(**formatter_args)
    except:
        # import sys
        # e = sys.exc_info()[0]
        return lambda x: x
23885
def plot(self, f, lfilter=None,**kargs):
        """"""

        return plt.plot([ f(i) for i in self.res if not lfilter or lfilter(i) ], **kargs)
258799
def plotline(plt, alpha, taus, style,label=""):
    
    y = [pow(tt, alpha) for tt in taus]
    plt.loglog(taus, y, style,label=label)