Creates 2x2 grid plot of the 4 anscombe datasets for illustration.
482770
def anscombe():
    
    _, ((axa, axb), (axc, axd)) =  plt.subplots(2, 2, sharex='col', sharey='row')
    colors = get_color_cycle()

    for arr, ax, color in zip(ANSCOMBE, (axa, axb, axc, axd), colors):
        x = arr[0]
        y = arr[1]

        # Set the X and Y limits
        ax.set_xlim(0, 15)
        ax.set_ylim(0, 15)

        # Draw the points in the scatter plot
        ax.scatter(x, y, c=color)

        # Draw the linear best fit line on the plot
        draw_best_fit(x, y, ax, c=color)

    return (axa, axb, axc, axd)
172114
def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None):
    
    f = plt.figure(figsize=figsize)
    if maintitle is not None: plt.suptitle(maintitle, fontsize=16)
    for i in range(len(imspaths)):
        sp = f.add_subplot(rows, ceildiv(len(imspaths), rows), i+1)
        sp.axis('Off')
        if titles is not None: sp.set_title(titles[i], fontsize=16)
        img = plt.imread(imspaths[i])
        plt.imshow(img)
26842
def plotGrid(self, numLines=(5,5), lineWidth=1, colour="#777777"):
        
        x1, x2, y1, y2 = mp.axis()
        ra1, dec0 = self.pixToSky(x1, y1)
        ra0, dec1 = self.pixToSky(x2, y2)

        xNum, yNum = numLines
        self.raRange, self.decRange  = self.getRaDecRanges(numLines)

        #import pdb; pdb.set_trace()
        #Guard against Ra of zero within the plot
        a1 = np.abs(ra1-ra0)
        a2 = np.abs( min(ra0, ra1) - (max(ra0, ra1) - 360))
        if a2 < a1:     #Then we straddle 360 degrees in RA
            if ra0 < ra1:
                ra1 -= 360
            else:
                ra0 -= 360


        #Draw lines of constant dec
        lwr = min(ra0, ra1)
        upr = max(ra0, ra1)
        stepX = round((upr-lwr) / float(xNum))
        ra_deg = np.arange(lwr - 3*stepX, upr + 3.5*stepX, 1, dtype=np.float)
        for dec in self.decRange:
            self.plotLine(ra_deg, dec, '-', color = colour, linewidth = lineWidth)


        #Draw lines of const ra
        lwr = min(dec0, dec1)
        upr = max(dec0, dec1)
        stepY = round((upr-lwr) / float(yNum))
        dec_deg = np.arange(dec0 - 3*stepY, dec1 + 3.5*stepY, 1, dtype=np.float)
        for ra in self.raRange:
            self.plotLine(ra, dec_deg, '-', color = colour, linewidth = lineWidth)

        mp.axis([x1, x2, y1, y2])
469539
def _generate_grid(self):
        """"""
        grid_axes = []
        for _, param in self.tunables:
            grid_axes.append(param.get_grid_axis(self.grid_width))

        return grid_axes
835277
def show_xyzs(self, xs, ys, zs, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
        ""
        if self._square_show_res:
            title = 'Ground truth\nPredictions'
            rows = int(np.ceil(math.sqrt(len(xs))))
            axs = subplots(rows, rows, imgsize=imgsize, figsize=figsize, title=title, weight='bold', size=12)
            for x,y,z,ax in zip(xs,ys,zs,axs.flatten()): x.show(ax=ax, title=f'{str(y)}\n{str(z)}', **kwargs)
            for ax in axs.flatten()[len(xs):]: ax.axis('off')
        else:
            title = 'Ground truth/Predictions'
            axs = subplots(len(xs), 2, imgsize=imgsize, figsize=figsize, title=title, weight='bold', size=14)
            for i,(x,y,z) in enumerate(zip(xs,ys,zs)):
                x.show(ax=axs[i,0], y=y, **kwargs)
                x.show(ax=axs[i,1], y=z, **kwargs)
62145
def plot_date(datasets, **kwargs):
    

    defaults = {
        'grid': True,
        'xlabel': '',
        'ylabel': '',
        'title': '',
        'output': None,
        'figsize': (8, 6),
    }
    plot_params = {
        'color': 'b',
        'ls': '',
        'alpha': 0.75,
    }
    _update_params(defaults, plot_params, kwargs)
    if isinstance(datasets, Dataset):
        datasets = [datasets]

    colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
    color = plot_params.pop('color')
    try:
        del colors[colors.index(color)]
        colors.insert(0, color)
    except IndexError:
        pass
    colors = cycle(colors)

    fig, ax = plt.subplots()
    fig.set_size_inches(*defaults['figsize'])
    fig.autofmt_xdate()
    ax.autoscale_view()

    for dataset in datasets:
        if isinstance(dataset, Dataset):
            dates = list(dataset.get_column_by_type(dataset.DATE))
            values = list(dataset.get_column_by_type(dataset.NUM))
            label = dataset.name
        else:
            dates, values = dataset
            label = ''
        dates = date2num(dates)
        color = next(colors)
        plt.plot_date(dates, values, color=color, label=label, **plot_params)

    plt.xlabel(defaults['xlabel'])
    plt.ylabel(defaults['ylabel'])
    plt.title(defaults['title'])
    plt.grid(defaults['grid'])

    plt.legend(loc='best', prop={'size': 10})
    filename = defaults['output'] or get_tmp_file_name('.png')
    plt.savefig(filename)
    return filename
448515
function drawLinesDataset(axis, animPc, data, config, ctx, offsets, vars) {
		var xAxisPosY = vars.xAxisPosY;
		var yAxisPosX = vars.yAxisPosX;
		var valueHop = vars.valueHop;
		var nbValueHop = vars.nbValueHop;
		var scaleHop = vars.scaleHop;
		var zeroY = vars.zeroY;
		var calculatedScale = vars.calculatedScale;
		var logarithmic = vars.logarithmic;
		var currentAnimPc = animationCorrection(animPc, data, config, 0, 0, 0);
		var totvalue = new Array();
		var maxvalue = new Array();
		var lmaxvalue = new Array();
		var lminvalue = new Array();
		for (var i = 0; i < data.datasets.length; i++) {
			lmaxvalue[i] = -999999999;
			lminvalue[i] = 999999999;
			if ((axis == 2 && data.datasets[i].axis == 2) || (axis != 2 && data.datasets[i].axis != 2)) {
				for (var j = 0; j < data.datasets[i].data.length; j++) {
					totvalue[j] = 0;
					maxvalue[j] = -999999999;
				}
			}
		}
		currentAnimPc.mainVal = 1;
		for (var i = 0; i < data.datasets.length; i++) {
			if ((axis == 2 && data.datasets[i].axis == 2) || (axis != 2 && data.datasets[i].axis != 2)) {
				for (var j = 0; j < data.datasets[i].data.length; j++) {
					totvalue[j] += data.datasets[i].data[j];
					maxvalue[j] = Max([maxvalue[j], data.datasets[i].data[j]]);
					lmaxvalue[i] = Max([lmaxvalue[i], yPos(i, j)]);
					lminvalue[i] = Min([lminvalue[i], yPos(i, j)]);
				}
			}
		}
		for (var i = 0; i < data.datasets.length; i++) {
			if ((axis == 2 && data.datasets[i].axis == 2) || (axis != 2 && data.datasets[i].axis != 2)) {
				var prevpt = -1;
				var frstpt = -1;
				if (typeof data.datasets[i].strokeColor == "function") {
					ctx.strokeStyle = data.datasets[i].strokeColor("STROKECOLOR", data, config, i, -1, animPc, -1, "Line", ctx, yAxisPosX, lmaxvalue[i], yAxisPosX + valueHop * (data.datasets[i].data.length - 1), lmaxvalue[i] - ((config.animationLeftToRight) ? 1 : 1*currentAnimPc.mainVal) * (lmaxvalue[i] - lminvalue[i]));
				} else if (typeof data.datasets[i].strokeColor == "string") {
					ctx.strokeStyle = data.datasets[i].strokeColor;
				} else ctx.strokeStyle = config.defaultStrokeColor;
				ctx.lineWidth = config.datasetStrokeWidth;
				ctx.beginPath();
				var prevAnimPc;
				var prevXpos;
				prevAnimPc = 0;
				prevnotempty = 0;
				for (var j = 0; j < data.datasets[i].data.length; j++) {
					var xposj = xPos(i, j, data);
					currentAnimPc = animationCorrection(animPc, data, config, i, j, 0);
					if (currentAnimPc.mainVal == 0 && prevAnimPc > 0) {
						ctx.stroke();
						ctx.strokeStyle = "rgba(0,0,0,0)";
						//          ctx.lineWidth =0.01;                                                                   
						ctx.lineTo(prevXpos, xAxisPosY - zeroY);
					}
					prevAnimPc = currentAnimPc.mainVal;
					if (currentAnimPc.mainVal >= 1) {
						if (typeof(data.datasets[i].title) == "string") lgtxt = data.datasets[i].title.trim();
						else lgtxt = "";
					}
					if (!(typeof(data.datasets[i].data[j]) == 'undefined')) {
						prevXpos = xPos(i, j, data);
						if (prevpt == -1) {
							ctx.moveTo(xposj, yPos(i, j));
							frstpt = j;
						} else {
							if (config.bezierCurve) {
								ctx.bezierCurveTo(xPos(i, j - (j - prevpt) / 2, data), yPos(i, prevpt), xPos(i, j - (j - prevpt) / 2, data), yPos(i, j), xPos(i, j, data), yPos(i, j));
							} else {
								ctx.lineTo(xPos(i, j, data), yPos(i, j));
							}
						}
						if ((typeof(data.datasets[i].data[j + 1]) !== 'undefined') || (true == config.extrapolateMissingData)) {
							if (currentAnimPc.subVal > 0) {
								// next not missing value
								nxtnotmiss = -1;
								for (t = j + 1; t < data.datasets[i].data["length"] && nxtnotmiss == -1; t++) {
									if (!(typeof(data.datasets[i].data[t]) == 'undefined')) nxtnotmiss = t;
								}
								if (nxtnotmiss != -1) {
									prevXpos = xPos(i, j + currentAnimPc.subVal, data);
									if (config.bezierCurve) {
										ctx.bezierCurveTo(xPos(i, j + currentAnimPc.subVal / 2, data), yPos(i, j), xPos(i, j + currentAnimPc.subVal / 2, data), yPos(i, nxtnotmiss), xPos(i, j + currentAnimPc.subVal, data), yPos(i, nxtnotmiss));
									} else {
										ctx.lineTo(xPos(i, j + currentAnimPc.subVal, data), yPos(i, j + 1));
									}
								}
							}
							prevpt = j;
							if (animPc >= 1) {
								if (i == 0) divprev = data.datasets[i].data[j];
								else divprev = data.datasets[i].data[j] - data.datasets[i - 1].data[j];
								if (i == data.datasets.length - 1) divnext = data.datasets[i].data[j];
								else divnext = data.datasets[i].data[j] - data.datasets[i + 1].data[j];
								lgtxt2 = "";
								if (typeof data.datasets[i].xPos != "undefined") {
									if (!(typeof data.datasets[i].xPos[j] == "undefined")) lgtxt2 = data.datasets[i].xPos[j];
								}
								if (lgtxt2 == "" && !(typeof(data.labels[j]) == "undefined")) lgtxt2 = data.labels[j];
								if (typeof lgtxt2 == "string") lgtxt2 = lgtxt2.trim();
								jsGraphAnnotate[ctx.ChartNewId][jsGraphAnnotate[ctx.ChartNewId].length] = ["POINT", xPos(i, j, data), yPos(i, j), lgtxt, lgtxt2, 1 * data.datasets[i].data[j], divprev, divnext, maxvalue[j], totvalue[j], i, j];
								if (config.inGraphDataShow) {
									ctx.save();
									ctx.textAlign = config.inGraphDataAlign;
									ctx.textBaseline = config.inGraphDataVAlign;
									ctx.font = config.inGraphDataFontStyle + ' ' + config.inGraphDataFontSize + 'px ' + config.inGraphDataFontFamily;
									ctx.fillStyle = config.inGraphDataFontColor;
									var dotX = yAxisPosX + (valueHop * k),
										dotY = xAxisPosY - currentAnimPc.mainVal * (calculateOffset(logarithmic, data.datasets[i].data[j], calculatedScale, scaleHop)),
										paddingTextX = config.inGraphDataPaddingX,
										paddingTextY = config.inGraphDataPaddingY;
									var dispString = tmplbis(config.inGraphDataTmpl, {
										config: config,
										v1: fmtChartJS(config, lgtxt, config.fmtV1),
										v2: fmtChartJS(config, lgtxt2, config.fmtV2),
										v3: fmtChartJS(config, 1 * data.datasets[i].data[j], config.fmtV3),
										v4: fmtChartJS(config, divprev, config.fmtV4),
										v5: fmtChartJS(config, divnext, config.fmtV5),
										v6: fmtChartJS(config, maxvalue[j], config.fmtV6),
										v7: fmtChartJS(config, totvalue[j], config.fmtV7),
										v8: roundToWithThousands(config, fmtChartJS(config, 100 * data.datasets[i].data[j] / totvalue[j], config.fmtV8), config.roundPct),
										v9: fmtChartJS(config, yAxisPosX + (valueHop * k), config.fmtV9),
										v10: fmtChartJS(config, xAxisPosY - (calculateOffset(logarithmic, data.datasets[i].data[j], calculatedScale, scaleHop)), config.fmtV10),
										v11: fmtChartJS(config, i, config.fmtV11),
										v12: fmtChartJS(config, j, config.fmtV12),
										data: data
									});
									ctx.translate(xPos(i, j, data) + paddingTextX, yPos(i, j) - paddingTextY);
									ctx.rotate(config.inGraphDataRotate * (Math.PI / 180));
									ctx.fillTextMultiLine(dispString, 0, 0, ctx.textBaseline, config.inGraphDataFontSize);
									ctx.restore();
								}
							}
						}
					} else {
						if (false == config.extrapolateMissingData) {
							ctx.stroke();
							if (config.datasetFill) {
								ctx.lineTo(prevXpos, xAxisPosY - zeroY);
								ctx.lineTo(xPos(i, frstpt, data), xAxisPosY - zeroY);
								ctx.lineTo(xPos(i, frstpt, data), yPos(i, frstpt));
								ctx.closePath();
								if (typeof data.datasets[i].fillColor == "function") ctx.fillStyle = data.datasets[i].fillColor("FILLCOLOR", data, config, i, -1, currentAnimPc.mainVal, -1, "Line", ctx, yAxisPosX, lmaxvalue[i], yAxisPosX + valueHop * (data.datasets[i].data.length - 1), lmaxvalue[i] - ((config.animationLeftToRight) ? 1 : 1*currentAnimPc.mainVal) * (lmaxvalue[i] - lminvalue[i]));
								else if (typeof data.datasets[i].fillColor == "string") ctx.fillStyle = data.datasets[i].fillColor;
								else ctx.fillStyle = config.defaultFillColor;
								ctx.fill();
							}
							ctx.beginPath();
							prevpt = -1;
							frstpt = -1;
							prevAnimPc = 0;
							prevnotempty = 0;
						} else {
							if (currentAnimPc.subVal > 0) {
								nxtnotmiss = -1;
								for (t = j + 1; t < data.datasets[i].data["length"] && nxtnotmiss == -1; t++) {
									if (!(typeof(data.datasets[i].data[t]) == 'undefined')) nxtnotmiss = t;
								}
								if ((typeof(data.datasets[i].data[j]) !== 'undefined') || (true == config.extrapolateMissingData)) {
									if (nxtnotmiss != -1) {
										prevXpos = xPos(i, j + currentAnimPc.subVal, data);
										if (config.bezierCurve) {
											ctx.bezierCurveTo(xPos(i, prevpt + (j + currentAnimPc.subVal - prevpt) / 2, data), yPos(i, prevpt), xPos(i, prevpt + (j + currentAnimPc.subVal - prevpt) / 2, data), yPos(i, nxtnotmiss), xPos(i, j + currentAnimPc.subVal, data), yPos(i, nxtnotmiss));
										} else {
											ctx.lineTo(xPos(i, j + currentAnimPc.subVal, data), yPos(i, j + 1));
										}
									}
								}
							}
						}
					}
				}
				ctx.stroke();
				if (config.datasetFill) {
					//				ctx.lineTo(yAxisPosX + (valueHop * (data.datasets[i].data.length - 1)), xAxisPosY - zeroY);
					ctx.lineTo(prevXpos, xAxisPosY - zeroY);
					ctx.lineTo(xPos(i, frstpt, data), xAxisPosY - zeroY);
					ctx.lineTo(xPos(i, frstpt, data), yPos(i, frstpt));
					ctx.closePath();
					if (typeof data.datasets[i].fillColor == "function") { ctx.fillStyle = data.datasets[i].fillColor("FILLCOLOR", data, config, i, -1, currentAnimPc.mainVal, -1, "Line", ctx, yAxisPosX, lmaxvalue[i], yAxisPosX + valueHop * (data.datasets[i].data.length - 1), lmaxvalue[i] - ((config.animationLeftToRight) ? 1 : 1*currentAnimPc.mainVal) * (lmaxvalue[i] - lminvalue[i])); }
					else if (typeof data.datasets[i].fillColor == "string") ctx.fillStyle = data.datasets[i].fillColor;
					else ctx.fillStyle = config.defaultFillColor;
					ctx.fill();
				} else {
					ctx.closePath();
				}
				if (config.pointDot) {
					if (typeof data.datasets[i].pointColor == "function") ctx.fillStyle = data.datasets[i].pointColor("POINTCOLOR", data, config, i, -1, animPc, -1, "Line", ctx, yAxisPosX, lmaxvalue[i], yAxisPosX + valueHop * (data.datasets[i].data.length - 1), lmaxvalue[i] - ((config.animationLeftToRight) ? 1 : 1*currentAnimPc.mainVal) * (lmaxvalue[i] - lminvalue[i]));
					else ctx.fillStyle = data.datasets[i].pointColor;
					if (typeof data.datasets[i].pointStrokeColor == "function") ctx.strokeStyle = data.datasets[i].pointStrokeColor("POINTSTROKECOLOR", data, config, i, -1, animPc, -1, "Line", ctx, yAxisPosX, lmaxvalue[i], yAxisPosX + valueHop * (data.datasets[i].data.length - 1), lmaxvalue[i] - ((config.animationLeftToRight) ? 1 : 1*currentAnimPc.mainVal) * (lmaxvalue[i] - lminvalue[i]));
					else ctx.strokeStyle = data.datasets[i].pointStrokeColor;
					ctx.lineWidth = config.pointDotStrokeWidth;
					for (var k = 0; k < data.datasets[i].data.length; k++) {
						if (!(typeof(data.datasets[i].data[k]) == 'undefined')) {
							var currentAnimPc = animationCorrection(animPc, data, config, i, k, 0);
							if (currentAnimPc.mainVal > 0 || !config.animationLeftToRight) {
								ctx.beginPath();
								ctx.arc(xPos(i, k, data), yPos(i, k), config.pointDotRadius, 0, Math.PI * 2, true);
								ctx.fill();
								ctx.stroke();
							}
						}
					}
				}
			}
		};

		function yPos(dataSet, iteration) {
			return xAxisPosY - zeroY - currentAnimPc.mainVal * (calculateOffset(logarithmic, data.datasets[dataSet].data[iteration], calculatedScale, scaleHop) - zeroY);
		};

		function xPos(ival, iteration, data) {
			if (typeof data.datasets[ival].xPos == "object") {
				if (!(typeof data.datasets[ival].xPos[Math.floor(iteration + 0.0001)] == "undefined")) {
					var width = valueHop * nbValueHop;
					var deb = (typeof data.xBegin != "undefined") ? data.xBegin : 1 * data.labels[0];
					var fin = (typeof data.xEnd != "undefined") ? data.xEnd : 1 * data.labels[data.labels.length - 1];
					if (fin <= deb) fin = deb + 100;
					if (1 * data.datasets[ival].xPos[Math.floor(iteration + 0.0001)] >= deb && data.datasets[ival].xPos[Math.floor(iteration + 0.0001)] <= fin) {
						var p1 = yAxisPosX + width * ((1 * data.datasets[ival].xPos[Math.floor(iteration + 0.0001)] - deb) / (fin - deb));
						var p2 = p1;
						if (Math.abs(iteration - Math.floor(iteration + 0.0001)) > 0.0001) {
							var tt = iteration + Math.floor(iteration + 0.0001);
							var p2 = xPos(ival, Math.ceil(iteration - 0.0001), data);
						}
						return p1 + (iteration - Math.floor(iteration + 0.0001)) * (p2 - p1);
					}
				}
			}
			return yAxisPosX + (valueHop * iteration);
		};
	}
746258
def show_xys(self, xs, ys, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
        ""
        rows = int(np.ceil(math.sqrt(len(xs))))
        axs = subplots(rows, rows, imgsize=imgsize, figsize=figsize)
        for x,y,ax in zip(xs, ys, axs.flatten()): x.show(ax=ax, y=y, **kwargs)
        for ax in axs.flatten()[len(xs):]: ax.axis('off')
        plt.tight_layout()
71096
def gen_grid_2d(shape, voxelsize):
    
    nr, nc = shape
    nrm1, ncm1 = nr - 1, nc - 1
    # sh = nm.asarray(shape)
    # calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols)
    nedges = 0
    for direction in range(len(shape)):
        sh = copy.copy(list(shape))
        sh[direction] += -1
        nedges += nm.prod(sh)

    nedges_old = ncm1 * nr + nrm1 * nc
    edges = nm.zeros((nedges, 2), dtype=nm.int16)
    edge_dir = nm.zeros((ncm1 * nr + nrm1 * nc,), dtype=nm.bool)
    nodes = nm.zeros((nm.prod(shape), 3), dtype=nm.float32)

    # edges
    idx = 0
    row = nm.zeros((ncm1, 2), dtype=nm.int16)
    row[:, 0] = nm.arange(ncm1)
    row[:, 1] = nm.arange(ncm1) + 1
    for ii in range(nr):
        edges[slice(idx, idx + ncm1), :] = row + nc * ii
        idx += ncm1

    edge_dir[slice(0, idx)] = 0  # horizontal dir

    idx0 = idx
    col = nm.zeros((nrm1, 2), dtype=nm.int16)
    col[:, 0] = nm.arange(nrm1) * nc
    col[:, 1] = nm.arange(nrm1) * nc + nc
    for ii in range(nc):
        edges[slice(idx, idx + nrm1), :] = col + ii
        idx += nrm1

    edge_dir[slice(idx0, idx)] = 1  # vertical dir

    # nodes
    idx = 0
    row = nm.zeros((nc, 3), dtype=nm.float32)
    row[:, 0] = voxelsize[0] * (nm.arange(nc) + 0.5)
    row[:, 1] = voxelsize[1] * 0.5
    for ii in range(nr):
        nodes[slice(idx, idx + nc), :] = row
        row[:, 1] += voxelsize[1]
        idx += nc

    return nodes, edges, edge_dir
1366098
def make_imshow_plot(grid, name):
    
    plt.tick_params(labelbottom="off", labeltop="off", labelleft="off",
                    labelright="off", bottom="off", top="off", left="off",
                    right="off")
    plt.imshow(grid, interpolation="nearest", aspect=1, zorder=1)
    plt.tight_layout()
    plt.savefig(name, dpi=1000, bbox_inches="tight")
1236232
def plot(data: Dict[str, np.array], fields: List[str] = None, *args, **kwargs):
    
    if plt is None:
        return

    if fields is None:
        fields = ['x', 'y', 'm', 'c']
    labels = []
    lines = []
    for field in fields:
        if min(data[field].shape) > 0:
            f_lines = plt.plot(data['t'], data[field], *args, **kwargs)
            lines.extend(f_lines)
            labels.extend(data['labels'][field])
    plt.legend(lines, labels, ncol=2, loc='best')
    plt.xlabel('t, sec')
    plt.grid()
1041475
def plot_grid(step):
    
    rad = get_rprof(step, 'r')[0]
    drad = get_rprof(step, 'dr')[0]
    _, unit = step.sdat.scale(1, 'm')
    if unit:
        unit = ' ({})'.format(unit)
    fig, (ax1, ax2) = plt.subplots(2, sharex=True)
    ax1.plot(rad, '-ko')
    ax1.set_ylabel('$r$' + unit)
    ax2.plot(drad, '-ko')
    ax2.set_ylabel('$dr$' + unit)
    ax2.set_xlim([-0.5, len(rad) - 0.5])
    ax2.set_xlabel('Cell number')
    misc.saveplot(fig, 'grid', step.istep)
669708
def parallel_plot(df, color=None, palette=None):
    
    npts = df.shape[0]
    ndims = len(df.columns)

    if color is None:
        color = np.ones(npts)
    if palette is None:
        palette = ['#ff0000']

    cmap = LinearColorMapper(high=color.min(),
                             low=color.max(),
                             palette=palette)

    data_source = ColumnDataSource(dict(
        xs=np.arange(ndims)[None, :].repeat(npts, axis=0).tolist(),
        ys=np.array((df-df.min())/(df.max()-df.min())).tolist(),
        color=color))

    p = figure(x_range=(-1, ndims),
               y_range=(0, 1),
               width=1000,
               tools="pan, box_zoom")

    # Create x axis ticks from columns contained in dataframe
    fixed_x_ticks = FixedTicker(
        ticks=np.arange(ndims), minor_ticks=[])
    formatter_x_ticks = FuncTickFormatter(
        code="return columns[index]", args={"columns": df.columns})
    p.xaxis.ticker = fixed_x_ticks
    p.xaxis.formatter = formatter_x_ticks

    p.yaxis.visible = False
    p.y_range.start = 0
    p.y_range.end = 1
    p.y_range.bounds = (-0.1, 1.1) # add a little padding around y axis
    p.xgrid.visible = False
    p.ygrid.visible = False

    # Create extra y axis for each dataframe column
    tickformatter = BasicTickFormatter(precision=1)
    for index, col in enumerate(df.columns):
        start = df[col].min()
        end = df[col].max()
        bound_min = start + abs(end-start) * (p.y_range.bounds[0] - p.y_range.start)
        bound_max = end + abs(end-start) * (p.y_range.bounds[1] - p.y_range.end)
        p.extra_y_ranges.update(
            {col: Range1d(start=bound_min, end=bound_max, bounds=(bound_min, bound_max))})

        fixedticks = FixedTicker(
            ticks=np.linspace(start, end, 8), minor_ticks=[])

        p.add_layout(LinearAxis(fixed_location=index, y_range_name=col,
                                ticker=fixedticks, formatter=tickformatter), 'right')

    # create the data renderer ( MultiLine )
    # specify selected and non selected style
    non_selected_line_style = dict(line_color='grey', line_width=0.1, line_alpha=0.5)

    selected_line_style = dict(line_color={'field': 'color', 'transform': cmap}, line_width=1)

    parallel_renderer = p.multi_line(
        xs="xs", ys="ys", source=data_source, **non_selected_line_style)

    # Specify selection style
    selected_lines = MultiLine(**selected_line_style)

    # Specify non selection style
    nonselected_lines = MultiLine(**non_selected_line_style)

    parallel_renderer.selection_glyph = selected_lines
    parallel_renderer.nonselection_glyph = nonselected_lines
    p.y_range.start = p.y_range.bounds[0]
    p.y_range.end = p.y_range.bounds[1]

    rect_source = ColumnDataSource({
        'x': [], 'y': [], 'width': [], 'height': []
    })

    # add rectangle selections
    selection_renderer = p.rect(x='x', y='y', width='width', height='height',
                                source=rect_source,
                                fill_alpha=0.7, fill_color='#009933')
    selection_tool = ParallelSelectionTool(
        renderer_select=selection_renderer, renderer_data=parallel_renderer,
        box_width=10)
    # custom resets (reset only axes not selections)
    reset_axes = ParallelResetTool()

    # add tools and activate selection ones
    p.add_tools(selection_tool, reset_axes)
    p.toolbar.active_drag = selection_tool
    return p
842082
def make_plots(datadf, settings):
    '''
    
    '''
    plot_settings = dict(font_scale=settings["font_scale"])
    nanoplotter.plot_settings(plot_settings, dpi=settings["dpi"])
    color = nanoplotter.check_valid_color(settings["color"])
    plotdict = {type: settings["plots"].count(type) for type in ["kde", "hex", "dot", 'pauvre']}
    plots = []
    if settings["N50"]:
        n50 = nanomath.get_N50(np.sort(datadf["lengths"]))
    else:
        n50 = None
    plots.extend(
        nanoplotter.length_plots(
            array=datadf[datadf["length_filter"]]["lengths"],
            name="Read length",
            path=settings["path"],
            n50=n50,
            color=color,
            figformat=settings["format"],
            title=settings["title"])
    )
    logging.info("Created length plots")
    if "quals" in datadf:
        plots.extend(
            nanoplotter.scatter(
                x=datadf[datadf["length_filter"]][settings["lengths_pointer"]],
                y=datadf[datadf["length_filter"]]["quals"],
                names=['Read lengths', 'Average read quality'],
                path=settings["path"] + "LengthvsQualityScatterPlot",
                color=color,
                figformat=settings["format"],
                plots=plotdict,
                log=settings["logBool"],
                title=settings["title"],
                plot_settings=plot_settings)
        )
        logging.info("Created LengthvsQual plot")
    if "channelIDs" in datadf:
        plots.extend(
            nanoplotter.spatial_heatmap(
                array=datadf["channelIDs"],
                title=settings["title"],
                path=settings["path"] + "ActivityMap_ReadsPerChannel",
                color="Greens",
                figformat=settings["format"])
        )
        logging.info("Created spatialheatmap for succesfull basecalls.")
    if "start_time" in datadf:
        plots.extend(
            nanoplotter.time_plots(
                df=datadf,
                path=settings["path"],
                color=color,
                figformat=settings["format"],
                title=settings["title"],
                log_length=settings["logBool"],
                plot_settings=plot_settings)
        )
        logging.info("Created timeplots.")
    if "aligned_lengths" in datadf and "lengths" in datadf:
        plots.extend(
            nanoplotter.scatter(
                x=datadf[datadf["length_filter"]]["aligned_lengths"],
                y=datadf[datadf["length_filter"]]["lengths"],
                names=["Aligned read lengths", "Sequenced read length"],
                path=settings["path"] + "AlignedReadlengthvsSequencedReadLength",
                figformat=settings["format"],
                plots=plotdict,
                color=color,
                title=settings["title"],
                plot_settings=plot_settings)
        )
        logging.info("Created AlignedLength vs Length plot.")
    if "mapQ" in datadf and "quals" in datadf:
        plots.extend(
            nanoplotter.scatter(
                x=datadf["mapQ"],
                y=datadf["quals"],
                names=["Read mapping quality", "Average basecall quality"],
                path=settings["path"] + "MappingQualityvsAverageBaseQuality",
                color=color,
                figformat=settings["format"],
                plots=plotdict,
                title=settings["title"],
                plot_settings=plot_settings)
        )
        logging.info("Created MapQvsBaseQ plot.")
        plots.extend(
            nanoplotter.scatter(
                x=datadf[datadf["length_filter"]][settings["lengths_pointer"]],
                y=datadf[datadf["length_filter"]]["mapQ"],
                names=["Read length", "Read mapping quality"],
                path=settings["path"] + "MappingQualityvsReadLength",
                color=color,
                figformat=settings["format"],
                plots=plotdict,
                log=settings["logBool"],
                title=settings["title"],
                plot_settings=plot_settings)
        )
        logging.info("Created Mapping quality vs read length plot.")
    if "percentIdentity" in datadf:
        minPID = np.percentile(datadf["percentIdentity"], 1)
        if "aligned_quals" in datadf:
            plots.extend(
                nanoplotter.scatter(
                    x=datadf["percentIdentity"],
                    y=datadf["aligned_quals"],
                    names=["Percent identity", "Average Base Quality"],
                    path=settings["path"] + "PercentIdentityvsAverageBaseQuality",
                    color=color,
                    figformat=settings["format"],
                    plots=plotdict,
                    stat=stats.pearsonr,
                    minvalx=minPID,
                    title=settings["title"],
                    plot_settings=plot_settings)
            )
            logging.info("Created Percent ID vs Base quality plot.")
        plots.extend(
            nanoplotter.scatter(
                x=datadf[datadf["length_filter"]][settings["lengths_pointer"]],
                y=datadf[datadf["length_filter"]]["percentIdentity"],
                names=["Aligned read length", "Percent identity"],
                path=settings["path"] + "PercentIdentityvsAlignedReadLength",
                color=color,
                figformat=settings["format"],
                plots=plotdict,
                stat=stats.pearsonr,
                log=settings["logBool"],
                minvaly=minPID,
                title=settings["title"],
                plot_settings=plot_settings)
        )
        logging.info("Created Percent ID vs Length plot")
    return plots
1011809
def match_plot(plotdata, outfile):
    
    fig_h = 2 
    fig_w = 7

    nrows = len(plotdata)
    ncols = 2
    fig = plt.figure(figsize=(fig_w, nrows * fig_h))
    
    for i, (motif, dbmotif, pval) in enumerate(plotdata):
        text = "Motif: %s\nBest match: %s\np-value: %0.2e" % (motif.id, dbmotif.id, pval)
        

        grid = ImageGrid(fig, (nrows, ncols, i * 2 + 1), 
                         nrows_ncols = (2,1),
                         axes_pad=0, 
                         )

        for j in range(2):  
            axes_off(grid[j])

        tmp = NamedTemporaryFile(dir=mytmpdir(), suffix=".png")
        motif.to_img(tmp.name, fmt="PNG", height=6)
        grid[0].imshow(plt.imread(tmp.name), interpolation="none")
        tmp = NamedTemporaryFile(dir=mytmpdir(), suffix=".png")
        dbmotif.to_img(tmp.name, fmt="PNG")
        grid[1].imshow(plt.imread(tmp.name), interpolation="none")

        ax = plt.subplot(nrows, ncols, i * 2 + 2)
        axes_off(ax)

        ax.text(0, 0.5, text,
        horizontalalignment='left',
        verticalalignment='center') 
    
    plt.savefig(outfile, dpi=300, bbox_inches='tight')
    plt.close(fig)
808029
def _plot(self, xticks=[], yticks=[], minor_xticks=[], minor_yticks=[],
              xlabel='Longitude', ylabel='Latitude', ax=None, ax2=None,
              colorbar=None, cb_label=None, cb_orientation=None, grid=False,
              axes_labelsize=None, tick_labelsize=None, **kwargs):
        """"""
        if ax is None:
            if colorbar is True:
                if cb_orientation == 'horizontal':
                    scale = 1.5
                else:
                    scale = 1.1
            else:
                scale = 1.2
            figsize = (_mpl.rcParams['figure.figsize'][0],
                       _mpl.rcParams['figure.figsize'][0]*scale)
            fig, axes = _plt.subplots(2, 1, figsize=figsize)
            axreal = axes.flat[0]
            axcomplex = axes.flat[1]
        else:
            axreal = ax
            axcomplex = ax2

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

        cim1 = axreal.imshow(self.data.real, origin='upper',
                             extent=(0., 360., -90., 90.), **kwargs)
        axreal.set(title='Real component', xticks=xticks, yticks=yticks)
        axreal.set_xlabel(xlabel, fontsize=axes_labelsize)
        axreal.set_ylabel(ylabel, fontsize=axes_labelsize)
        axreal.set_xticklabels(xticklabels, fontsize=tick_labelsize)
        axreal.set_yticklabels(yticklabels, fontsize=tick_labelsize)
        axreal.set_xticks(minor_xticks, minor=True)
        axreal.set_yticks(minor_yticks, minor=True)
        axreal.grid(grid, which='major')
        cim2 = axcomplex.imshow(self.data.imag, origin='upper',
                                extent=(0., 360., -90., 90.), **kwargs)
        axcomplex.set(title='Imaginary component', xticks=xticks,
                      yticks=yticks)
        axcomplex.set_xlabel(xlabel, fontsize=axes_labelsize)
        axcomplex.set_ylabel(ylabel, fontsize=axes_labelsize)
        axcomplex.set_xticklabels(xticklabels, fontsize=tick_labelsize)
        axcomplex.set_yticklabels(yticklabels, fontsize=tick_labelsize)
        axcomplex.set_xticks(minor_xticks, minor=True)
        axcomplex.set_yticks(minor_yticks, minor=True)
        axcomplex.grid(grid, which='major')

        if colorbar is True:
            if cb_orientation == 'vertical':
                divider1 = _make_axes_locatable(axreal)
                cax1 = divider1.append_axes("right", size="2.5%", pad=0.05)
                cbar1 = _plt.colorbar(cim1, cax=cax1,
                                      orientation=cb_orientation)
                divider2 = _make_axes_locatable(axcomplex)
                cax2 = divider2.append_axes("right", size="2.5%", pad=0.05)
                cbar2 = _plt.colorbar(cim2, cax=cax2,
                                      orientation=cb_orientation)
            else:
                divider1 = _make_axes_locatable(axreal)
                cax1 = divider1.append_axes("bottom", size="5%", pad=0.5)
                cbar1 = _plt.colorbar(cim1, cax=cax1,
                                      orientation=cb_orientation)
                divider2 = _make_axes_locatable(axcomplex)
                cax2 = divider2.append_axes("bottom", size="5%", pad=0.5)
                cbar2 = _plt.colorbar(cim2, cax=cax2,
                                      orientation=cb_orientation)

            if cb_label is not None:
                cbar1.set_label(cb_label, fontsize=axes_labelsize)
                cbar2.set_label(cb_label, fontsize=axes_labelsize)
            cbar1.ax.tick_params(labelsize=tick_labelsize)
            cbar2.ax.tick_params(labelsize=tick_labelsize)

        if ax is None:
            return fig, axes
1054900
def plot_diagrams(results, configs, compiler, out_dir):
    """"""
    compiler_fn = make_filename(compiler)
    total = psutil.virtual_memory().total  # pylint:disable=I0011,E1101
    memory = int(math.ceil(byte_to_gb(total)))

    images_dir = os.path.join(out_dir, 'images')

    for config in configs:
        out_prefix = '{0}_{1}'.format(config['name'], compiler_fn)

        plot_diagram(
            config,
            results,
            images_dir,
            os.path.join(images_dir, '{0}.png'.format(out_prefix))
        )

        with open(
            os.path.join(out_dir, '{0}.qbk'.format(out_prefix)),
            'wb'
        ) as out_f:
            qbk_content = """{0}
Measured on a {2} host with {3} GB memory. Compiler used: {4}.

[$images/metaparse/{1}.png [width 100%]]
""".format(config['desc'], out_prefix, platform.platform(), memory, compiler)
            out_f.write(qbk_content)