plot the het_check scatter plot
350838
def peddy_het_check_plot(self):
        """"""
        # empty dictionary to add sample names, and dictionary of values
        data = {}

        # for each sample, and list in self.peddy_data
        for s_name, d in self.peddy_data.items():
            # check the sample contains the required columns
            if 'median_depth_het_check' in d and 'het_ratio_het_check' in d:
                # add sample to dictionary with value as a dictionary of points to plot
                data[s_name] = {
                    'x': d['median_depth_het_check'],
                    'y': d['het_ratio_het_check']
                }

        pconfig = {
            'id': 'peddy_het_check_plot',
            'title': 'Peddy: Het Check',
            'xlab': 'median depth',
            'ylab': 'proportion het calls',
        }

        self.add_section (
            name = 'Het Check',
            description = "Proportion of sites that were heterozygous against median depth.",
            helptext = """
            A high proportion of heterozygous sites suggests contamination, a low proportion suggests consanguinity.
            
            See [the main peddy documentation](https://peddy.readthedocs.io/en/latest/output.html#het-check) for more details about the `het_check` command.
            """,
            anchor = 'peddy-hetcheck-plot',
            plot = scatter.plot(data, pconfig)
        )
952800
def plot_fit(self):
        
        self.plt.plot(*self.fit.fit, **self.options['fit'])
1126199
def offline_plotly_scatter3d(df, x=0, y=1, z=-1):
    
    data = []
    # clusters = []
    colors = ['rgb(228,26,28)', 'rgb(55,126,184)', 'rgb(77,175,74)']

    # df.columns = clean_columns(df.columns)

    x = get_array(df, x, default=0)
    y = get_array(df, y, default=1)
    z = get_array(df, z, default=-1)
    for i in range(len(df['name'].unique())):
        name = df['Name'].unique()[i]
        color = colors[i]
        x = x[pd.np.array(df['name'] == name)]
        y = y[pd.np.array(df['name'] == name)]
        z = z[pd.np.array(df['name'] == name)]

        trace = dict(
            name=name,
            x=x, y=y, z=z,
            type="scatter3d",
            mode='markers',
            marker=dict(size=3, color=color, line=dict(width=0)))
        data.append(trace)

    layout = dict(
        width=800,
        height=550,
        autosize=False,
        title='Iris dataset',
        scene=dict(
            xaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            yaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            zaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            aspectratio=dict(x=1, y=1, z=0.7),
            aspectmode='manual'
        ),
    )

    fig = dict(data=data, layout=layout)

    # IPython notebook
    # plotly.iplot(fig, filename='pandas-3d-iris', validate=False)

    url = plotly.offline.plot(fig, filename='pandas-3d-iris', validate=False)
    return url
316931
def draw_scatter_plot(world, size, target):
    

    #Find min and max values of humidity and temperature on land so we can
    #normalize temperature and humidity to the chart
    humid = numpy.ma.masked_array(world.layers['humidity'].data, mask=world.layers['ocean'].data)
    temp = numpy.ma.masked_array(world.layers['temperature'].data, mask=world.layers['ocean'].data)
    min_humidity = humid.min()
    max_humidity = humid.max()
    min_temperature = temp.min()
    max_temperature = temp.max()
    temperature_delta = max_temperature - min_temperature
    humidity_delta = max_humidity - min_humidity
    
    #set all pixels white
    for y in range(0, size):
        for x in range(0, size):
            target.set_pixel(x, y, (255, 255, 255, 255))

    #fill in 'bad' boxes with grey
    h_values = ['62', '50', '37', '25', '12']
    t_values = [   0,    1,    2,   3,    5 ]
    for loop in range(0, 5):
        h_min = (size - 1) * ((world.layers['humidity'].quantiles[h_values[loop]] - min_humidity) / humidity_delta)
        if loop != 4:
            h_max = (size - 1) * ((world.layers['humidity'].quantiles[h_values[loop + 1]] - min_humidity) / humidity_delta)
        else:
            h_max = size
        v_max = (size - 1) * ((world.layers['temperature'].thresholds[t_values[loop]][1] - min_temperature) / temperature_delta)
        if h_min < 0:
            h_min = 0
        if h_max > size:
            h_max = size
        if v_max < 0:
            v_max = 0
        if v_max > (size - 1):
            v_max = size - 1
            
        if h_max > 0 and h_min < size and v_max > 0:
            for y in range(int(h_min), int(h_max)):
                for x in range(0, int(v_max)):
                    target.set_pixel(x, (size - 1) - y, (128, 128, 128, 255))
                    
    #draw lines based on thresholds
    for t in range(0, 6):
        v = (size - 1) * ((world.layers['temperature'].thresholds[t][1] - min_temperature) / temperature_delta)
        if 0 < v < size:
            for y in range(0, size):
                target.set_pixel(int(v), (size - 1) - y, (0, 0, 0, 255))
    ranges = ['87', '75', '62', '50', '37', '25', '12']
    for p in ranges:
        h = (size - 1) * ((world.layers['humidity'].quantiles[p] - min_humidity) / humidity_delta)
        if 0 < h < size:
            for x in range(0, size):
                target.set_pixel(x, (size - 1) - int(h), (0, 0, 0, 255))

    #draw gamma curve
    curve_gamma = world.gamma_curve
    curve_bonus = world.curve_offset
    
    for x in range(0, size):
        y = (size - 1) * ((numpy.power((float(x) / (size - 1)), curve_gamma) * (1 - curve_bonus)) + curve_bonus)
        target.set_pixel(x, (size - 1) - int(y), (255, 0, 0, 255))

    #examine all cells in the map and if it is land get the temperature and
    #humidity for the cell.
    for y in range(world.height):
        for x in range(world.width):
            if world.is_land((x, y)):
                t = world.temperature_at((x, y))
                p = world.humidity_at((x, y))

    #get red and blue values depending on temperature and humidity                
                if world.is_temperature_polar((x, y)):
                    r = 0
                elif world.is_temperature_alpine((x, y)):
                    r = 42
                elif world.is_temperature_boreal((x, y)):
                    r = 85
                elif world.is_temperature_cool((x, y)):
                    r = 128
                elif world.is_temperature_warm((x, y)):
                    r = 170
                elif world.is_temperature_subtropical((x, y)):
                    r = 213
                elif world.is_temperature_tropical((x, y)):
                    r = 255
                if world.is_humidity_superarid((x, y)):
                    b = 32
                elif world.is_humidity_perarid((x, y)):
                    b = 64
                elif world.is_humidity_arid((x, y)):
                    b = 96
                elif world.is_humidity_semiarid((x, y)):
                    b = 128
                elif world.is_humidity_subhumid((x, y)):
                    b = 160
                elif world.is_humidity_humid((x, y)):
                    b = 192
                elif world.is_humidity_perhumid((x, y)):
                    b = 224
                elif world.is_humidity_superhumid((x, y)):
                    b = 255

    #calculate x and y position based on normalized temperature and humidity
                nx = (size - 1) * ((t - min_temperature) / temperature_delta)
                ny = (size - 1) * ((p - min_humidity) / humidity_delta)
                    
                target.set_pixel(int(nx), (size - 1) - int(ny), (r, 128, b, 255))
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")
214617
def treeplot(self, qlist, credible_interval):
        """"""
        for y, _, label, values, color in self.iterator():
            ntiles = np.percentile(values.flatten(), qlist)
            ntiles[0], ntiles[-1] = hpd(values.flatten(), credible_interval)
            yield y, label, ntiles, color
565077
def _histplot_op(ax, data, **kwargs):
    """"""
    bins = get_bins(data)
    ax.hist(data, bins=bins, align="left", density=True, **kwargs)
    return ax
830646
def plot(self, n=500, eigenvalues=None, sum=None, title=None,
             ax=None, **kwargs):
        """
        from pygsp.plotting import _plot_filter
        return _plot_filter(self, n=n, eigenvalues=eigenvalues, sum=sum,
                            title=title, ax=ax, **kwargs)
623193
def methylqa_alignment_plot (self):
        

        if len(self.methylqa_coverage_counts) == 0:
            return '<div class="alert alert-danger">No histogram data found.</div>'

        pconfig = {
            'id': 'methylqa_coverage',
            'title': 'methylQA: CpG Coverage',
            'categories': True,
            'ylab': 'CpG Counts',
            'xlab': 'Times covered',
            'ymin': 0,
            'data_labels': [
                {'name': 'Counts', 'ylab': 'CpG Counts' },
                {'name': 'Percentages', 'ylab': '% CpGs', 'ymax': 100 }
            ]
        }
        return linegraph.plot([self.methylqa_coverage_counts, self.methylqa_coverage_percentages], pconfig)
1305996
def plot_matched_regions(hits = @hits)
      no_lines = hits.length

      hits_less = hits[0..[no_lines, hits.length - 1].min]

      data = hits_less.each_with_index.map do |hit, i|
        { 'y' => i,
          'start' => hit.hsp_list.map(&:match_query_from).min,
          'stop' => hit.hsp_list.map(&:match_query_to).max,
          'color' => 'black',
          'dotted' => 'true' }
      end .flatten +
             hits_less.each_with_index.map do |hit, i|
               hit.hsp_list.map do |hsp|
                 { 'y' => i,
                   'start' => hsp.match_query_from,
                   'stop' => hsp.match_query_to,
                   'color' => 'orange' }
               end
             end .flatten

      Plot.new(data,
               :lines,
               'Gene Merge Validation: Query coord covered by blast hit' \
               ' (1 line/hit)',
               '',
               'Offset in Prediction',
               'Hit Number',
               hits_less.length)
    end
1308555
def plot(self, qubit_subset=None):
        
        import matplotlib.pyplot as plt
        prob_dict = self.get_outcome_probs()
        if qubit_subset:
            sub_dict = {}
            qubit_num = len(self)
            for i in qubit_subset:
                if i > (2**qubit_num - 1):
                    raise IndexError("Index {} too large for {} qubits.".format(i, qubit_num))
                else:
                    sub_dict[get_bitstring_from_index(i, qubit_num)] = prob_dict[get_bitstring_from_index(i, qubit_num)]
            prob_dict = sub_dict
        plt.bar(range(len(prob_dict)), prob_dict.values(), align='center', color='#6CAFB7')
        plt.xticks(range(len(prob_dict)), prob_dict.keys())
        plt.show()
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
322580
def check_data(labels, data, args):
    """"""
    len_categories = len(data[0])

    # Check that there are data for all labels.
    if len(labels) != len(data):
        print(">> Error: Label and data array sizes don't match")
        sys.exit(1)

    # Check that there are data for all categories per label.
    for dat in data:
        if len(dat) != len_categories:
            print(">> Error: There are missing values")
            sys.exit(1)

    colors = []

    # If user inserts colors, they should be as many as the categories.
    if args['color'] is not None:
        if len(args['color']) != len_categories:
            print(">> Error: Color and category array sizes don't match")
            sys.exit(1)

        for color in args['color']:
            colors.append(AVAILABLE_COLORS.get(color))

    # Vertical graph for multiple series of same scale is not supported yet.
    if args['vertical'] and len_categories > 1 and not args['different_scale']:
        print(">> Error: Vertical graph for multiple series of same "
              "scale is not supported yet.")
        sys.exit(1)

    # If user hasn't inserted colors, pick the first n colors
    # from the dict (n = number of categories).
    if args['stacked'] and not colors:
        colors = [v for v in list(AVAILABLE_COLORS.values())[:len_categories]]

    return colors
709507
def scatter(data, color=None, point_size=2, f_tooltip=None):
    
    import warnings
    warnings.warn("deprecated, use geoplotlib.dot", DeprecationWarning)
    dot(data, color, point_size, f_tooltip)
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
532277
def horizontal_bar_plot(ax, Si, param_dict, sortby='mu_star', unit=''):
    '''
    '''

    assert sortby in ['mu_star', 'mu_star_conf', 'sigma', 'mu']

    # Sort all the plotted elements by mu_star (or optionally another
    # metric)
    names_sorted = _sort_Si(Si, 'names', sortby)
    mu_star_sorted = _sort_Si(Si, 'mu_star', sortby)
    mu_star_conf_sorted = _sort_Si(Si, 'mu_star_conf', sortby)

    # Plot horizontal barchart
    y_pos = np.arange(len(mu_star_sorted))
    plot_names = names_sorted

    out = ax.barh(y_pos,
                  mu_star_sorted,
                  xerr=mu_star_conf_sorted,
                  align='center',
                  ecolor='black',
                  **param_dict)

    ax.set_yticks(y_pos)
    ax.set_yticklabels(plot_names)
    ax.set_xlabel(r'$\mu^\star$' + unit)

    ax.set_ylim(min(y_pos)-1, max(y_pos)+1)

    return out
1179278
def hist(P, edges, **kwargs):
  
  '''

  from matplotlib.collections import PatchCollection
  from matplotlib.patches     import Polygon

  # extract local options
  axis      = kwargs.pop( 'axis'      , plt.gca() )
  cindex    = kwargs.pop( 'cindex'    , None      )
  autoscale = kwargs.pop( 'autoscale' , True      )

  # set defaults
  kwargs.setdefault('edgecolor','k')

  # no color-index -> set transparent
  if cindex is None:
    kwargs.setdefault('facecolor',(0.,0.,0.,0.))

  # convert -> list of Polygons
  poly = []
  for p, xl, xu in zip(P, edges[:-1], edges[1:]):
    coor = np.array([
      [xl, 0.],
      [xu, 0.],
      [xu, p ],
      [xl, p ],
    ])
    poly.append(Polygon(coor))
  args = (poly)

  # convert patches -> matplotlib-objects
  p = PatchCollection(args,**kwargs)
  # add colors to patches
  if cindex is not None:
    p.set_array(cindex)
  # add patches to axis
  axis.add_collection(p)

  # rescale the axes manually
  if autoscale:
    # - get limits
    xlim = [ edges[0], edges[-1] ]
    ylim = [ 0       , np.max(P) ]
    # - set limits +/- 10% extra margin
    axis.set_xlim([xlim[0]-.1*(xlim[1]-xlim[0]),xlim[1]+.1*(xlim[1]-xlim[0])])
    axis.set_ylim([ylim[0]-.1*(ylim[1]-ylim[0]),ylim[1]+.1*(ylim[1]-ylim[0])])

  return p