Convert the given data to plotting units.
199535
def to_plot_units(self, data, dtype_vert=False):
        """"""
        if dtype_vert == 'vert_av' or not dtype_vert:
            conv_factor = self.units.plot_units_conv
        elif dtype_vert == ('vert_int'):
            conv_factor = self.units.vert_int_plot_units_conv
        else:
            raise ValueError("dtype_vert value `{0}` not recognized.  Only "
                             "bool(dtype_vert) = False, 'vert_av', and "
                             "'vert_int' supported.".format(dtype_vert))
        if isinstance(data, dict):
            return {key: val*conv_factor for key, val in data.items()}
        return data*conv_factor
442853
def from_inches(value, units):
    
    lookup = {'in': lambda x: x,
              'cm': lambda x: x*2.54,
              'mm': lambda x: x*2.54*10}
    try:
        return lookup[units](value)
    except KeyError:
        raise PlotnineError("Unknown units '{}'".format(units))
802418
def proj_units_to_meters(proj_str):
    """"""
    proj_parts = proj_str.split()
    new_parts = []
    for itm in proj_parts:
        key, val = itm.split('=')
        key = key.strip('+')
        if key in ['a', 'b', 'h']:
            val = float(val)
            if val < 6e6:
                val *= 1000.
                val = '%.3f' % val

        if key == 'units' and val == 'km':
            continue

        new_parts.append('+%s=%s' % (key, val))

    return ' '.join(new_parts)
1335316
def plot_flat(r, c, figsize):
    ""
    return enumerate(plt.subplots(r, c, figsize=figsize)[1].flatten())
287906
def plot(self,init=None):
		""""""

		if not init:
			init=self
			init.plotstats={}
			init.unitfeats=self._getFeatValDict()

			sels=[]
			for k,v in sorted(init.unitfeats.items()):
				for kk,vv in v.items():
					sels.append((k,kk))

			conditions={'x':[],'y':[]}
			targets={'x':[],'y':[]}
			pkey={'x':[],'y':[]}

			print str(0)+"\t[no condition]"
			for selnum in range(len(sels)):
				print str(selnum+1)+"\t"+str(sels[selnum][0])+" = "+str(sels[selnum][1])
			print

			stepnum=0
			for a in sorted(conditions.keys()):
				stepnum+=1
				sel=raw_input(">> [step "+str(stepnum)+"/4] ["+a+" coord] [conditions of population] please type in the number (or numbers separated by commas)\n\tof the conditions determining the total population from which the percentage of the sample is taken:\n").strip()
				for x in sel.split(","):
					try:
						conditions[a].append(sels[int(x)-1])
						pkey[a]+=["of_"+str(sels[int(x)-1][0])+"_is_"+str(sels[int(x)-1][1])]
					except:
						pass

				stepnum+=1
				sel=raw_input(">> [step "+str(stepnum)+"/4] ["+a+" coord] [conditions of sample] please type in the number (or numbers separated by commas)\n\tof the conditions determining the sample:\n").strip()
				for x in sel.split(","):
					try:
						targets[a].append(sels[int(x)-1])
						pkey[a]+=[str(sels[int(x)-1][0])+"_is_"+str(sels[int(x)-1][1])]
					except:
						pass


			# print ">> POPULATION:"
			# print conditions
			#
			# print ">> SAMPLE:"
			# print targets

			init.population=conditions
			init.sample=targets

			init.pkey="X_"+"-".join(pkey['x'])+"."+"Y_"+"-".join(pkey['y'])
			print ">> plotting: "+ init.pkey


		if not hasattr(self,'bestParses'):
			for child in self.children:
				child.plot(init)
		else:
			posdict={}
			minparselen = min([len(parse.positions) for parse in self.bestParses()])
			maxparselen = max([len(parse.positions) for parse in self.bestParses()])
			#if not hasattr(self,'minparselen'): return None
			for posnum in range(maxparselen):
				posdict[posnum]={'x':[],'y':[]}
				for parse in self.bestParses():
					try:
						posfeats=parse.positions[posnum].posfeats()
					except IndexError:
						# there is no position number `posnum` in this parse `parse`
						continue

					for a in ['x','y']:
						conds=init.population[a]
						targs=init.sample[a]

						condsHold=True
						if len(conds):
							for cond in conds:
								condK=cond[0]
								condV=cond[1]

								try:
									if posfeats[condK]==condV:
										continue
								except:
									condsHold=False
									break
								condsHold=False
								break

						if condsHold:
							targsHold=True
							for targ in targs:
								targK=targ[0]
								targV=targ[1]

								try:
									if posfeats[targK]==targV:
										continue
								except:
									targsHold=False
									break
								targsHold=False
								break

							if targsHold:
								posdict[posnum][a].append(1)
							else:
								posdict[posnum][a].append(0)

			for a in ['x','y']:
				if not posdict[posnum][a]:
					print "<< not enough data: position number ("+str(posnum)+") empty on dimension ["+str(a)+"]"
					return None

			init.plotstats[self.getName()]=posdict
			if (self!=init): return None

		totalstrs=[]
		totaltsvs=[]
		for textname,posdict in sorted(init.plotstats.items()):

			tsv="posnum\tnumobs\tx_mean\ty_mean\tx_std\ty_std\n"
			xs=[]
			ys=[]
			for posnum,xydict in posdict.items():
				x_avg,x_std=mean_stdev(xydict['x'])
				y_avg,y_std=mean_stdev(xydict['y'])

				assert len(xydict['x'])==len(xydict['y'])

				xs.append(x_avg)
				ys.append(y_avg)
				tsv+="\t".join(str(bb) for bb in [(posnum+1),len(xydict['x']),x_avg,y_avg,x_std,y_std])+"\n"


			ccmsg=""
			cc=None
			p=None
			try:
				from statlib import stats
				(cc,p)=stats.pearsonr(xs,ys)

				aa=makeminlength("    correlation coefficient: ",int(being.linelen/1.4))+str(cc)
				bb=makeminlength("    p-value: ",int(being.linelen/1.4))+str(p)

				tsv+=aa.strip().replace(":",":\t")+"\n"
				tsv+=bb.strip().replace(":",":\t")+"\n"

				for l in tsv.split("\n"):
					totaltsvs.append(textname+"_"+l)

				ccmsg+=aa+"\n"+bb+"\n"

			except:
				pass

			writeToFile(textname,init.pkey,tsv,extension="tsv")
			totaltsvs.append(tsv)

			"""
			try:
				strtowrite=self.makeBubbleChart(posdict,".".join([textname,init.pkey]),(cc,p))
				totalstrs+=[strtowrite]
				writeToFile(textname,init.pkey,self._getBubbleHeader()+strtowrite+self._getBubbleFooter(),extension="htm")
			except:
				pass
			"""

			if ccmsg:
				print ccmsg

		if not self.classname()=="Corpus": return None

		"""
		writeToFile(self.getName(),
			init.pkey,
			self._getBubbleHeader()+"\n<br/><br/><br/><br/><br/><br/><br/><br/>\n".join(totalstrs)+self._getBubbleFooter(),
			iscorpus=True,
			extension="htm")
		"""

		writeToFile(self.getName(),init.pkey,"\n\n\n\n".join(totaltsvs),iscorpus=True,extension="tsv")
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)
760669
def plot_data():
    '''

    '''

    var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM']
    # colorbar limits for each property
    lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]])  # reasonable values
    # lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps

    for fname in fnames:
        fig, axes = plt.subplots(nrows=4, ncols=2)
        fig.set_size_inches(20, 10)
        fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.0, hspace=0.07)
        i = 0
        for ax, Var, cmap in zip(axes.flat, var, cmaps):  # loop through data to plot up

            # get variable data
            lat, lon, z, data = test.read(Var, fname)

            map1 = ax.scatter(lat, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=lims[i, 0], vmax=lims[i, 1])
            # no stupid offset
            y_formatter = mpl.ticker.ScalarFormatter(useOffset=False)
            ax.xaxis.set_major_formatter(y_formatter)
            if i == 6:
                ax.set_xlabel('Latitude [degrees]')
                ax.set_ylabel('Depth [m]')
            else:
                ax.set_xticklabels([])
                ax.set_yticklabels([])
            ax.set_ylim(-z.max(), 0)
            ax.set_xlim(lat.min(), lat.max())
            cb = plt.colorbar(map1, ax=ax, pad=0.02)
            cb.set_label(cmap.name + ' [' + '$' + cmap.units + '$]')
            i += 1

        fig.savefig('figures/' + fname.split('.')[0] + '.png', bbox_inches='tight')
411878
def plot_data(self, proj, ax):
        
        x, y = proj
        ax.scatter(self.ig.independent_data[x],
                   self.ig.dependent_data[y], c='b')
866250
def data(self,data):
        """"""
        assert type(data) is np.ndarray
        assert data.shape[1] == self.nCols
        for i in range(self.nCols):
            self.colData[i]=data[:,i].tolist()
30649
def to_df(figure):
    
    dfs=[]
    for trace in figure['data']:
        if 'scatter' in trace['type']:
            try:
                if type(trace['x'][0])==float:
                    index=trace['x']
                else:
                    index=pd.to_datetime(trace['x'])
            except:
                index=trace['x']
            if 'marker' in trace:
                d={}
                if 'size' in trace['marker']:
                    size=trace['marker']['size']
                    if type(size)!=list:
                        size=[size]*len(index)
                    d['size']=size
                if 'text' in trace:
                    d['text']=trace['text']
                if 'name' in trace:
                    name=trace['name']
                    if type(name)!=list:
                        name=[name]*len(index)
                    d['categories']=name
                d['y']=trace['y']
                d['x']=trace['x']
                if 'z' in trace:
                    d['z']=trace['z']
                df=pd.DataFrame(d)
            else:
                df=pd.Series(trace['y'],index=index,name=trace['name'])
            dfs.append(df)
        elif trace['type'] in ('heatmap','surface'):
            df=pd.DataFrame(trace['z'].transpose(),index=trace['x'],columns=trace['y'])
            dfs.append(df)
        elif trace['type'] in ('box','histogram'):
            vals=trace['x'] if 'x' in trace else trace['y']
            df=pd.DataFrame({trace['name']:vals})
            dfs.append(df)
    if max(list(map(len,dfs)))==min(list(map(len,dfs))):
        if len(dfs)==1:
            return dfs[0]
        else:
            if type(dfs[0])==pd.core.series.Series:
                return pd.concat(dfs,axis=1)                
            if all(dfs[0].columns==dfs[1].columns):
                    return pd.concat(dfs,axis=0)
            else:
                return pd.concat(dfs,axis=1)
    else:
        try:
            return pd.concat(dfs)
        except:
            return dfs
1245357
def plot(self, bins=250, **kwargs):
        """"""
        # Data #
        counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
        # Linear bins in logarithmic space #
        if 'log' in kwargs.get('x_scale', ''):
            start, stop = numpy.log10(1), numpy.log10(max(counts))
            bins = list(numpy.logspace(start=start, stop=stop, num=bins))
            bins.insert(0, 0)
        # Plot #
        fig = pyplot.figure()
        pyplot.hist(counts, bins=bins, color='gray')
        axes = pyplot.gca()
        # Information #
        title = 'Distribution of the total nucleotide count in the bins'
        axes.set_title(title)
        axes.set_xlabel('Number of nucleotides in a bin')
        axes.set_ylabel('Number of bins with that many nucleotides in them')
        # Save it #
        self.save_plot(fig, axes, **kwargs)
        pyplot.close(fig)
        # For convenience #
        return self
375767
def plot(q: np.ndarray, bodies: List[str], plot_colors: Dict[str, str],
         sim_name: str, fname: Optional[str] = None):
    
    # Get N and number of dims
    N, dims = q.shape

    # Slices for 
    x_slice = slice(0, dims, 3)
    y_slice = slice(1, dims, 3)
    # Convert all distances from meters to astronomical units (AU)
    plot_x = q[:, x_slice] / au2m
    plot_y = q[:, y_slice] / au2m
    
    # Set up chart title and scale
    fig, ax = plt.subplots(figsize=[12,12])
    ax.set_title(f'Inner Planetary Orbits in 2018; Weekly from {sim_name}')
    ax.set_xlabel('x in J2000.0 Frame; Astronomical Units (au)')
    ax.set_ylabel('y in J2000.0 Frame; Astronomical Units (au)')
    # Scale and tick size
    a = 5.0
    da = 1.0
    ticks = np.arange(-a, a+da, da)
    # Set limits and ticks
    ax.set_xlim(-a, a)
    ax.set_ylim(-a, a)
    ax.set_xticks(ticks)
    ax.set_yticks(ticks)

    # Set marker sizes proportional to size of bodies
    radius_earth = radius_tbl['earth']
    markersize_earth = 4.0
    markersize_tbl = {body : cbrt(radius_tbl[body] / radius_earth) * markersize_earth for body in bodies}
    
    # Plot the orbit of each body
    for k, body in enumerate(bodies):
        ax.plot(plot_x[:, k], plot_y[:, k], label=body, color=plot_colors[body], 
                linewidth=0, markersize = markersize_tbl[body], marker='o')
    
    # Legend and grid
    fig.legend(loc=7, bbox_to_anchor=(0.85, 0.5))
    # ax.legend()
    ax.grid()

    # Save plot if a filename was provided
    if fname is not None:
        fig.savefig(fname, bbox_inches='tight')

    # Display plot
    plt.show()
1241039
def _add_converted_units(self, dataframe, parameter, key='VALUE'):
        """"""
        convert_unit = self.parameters.get_converter(parameter)
        try:
            log.debug("Adding unit converted DATA_VALUE to the data")
            dataframe[key] = dataframe['DATA_VALUE'].apply(convert_unit)
        except KeyError:
            log.warning("Missing 'VALUE': no unit conversion.")
        else:
            dataframe.unit = self.parameters.unit(parameter)
1103640
def _plot(self, xticks=[], yticks=[], minor_xticks=[], minor_yticks=[],
              xlabel='Longitude', ylabel='Latitude', ax=None, ax2=None,
              colorbar=None, cb_orientation=None, cb_label=None, grid=False,
              axes_labelsize=None, tick_labelsize=None, **kwargs):
        """"""

        if ax is None:
            if colorbar is True:
                if cb_orientation == 'horizontal':
                    scale = 0.67
                else:
                    scale = 0.5
            else:
                scale = 0.55
            figsize = (_mpl.rcParams['figure.figsize'][0],
                       _mpl.rcParams['figure.figsize'][0] * scale)
            fig, axes = _plt.subplots(1, 1, figsize=figsize)
        else:
            axes = ax

        deg = '$^{\circ}$'
        xticklabels = [str(int(y)) + deg for y in xticks]
        yticklabels = [str(int(y)) + deg for y in yticks]

        cim = axes.imshow(self.data, origin='upper',
                          extent=(0., 360., -90., 90.), **kwargs)
        axes.set(xticks=xticks, yticks=yticks)
        axes.set_xlabel(xlabel, fontsize=axes_labelsize)
        axes.set_ylabel(ylabel, fontsize=axes_labelsize)
        axes.set_xticklabels(xticklabels, fontsize=tick_labelsize)
        axes.set_yticklabels(yticklabels, fontsize=tick_labelsize)
        axes.set_xticks(minor_xticks, minor=True)
        axes.set_yticks(minor_yticks, minor=True)
        axes.grid(grid, which='major')

        if colorbar is True:
            if cb_orientation == 'vertical':
                divider = _make_axes_locatable(axes)
                cax = divider.append_axes("right", size="2.5%", pad=0.15)
                cbar = _plt.colorbar(cim, cax=cax, orientation=cb_orientation)
            else:
                divider = _make_axes_locatable(axes)
                cax = divider.append_axes("bottom", size="5%", pad=0.5)
                cbar = _plt.colorbar(cim, cax=cax,
                                     orientation=cb_orientation)
            if cb_label is not None:
                cbar.set_label(cb_label, fontsize=axes_labelsize)
            cbar.ax.tick_params(labelsize=tick_labelsize)

        if ax is None:
            return fig, axes
962006
def plot_nb(self,xdata,ydata=[],logScale=False):
        ''''''
        self.plot(xdata,ydata,logScale)
40226
def units(cls, scale=1):
        '''
        

        '''
        return [cls(x=scale), cls(y=scale), cls(z=scale)]
810582
def prepare_data():
  """"""
  ((x_train, y_train), (x_test, y_test)) = DATASET.load_data()
  x_train = x_train.astype("float32")
  x_test = x_test.astype("float32")
  x_train /= 255.0
  x_test /= 255.0
  return ((x_train, y_train), (x_test, y_test))