Example #1
0
def quickPlot(filename, path, datalist, xlabel="x", ylabel="y", xrange=["auto", "auto"], yrange=["auto", "auto"], yscale="linear", xscale="linear", col=["r", "b"]):
	"""Plots Data to .pdf File in Plots Folder Using matplotlib"""
	if "plots" not in os.listdir(path):
		os.mkdir(os.path.join(path, "plots"))
	coltab = col*10
	seaborn.set_context("notebook", rc={"lines.linewidth": 1.0})
	formatter = ScalarFormatter(useMathText=True)
	formatter.set_scientific(True)
	formatter.set_powerlimits((-2, 3))
	fig = Figure(figsize=(6, 6))
	ax = fig.add_subplot(111)
	for i, ydata in enumerate(datalist[1:]):
		ax.plot(datalist[0], ydata, c=coltab[i])
	ax.set_title(filename)
	ax.set_yscale(yscale)
	ax.set_xscale(xscale)
	ax.set_xlabel(xlabel)
	ax.set_ylabel(ylabel)
	if xrange[0] != "auto":
		ax.set_xlim(xmin=xrange[0])
	if xrange[1] != "auto":
		ax.set_xlim(xmax=xrange[1])
	if yrange[0] != "auto":
		ax.set_ylim(ymin=yrange[0])
	if yrange[1] != "auto":
		ax.set_ylim(ymax=yrange[1])
	if yscale == "linear":
		ax.yaxis.set_major_formatter(formatter)
	ax.xaxis.set_major_formatter(formatter)
	canvas = FigureCanvasPdf(fig)
	canvas.print_figure(os.path.join(path, "plots", filename+".pdf"))
	return
Example #2
0
def backtest_plot(account_value,
                  baseline_start=config.START_TRADE_DATE,
                  baseline_end=config.END_DATE,
                  baseline_ticker="^DJI",
                  positions=None,
                  transactions=None,
                  value_col_name="account_value"):

    df = deepcopy(account_value)
    test_returns = get_daily_return(df, value_col_name=value_col_name)

    baseline_df = get_baseline(baseline_ticker, baseline_start, baseline_end)
    baseline_returns = get_daily_return(baseline_df, value_col_name="close")
    baseline_returns = baseline_returns.reindex(pd.date_range(
        start=test_returns.index.min(), end=test_returns.index.max()),
                                                fill_value=0)

    with pyfolio.plotting.plotting_context(font_scale=1.1):
        figs = pyfolio.create_full_tear_sheet(positions=positions,
                                              transactions=transactions,
                                              returns=test_returns,
                                              benchmark_rets=baseline_returns,
                                              set_context=False,
                                              return_figs=True)
    now = datetime.now().strftime(config.DATETIME_FMT)
    with PdfPages(
            f'./{config.RESULTS_DIR}/full_tear_sheet_{now}.pdf') as pages:
        for fig in figs:
            canvas = FigureCanvasPdf(fig)
            canvas.print_figure(pages)
Example #3
0
def plot_2(plotdata, filename, title, use_offset=False):
    f = mpl.figure.Figure(figsize=(11, 8.5))
    canvas = FigureCanvasPdf(f)
    f.suptitle(title)
    gs = GridSpec(len(plotdata), 1)
    gs.update(left=0.05, right=0.94, wspace=0.05)
    i = 0
    offset = 0
    for newdata, refdata, invert, series_no in plotdata:
        ax1 = f.add_subplot(gs[i, :])
        ax2 = ax1.twinx()
        data = newdata.match.rate().data
        ax2.plot(data[0], data[1], color='#e0b040', linewidth=2.0,
                 linestyle='-', marker='+', markeredgewidth=2.0)
        ax2max = ax2.get_ylim()[1]
        ax2.set_ylim([0, ax2max * 2])
        ax1.set_ylabel(newdata.series1[series_no].get_name())
        data = newdata.series1[series_no].data
        if use_offset:
            offset = -newdata.series1[series_no].std()*2
            if invert:
                offset = -offset
        ax1.plot(refdata.data[0], refdata.data[1]+offset, linewidth=2.0,
                 color='#9090ff')
        ax1.plot(data[0], data[1], color='black', linewidth=0.75)
        ax1.set_zorder(ax2.get_zorder()+1)  # put ax in front of ax2
        ax1.patch.set_visible(False)  # hide the 'canvas'
        if invert:
            ax1.invert_yaxis()
        i = i + 1
    canvas.print_figure(filename)
Example #4
0
def make_plot(seriess, filename, title=None, invert=False):
    f = mpl.figure.Figure(figsize=(11, 8.5))
    canvas = FigureCanvasPdf(f)
    if title:
        f.suptitle(title)

    gs = GridSpec(len(seriess), 1)
    gs.update(left=0.05, right=0.94, wspace=0.05)
    for i in range(0, len(seriess)):
        s = seriess[i]
        if isinstance(s, (list, tuple)):
            ax1 = f.add_subplot(gs[i, :])
            ax2 = ax1.twinx()
            ax2.plot(s[1].data[0],
                     s[1].data[1],
                     color='#aaaaaa',
                     linewidth=5.0)
            ax1.set_ylabel(s[0].get_name())
            ax1.plot(s[0].data[0], s[0].data[1], color='black')
            ax1.set_zorder(ax2.get_zorder() + 1)  # put ax in front of ax2
            ax1.patch.set_visible(False)  # hide the 'canvas'
            if invert:
                ax1.invert_yaxis()
                ax2.invert_yaxis()
        else:
            ax = f.add_subplot(gs[i, :])
            ax.set_ylabel(s.get_name())
            ax.plot(s.data[0], s.data[1], color='black')
            if invert:
                ax.invert_yaxis()

    canvas.print_figure(filename)
Example #5
0
def plotPolygon(tri, polyPoints, nodeID, xRange, yRange):
    """Plots the voronoi polygon around a single node."""
    fig = Figure(figsize=(4,4))
    canvas = FigureCanvas(fig)
    fig.subplots_adjust(left=0.15, bottom=0.13,wspace=0.25, right=0.95)
    ax = fig.add_subplot(111, aspect='equal')
    
    ax.plot(tri.x, tri.y, '.k', ms=1)
    ax.plot(tri.x[nodeID], tri.y[nodeID],'.r', ms=2)
    # print polyPoints[nodeID]
    patch = matplotlib.patches.Polygon(polyPoints[nodeID], closed=True, fill=True, lw=1)
    ax.add_patch(patch)
    # ax.plot(tri.x, tri.y, '.k')
    ax.set_xlim(xRange)
    ax.set_ylim(yRange)
    canvas.print_figure("cell", dpi=300.)
Example #6
0
def main(args):
	table = read_table(args.table)

	# Discard rows with any mutation within J at all
	logger.info('%s rows read', len(table))
	if not args.ignore_J:
		# Discard rows with any mutation within J at all
		table = table[table.J_SHM == 0][:]
		logger.info('%s rows remain after discarding J%%SHM > 0', len(table))

	if args.minimum_group_size is None:
		total = len(table)
		minimum_group_size = min(total // 1000, 100)
		logger.info('Skipping genes with less than %s assignments', minimum_group_size)
	else:
		minimum_group_size = args.minimum_group_size
	n = 0
	too_few = 0
	with PdfPages(args.pdf) as pages:
		for gene, group in table.groupby('V_gene'):
			if len(group) < minimum_group_size:
				too_few += 1
				continue
			fig = plot_difference_histogram(group, gene)
			n += 1
			FigureCanvasPdf(fig).print_figure(pages, bbox_inches='tight')
	logger.info('%s plots created (%s skipped because of too few sequences)', n, too_few)
def write_figures(prefix, directory, dose_name, dose_data, data, ec50_coeffs,
                  feature_set, log_transform):
    '''Write out figure scripts for each measurement

    prefix - prefix for file names
    directory - write files into this directory
    dose_name - name of the dose measurement
    dose_data - doses per image
    data - data per image
    ec50_coeffs - coefficients calculated by calculate_ec50
    feature_set - tuples of object name and feature name in same order as data
    log_transform - true to log-transform the dose data
    '''
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_pdf import FigureCanvasPdf

    if log_transform:
        dose_data = np.log(dose_data)
    for i, (object_name, feature_name) in enumerate(feature_set):
        fdata = data[:, i]
        fcoeffs = ec50_coeffs[i, :]
        filename = "%s%s_%s.pdf" % (prefix, object_name, feature_name)
        pathname = os.path.join(directory, filename)
        f = Figure()
        canvas = FigureCanvasPdf(f)
        ax = f.add_subplot(1, 1, 1)
        x = np.linspace(0, np.max(dose_data), num=100)
        y = sigmoid(fcoeffs, x)
        ax.plot(x, y)
        dose_y = sigmoid(fcoeffs, dose_data)
        ax.plot(dose_data, dose_y, "o")
        ax.set_xlabel('Dose')
        ax.set_ylabel('Response')
        ax.set_title('%s_%s' % (object_name, feature_name))
        f.savefig(pathname)
Example #8
0
  def canvas(self):
    type = self.get("imageType", "png")
    fig = Figure()
    if type == "png":
      canvas = FigureCanvasAgg(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "svg":
      canvas = FigureCanvasSVG(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "pdf":
      canvas = FigureCanvasPdf(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "ps" or type == "eps":
      canvas = FigureCanvasPS(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    else:
      raise "Invalid render target requested"

    # Set basic figure parameters
    dpi = float(self.get('dpi'))
    (w, h) = (float(self.get('width')), float(self.get('height')))
    (win, hin) = (w/dpi, h/dpi)
    fig.set_size_inches(win, hin)
    fig.set_dpi(dpi)
    fig.set_facecolor('white')
    return (fig, canvas, w, h)
Example #9
0
    def output(self, file_suffix):

        if self.wide:
            left_text = self.header + '\n' + self.ts.title
            text_len = len(left_text.split('\n'))
            fontsize = self.ax.yaxis.label.get_size()
            linespacing = 1.2
            fontrate = float(fontsize * linespacing) / 72. / 15.5
            yloc = .8 - fontrate * (
                text_len - 1)  # this doesn't quite work. fontrate is too
            # small by a small amount
            self.fig.text(.05, yloc, left_text, linespacing=linespacing)
            self.fname = '_'.join([
                self.prefix, self.ts.j.id, self.ts.owner, 'wide_' + file_suffix
            ])
        elif self.header != None:
            title = self.header + '\n' + self.ts.title
            if self.threshold:
                title += ', V: %(v)-6.1f' % {'v': self.threshold}
            self.fig.suptitle(title)
            self.fname = '_'.join(
                [self.prefix, self.ts.j.id, self.ts.owner, file_suffix])
        else:
            self.fname = '_'.join(
                [self.prefix, self.ts.j.id, self.ts.owner, file_suffix])

        if self.mode == 'hist':
            self.fname += '_hist'
        elif self.mode == 'percentile':
            self.fname += '_perc'
        if not self.save:
            self.canvas = FigureCanvasAgg(self.fig)
        else:
            self.canvas = FigureCanvasPdf(self.fig)
            self.fig.savefig(os.path.join(self.outdir, self.fname))
Example #10
0
def test_no_pyplot():
    # tests pickle-ability of a figure not created with pyplot
    from matplotlib.backends.backend_pdf import FigureCanvasPdf
    fig = mfigure.Figure()
    _ = FigureCanvasPdf(fig)
    ax = fig.add_subplot(1, 1, 1)
    ax.plot([1, 2, 3], [1, 2, 3])
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
Example #11
0
def main(args):
    table = read_table(
        args.table, usecols=['V_gene', 'J_gene', 'V_SHM', 'J_SHM', 'CDR3_nt'])
    if not args.multi and not args.boxplot:
        print('Don’t know what to do', file=sys.stderr)
        sys.exit(2)

    # Discard rows with any mutation within J at all
    logger.info('%s rows read', len(table))
    if args.max_j_shm is not None:
        # Discard rows with too many J mutations
        table = table[table.J_SHM <= args.max_j_shm][:]
        logger.info(
            '%s rows remain after keeping only those with J%%SHM <= %s',
            len(table), args.max_j_shm)

    if args.minimum_group_size is None:
        total = len(table)
        minimum_group_size = min(total // 1000, 100)
        logger.info('Skipping genes with less than %s assignments',
                    minimum_group_size)
    else:
        minimum_group_size = args.minimum_group_size

    # Genes with high enough assignment count
    all_genes = table['V_gene'].unique()
    genes = sorted(table['V_gene'].value_counts().
                   loc[lambda x: x >= minimum_group_size].index)
    gene_set = set(genes)

    logger.info('%s out of %s genes have enough assignments', len(genes),
                len(all_genes))
    if args.multi:
        with PdfPages(args.multi) as pages:
            for gene, group in table.groupby('V_gene'):
                if gene not in gene_set:
                    continue
                fig = plot_difference_histogram(group, gene)
                FigureCanvasPdf(fig).print_figure(pages, bbox_inches='tight')

        logger.info('Wrote %r', args.multi)

    if args.boxplot:
        aspect = 1 + len(genes) / 32
        g = sns.catplot(x='V_gene',
                        y='V_SHM',
                        kind='boxen',
                        order=genes,
                        data=table,
                        height=2 * 2.54,
                        aspect=aspect,
                        color='g')
        # g.set(ylim=(-.1, None))
        g.set(ylabel='% V SHM (nt)')
        g.set(xlabel='V gene')
        g.set_xticklabels(rotation=90)
        g.savefig(args.boxplot)
        logger.info('Wrote %r', args.boxplot)
Example #12
0
def download_plot_experiment(request, exp_id, plottype="box"):
    exp = get_object_or_404(models.Experiment, pk=exp_id)
    data, ndatamax = gather_measures(exp)

    fig = plt.Figure()
    if plottype == "box":
        ax = fig.add_subplot(111)
        ax = plot.make_box_plot(ax, data)
    else:
        fig = plot.make_hist_plot(fig, data)

    filename = "%s.pdf" % exp.name.replace(" ", "_")

    canvas = FigureCanvasPdf(fig)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    canvas.print_figure(response)
    return response
Example #13
0
    def PlotGraphPDF(self):
        '''
        PDFにグラフを描画する関数
        '''
        from matplotlib.backends.backend_pdf import FigureCanvasPdf
        from matplotlib.backends.backend_pdf import PdfPages  # PDFを作成するモジュールの読込
        import os

        if self.GraphDataExist:
            iDir = os.getcwd()  #カレントディレクトリーの読込
            iFile = 'test.pdf'
            openFileDialog = wx.FileDialog(self, "PDFファイルの保存", iDir, iFile,
                                           "PDF files (*.pdf)|*.pdf",
                                           wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)

            _filename = ''
            openFileDialog.ShowModal()
            _filename = openFileDialog.GetPath()
            if _filename != '':
                #         from matplotlib.figure import Figure
                #         if event == wx.EVT_BUTTON:
                #             print(event)

                #         self.figure = Figure(  None )    # Figure(グラフの台紙)オブジェクトを生成
                self.figure.set_size_inches(298. / 25.4, 210. / 25.4, True)
                self.figure.set_dpi(600)
                self.figure.set_facecolor((0.7, 0.7, 1.0))  # Figureの表面色を設定

                pdf1 = PdfPages(_filename)
                self.canvas = FigureCanvasPdf(
                    self.figure)  # Canvas(グラフ)オブジェクトをfigure上に生成

                #         Draw_Graph(self.figure)

                pdf1.savefig(self.figure)
                pdf1.close()
            else:
                print('Print Cancel')
        else:
            dlg = wx.MessageDialog(self, '作図データがありません', '警告',
                                   wx.OK | wx.ICON_WARNING)
            dlg.ShowModal()
            dlg.Destroy()
Example #14
0
def save_as_pdf(x, y, xlim, figsize):
    """Create and save a PDF file from plot data.

    Currently, it doesn't seem possible to select landscape vs. portrait for
    PDF. Try _save_as_eps if that feature is important.

    :param x: (numpy ndarray)
    :param y: (numpy ndarray)
    :param xlim: (float, float) a tuple of
    (max chemical shift, min chemical shift)
    :param figsize: (float, float) a tuple of (plot width, plot height) in
    inches.
    """
    figure = _create_figure(x, y, xlim, figsize)
    backend = FigureCanvasPdf(figure)
    filename = asksaveasfilename()
    if filename:
        if filename[-4:] != '.pdf':
            filename += '.pdf'
        backend.print_pdf(filename)
Example #15
0
def quickPlot(filename,
              path,
              datalist,
              xlabel="x",
              ylabel="y",
              xrange=["auto", "auto"],
              yrange=["auto", "auto"],
              yscale="linear",
              xscale="linear",
              col=["r", "b"]):
    """Plots Data to .pdf File in Plots Folder Using matplotlib"""
    if "plots" not in os.listdir(path):
        os.mkdir(os.path.join(path, "plots"))
    coltab = col * 10
    seaborn.set_context("notebook", rc={"lines.linewidth": 1.0})
    formatter = ScalarFormatter(useMathText=True)
    formatter.set_scientific(True)
    formatter.set_powerlimits((-2, 3))
    fig = Figure(figsize=(6, 6))
    ax = fig.add_subplot(111)
    for i, ydata in enumerate(datalist[1:]):
        ax.plot(datalist[0], ydata, c=coltab[i])
    ax.set_title(filename)
    ax.set_yscale(yscale)
    ax.set_xscale(xscale)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    if xrange[0] != "auto":
        ax.set_xlim(xmin=xrange[0])
    if xrange[1] != "auto":
        ax.set_xlim(xmax=xrange[1])
    if yrange[0] != "auto":
        ax.set_ylim(ymin=yrange[0])
    if yrange[1] != "auto":
        ax.set_ylim(ymax=yrange[1])
    if yscale == "linear":
        ax.yaxis.set_major_formatter(formatter)
    ax.xaxis.set_major_formatter(formatter)
    canvas = FigureCanvasPdf(fig)
    canvas.print_figure(os.path.join(path, "plots", filename + ".pdf"))
    return
Example #16
0
def run():
    args = get_args()
    roofile = up.open(args.input_file)
    outdir = args.output_dir
    if not path.isdir(outdir):
        mkdir(outdir)

    for name, hist in roofile.items():
        short_name = name.decode('utf-8').split(';')[0]
        print(f'drawing {short_name}')
        # set up canvas and figure
        fig = Figure(figsize=(5, 3))
        can = FigCanvas(fig)
        ax = fig.add_subplot(1, 1, 1)

        # add a plot
        vals, edges = hist.numpy
        centers = (edges[:-1] + edges[1:]) / 2
        ax.plot(centers, vals)
        ax.set_yscale('log')
        can.print_figure(f'{outdir}/{short_name}.pdf')
Example #17
0
    def finalize(self, key):
        logi = self.instances.pop(key)

        from matplotlib.figure import Figure
        from matplotlib.backends.backend_pdf import FigureCanvasPdf

        fig = Figure(figsize=(6, 8))
        fig.suptitle("%s - order:%d" % (key))
        logi.render(fig)

        FigureCanvasPdf(fig)

        self.pdf.savefig(figure=fig)
Example #18
0
def plot_flattend_a0v(spec_flattener, w, s_orig, of_list, data_list,
                      fout=None):
        print "Now generating figures"

        from matplotlib.backends.backend_pdf import Figure, FigureCanvasPdf
        fig = Figure()
        FigureCanvasPdf(fig)

        ax1 = fig.add_subplot(211)
        ax2 = fig.add_subplot(212, sharex=ax1)

        # data_list = [("flattened_spec", s_orig/continuum_array),
        #              ("wavelength", w),
        #              ("fitted_continuum", continuum_array),
        #              ("mask", mask_array),
        #              ("a0v_norm", a0v_array),
        #              ("model_teltrans", teltrans_array),
        #              ]

        s_a0v = data_list[4][1]
        tt_list = data_list[5][1]
        msk_list = data_list[3][1]
        cont_list = data_list[2][1]

        _interim_result = zip(w, s_orig, of_list, s_a0v, tt_list, msk_list, cont_list)

        for w1, s1_orig, of, s1_a0v, tt1, msk, cont in _interim_result:
            spec_flattener.plot_fitted(w1, s1_orig, s1_a0v, tt1,
                                       msk, msk, cont,
                                       ax1=ax1, ax2=ax2)

        ax2.set_ylim(-0.1, 1.2)
        ax2.axhline(1.0, color="0.8")
        ax2.set_xlabel(r"Wavelength [$\mu$m]")
        ax2.set_ylabel(r"Flattened Spectra")
        ax1.set_ylabel(r"Spectra w/o Blaze function correction")

        from matplotlib.backends.backend_pdf import PdfPages
        if fout is None:
            fout = 'multipage_pdf.pdf'
        with PdfPages(fout) as pdf:
            w = np.array(w)
            wmin, wmax = w.min(), w.max()
            ymax = np.nanmax(s_orig)
            ax1.set_xlim(wmin, wmax)
            ax1.set_ylim(-0.1*ymax, 1.1*ymax)
            pdf.savefig(figure=fig)

            for w1, s1_orig, of, s1_a0v, tt1, msk, cont in _interim_result:
                ax1.set_xlim(min(w1), max(w1))
                pdf.savefig(figure=fig)
Example #19
0
    def print_pdf(self, filename, **kwargs):
        transparent = kwargs.pop('transparent',
                                 rcParams['savefig.transparent'])

        if transparent:
            kwargs.setdefault('facecolor', 'none')
            kwargs.setdefault('edgecolor', 'none')
            original_axes_colors = []

            for ax in self.figure.axes:
                patch = ax.patch
                original_axes_colors.append(
                    (patch.get_facecolor(), patch.get_edgecolor()))
                patch.set_facecolor('none')
                patch.set_edgecolor('none')
        else:
            kwargs.setdefault('facecolor', rcParams['savefig.facecolor'])
            kwargs.setdefault('edgecolor', rcParams['savefig.edgecolor'])

        if 'rv' in THEME:
            self.reverse()

        FigureCanvasPdf.print_pdf(self, filename, **kwargs)
Example #20
0
    def makePDF(self, **params):
        from matplotlib.backends.backend_pdf import PdfPages
        #from pylab import *

        # Create the PdfPages object to which we will save the pages:
        imdata = StringIO()
        # should write to string buffer
        pdf = PdfPages(os.path.join(
            self.workDir, 'figures.pdf'))  #imdata) #'multipage_pdf.pdf')

        fig = self.heatmap()
        FigureCanvasPdf(fig)  # this constructor sets the figures canvas...
        pdf.savefig(fig)

        fig = self.histogram()
        FigureCanvasPdf(fig)  # this constructor sets the figures canvas...
        pdf.savefig(fig)  # here's another way - or you could do pdf.savefig(1)

        fig = self.plot()
        FigureCanvasPdf(fig)  # this constructor sets the figures canvas...
        pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig

        fig = self.duration()
        FigureCanvasPdf(fig)  # this constructor sets the figures canvas...
        pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig

        # We can also set the file's metadata via the PdfPages object:
        d = pdf.infodict()
        d['Title'] = 'Energy Fingerprint Report'
        d['Author'] = 'LBNL Energy Fingerprint Server'
        d['Subject'] = 'Visual summary of energy data with suggestions'
        d['Keywords'] = 'Green Button, Energy data, Fingerprint, LBNL'
        d['CreationDate'] = datetime.datetime.today()
        d['ModDate'] = datetime.datetime.today()

        # Remember to close the object - otherwise the file will not be usable
        pdf.close()
Example #21
0
    def EraseGraphWindow(self, panel1=wx.Panel):
        '''
        Windowのpanelのグラフを消去する関数
        '''
        #         print(self.radiobutton_1.GetValue())
        from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
        from matplotlib.figure import Figure
        self.figure = Figure(None)  # Figure(グラフの台紙)オブジェクトを生成
        self.figure.set_facecolor((1.0, 1.0, 1.0))  # Figureの表面色を設定

        #panel2にFigureを貼り付けcanvasを生成
        self.canvas = FigureCanvasWxAgg(panel1, -1, self.figure)
        self.canvas.SetSize(tuple(
            panel1.GetClientSize()))  # canvasのサイズをpanel2に合わせる。

        self.GraphDataExist = False
Example #22
0
def main(args):
	logger.info('Will plot results to %s', args.pdf)
	cdr3_column = 'CDR3_nt' if args.nt else 'CDR3_aa'
	n_datasets = len(args.tables)
	if args.names:
		names = args.names.split(',')
		if len(names) != n_datasets:
			logger.error('%s dataset names given, but %s datasets provided', len(names), n_datasets)
			sys.exit(1)
	else:
		names = list(range(n_datasets))

	datasets = (read_dataset(path, limit=args.limit, minsize=args.minsize) for path in args.tables)
	df = pd.concat(datasets, keys=range(n_datasets), names=['dataset_id'])
	logger.info('Read %s tables', n_datasets)
	df.rename(columns=lambda x: x[:-4], inplace=True)  # Removes _SHM suffix
	cols = ['V_gene', 'J_gene', cdr3_column]
	n = 0
	with PdfPages(args.pdf) as pages:
		for (v_gene, j_gene, cdr3), group in df.groupby(level=cols):
			group = group.reset_index(level=cols, drop=True)
			skip = False
			counter = Counter(group.index)
			for dataset_id in range(n_datasets):
				if counter[dataset_id] < args.minsize:
					skip = True
					break
			if skip:
				continue
			table = group.stack()
			table.index.set_names('region', level=1, inplace=True)
			table.name = 'SHM'
			table = table.reset_index()
			table = table.assign(Dataset=table['dataset_id'].map(lambda i: names[i]))
			g = sns.factorplot(data=table, x='region', y='SHM', hue='Dataset',
				kind='violin', size=16*CM, aspect=2)
			dscounts = ' vs '.join(str(counter[i]) for i in range(n_datasets))
			g.fig.suptitle('V: {} – J: {} – CDR3: {} ({})'.format(v_gene, j_gene, cdr3, dscounts))
			g.set_axis_labels('Region')
			g.set_ylabels('%SHM')
			# g.despine()
			FigureCanvasPdf(g.fig).print_figure(pages, bbox_inches='tight')
			n += 1
			logger.info('Plotted %s clonotypes', n)
Example #23
0
 def plot(self, gridspec=None, figsize=(11, 8.5), filetype="pdf"):
     if gridspec is None:
         gridspec = dict(left=0.05, right=0.94, wspace=0.05)
     nplots = len(self.plotspecs)
     fig = mpl.figure.Figure(figsize=figsize)
     if filetype.lower() == "pdf":
         FigureCanvasPdf(fig)
     elif filetype.lower() == "svg":
         FigureCanvasSVG(fig)
     else:
         raise ValueError("Unknown filetype: %s" % filetype)
     if self.title:
         fig.suptitle(self.title)
     gs = GridSpec(nplots, 1)
     gs.update(**gridspec)
     for i in xrange(0, nplots):
         self.plotspecs[i].plot(fig, gs, i)
     fig.set_size_inches(figsize)
     fig.savefig(self.filename + "." + filetype,
                 format=filetype.lower(), facecolor="none")
Example #24
0
    def draw(self, path=None, show=True):
        self.main_drawing_flow(self.figure)

        if path is None:
            handle, path = tempfile.mkstemp(prefix="tmp_solcore_",
                                            suffix=".%s" %
                                            self.options["format"])

        if self.options["format"].upper() == "PDF":
            self.canvas = FigureCanvasPdf(self.figure)
        else:
            self.canvas = FigureCanvasAgg(self.figure)

        self.canvas.print_figure(path,
                                 dpi=self.options["dpi"],
                                 bbox_extra_artists=self.extra_artists,
                                 bbox_inches='tight')

        if show and not self.suppress_show:
            open_with_os(path)
Example #25
0
    def PlotGraphWindow(self,
                        panel1=wx.Panel,
                        n1=2,
                        m1=2,
                        data=None,
                        Freq=1000.0,
                        SampleN=1000):
        '''
        Windowのpanelにグラフを描画する関数
        '''

        #         if self.GraphDataExist:
        #             self.EraseGraphWindow(panel1)

        #         print(self.radiobutton_1.GetValue())
        #         from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
        #         from matplotlib.figure import Figure
        #         self.figure = Figure(  None )    # Figure(グラフの台紙)オブジェクトを生成
        self.figure.clf(keep_observers=False)
        self.figure.set_facecolor((0.8, 0.8, 0.8))  # Figureの表面色を設定

        #panel2にFigureを貼り付けcanvasを生成
        self.canvas = FigureCanvasWxAgg(panel1, -1, self.figure)
        self.canvas.SetSize(tuple(
            self.Graph_panel.GetClientSize()))  # canvasのサイズをpanel2に合わせる。
        #         print(self.canvas.Size,self.canvas.Position)

        self.canvas.SetBackgroundColour(wx.Colour(
            100, 0, 255))  # Canvasの背景色を設定(これは不要?)
        self.n = n1
        self.m = m1
        #         self.MakeWaveData(self.n * self.m)
        #         self.MakeWaveData(7)

        self.y = data[:, :, int(self.microDAQ_GraphUnitNo.Value) - 1]
        self.x = np.arange(SampleN) / Freq
        Draw_Graph(self.figure, self.n, self.m, self.x, self.y)

        self.GraphDataExist = True
Example #26
0
 def plot(self, gridspec=None, figsize=(11, 8.5), filetype="pdf"):
     if gridspec is None:
         gridspec = dict(left=0.05, right=0.94, wspace=0.05)
     nplots = len(self.plotspecs)
     fig = mpl.figure.Figure(figsize=figsize)
     # We have to create a canvas in order to be able to save the figure,
     # even if we don't assign the object to anything.
     # FigureCanvasBase.__init__ calls figure.set_canvas for us.
     if filetype.lower() == "pdf":
         FigureCanvasPdf(fig)
     elif filetype.lower() == "svg":
         FigureCanvasSVG(fig)
     else:
         raise ValueError("Unknown filetype: %s" % filetype)
     if self.title:
         fig.suptitle(self.title)
     gs = GridSpec(nplots, 1)
     gs.update(**gridspec)
     for i in xrange(0, nplots):
         self.plotspecs[i].plot(fig, gs, i)
     fig.set_size_inches(figsize)
     fig.savefig(self.filename + "." + filetype,
                 format=filetype.lower(),
                 facecolor="none")
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot bars
bar1 = ax.bar(ind, p2p, width, color='r')
bar2 = ax.bar(ind+width, m2l, width, color='b')
rc('font',**font)

# axis labels
ax.set_ylabel('Time (s)', fontsize=10)
ax.set_xlabel('Iteration', fontsize=10)
xticks(arange(min(ind), max(ind)+1, 5.0))
# ax.set_xticklabels( ('8192','32768','131072') )
ax.legend( (bar1[0], bar2[0]), ('P2P', 'M2L'), loc=1 )
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesSolveBreakdown.pdf',dpi=80)

# text on scaling plot
#fig = Figure(figsize=(3,2), dpi=80)
#ax = fig.add_subplot(111)
#asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
#ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
#ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
#loc = (3*N[0]+N[1])/4
#tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
#tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
#ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
#rc('font',**font)
 def pdfData(self,fig):
   canvas=FigureCanvasPdf(fig)
   imdata=StringIO()
   canvas.print_pdf(imdata)
   return imdata.getvalue()
N_8cells = array([16384, 65536])
it_8cells = array([61, 66])

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(7,4), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
bar1 = ax.semilogx(N_2048,cells_2048,c='k',marker='o', ls='-', mfc='w', ms=5, label='')
bar2 = ax.semilogx(N_8192,cells_8192,c='k',marker='o', ls=':', mfc='w', ms=5, label='')
bar3 = ax.semilogx(N_32768,cells_32768,c='k',marker='o', ls='-.', mfc='w', ms=5, label='')
bar4 = ax.semilogx(N_2cells,it_2cells,c='r',marker='o', ls='-', mfc='w', ms=5, label='')
bar5 = ax.semilogx(N_4cells,it_4cells,c='r',marker='o', ls=':', mfc='w', ms=5, label='')
bar6 = ax.semilogx(N_8cells,it_8cells,c='r',marker='o', ls='-.', mfc='w', ms=5, label='')
rc('font',**font)

# axis labels
ax.set_ylabel('Iterations', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.legend( (bar1[0],bar2[0],bar3[0],bar4[0],bar5[0],bar6[0]), ('2048 per cell','8192 per cell','32768 per cell','2 cells','4 cells','8cells'),loc=2)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)



# plot to pdf
canvas.print_figure('EthrocyteMultipleCellIterations.pdf',dpi=80)

Example #30
0
    def save_annotated(self,
                       fname=None,
                       label_fmt=None,
                       text_annotate=None,
                       dpi=100,
                       sigma_clip=None):
        r"""Saves the most recently rendered image of the Scene to disk,
        including an image of the transfer function and and user-defined
        text.

        Once you have created a scene and rendered that scene to an image
        array, this saves that image array to disk with an optional filename.
        If an image has not yet been rendered for the current scene object,
        it forces one and writes it out.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as a bitmap to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)
        dpi: integer, optional
            By default, the resulting image will be the same size as the camera
            parameters.  If you supply a dpi, then the image will be scaled
            accordingly (from the default 100 dpi)
        label_fmt : str, optional
           A format specifier (e.g., label_fmt="%.2g") to use in formatting 
           the data values that label the transfer function colorbar. 
        text_annotate : list of iterables
           Any text that you wish to display on the image.  This should be an
           list containing a tuple of coordinates (in normalized figure 
           coordinates), the text to display, and, optionally, a dictionary of 
           keyword/value pairs to pass through to the matplotlib text() 
           function.

           Each item in the main list is a separate string to write.


        Returns
        -------
            Nothing


        Examples
        --------

        >>> sc.save_annotated("fig.png", 
        ...                   text_annotate=[[(0.05, 0.05),
        ...                                   "t = {}".format(ds.current_time.d),
        ...                                   dict(horizontalalignment="left")],
        ...                                  [(0.5,0.95),
        ...                                   "simulation title",
        ...                                   dict(color="y", fontsize="24",
        ...                                        horizontalalignment="center")]])

        """
        from yt.visualization._mpl_imports import \
            FigureCanvasAgg, FigureCanvasPdf, FigureCanvasPS
        sources = list(itervalues(self.sources))
        rensources = [s for s in sources if isinstance(s, RenderSource)]

        if fname is None:
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, string_types):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = "%s_Render_%s.png" % (basename, field)
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == '':
            suffix = '.png'
            fname = '%s%s' % (fname, suffix)

        self.render()

        # which transfer function?
        rs = rensources[0]
        tf = rs.transfer_function
        label = rs.data_source.ds._get_field_info(rs.field).get_label()

        ax = self._show_mpl(self._last_render.swapaxes(0, 1),
                            sigma_clip=sigma_clip,
                            dpi=dpi)
        self._annotate(ax.axes, tf, rs, label=label, label_fmt=label_fmt)

        # any text?
        if text_annotate is not None:
            f = self._render_figure
            for t in text_annotate:
                xy = t[0]
                string = t[1]
                if len(t) == 3:
                    opt = t[2]
                else:
                    opt = dict()

                # sane default
                if "color" not in opt:
                    opt["color"] = "w"

                ax.axes.text(xy[0],
                             xy[1],
                             string,
                             transform=f.transFigure,
                             **opt)

        suffix = get_image_suffix(fname)

        if suffix == ".png":
            canvas = FigureCanvasAgg(self._render_figure)
        elif suffix == ".pdf":
            canvas = FigureCanvasPdf(self._render_figure)
        elif suffix in (".eps", ".ps"):
            canvas = FigureCanvasPS(self._render_figure)
        else:
            mylog.warning("Unknown suffix %s, defaulting to Agg", suffix)
            canvas = self.canvas

        self._render_figure.canvas = canvas
        self._render_figure.tight_layout()
        self._render_figure.savefig(fname, facecolor='black', pad_inches=0)
              hatch='..' * 2,
              linewidth=1)
bar2 = ax.bar(ind + width,
              s_8192,
              width,
              fill=False,
              edgecolor='k',
              hatch='//' * 2,
              linewidth=1)
bar3 = ax.bar(ind + 2 * width,
              s_32768,
              width,
              fill=False,
              edgecolor='k',
              hatch='x' * 3,
              linewidth=1)

# axis labels
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.set_xticks(ind + 1.5 * width)
ax.set_xticklabels(('2048', '8192', '32768', '131072'))
ax.legend((bar1[0], bar2[0], bar3[0]),
          ('2048 panels/cell', '8192 panels/cell', '32768 panels/cell'),
          loc=2,
          fontsize='small')
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('EthrocyteMultipleCellSpeedup.pdf', dpi=80)
Example #32
0
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N[0]*error[0]/N
ax.loglog(N, error, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp, c='k', marker='None', ls=':', lw=0.8, label=None)
rc('font',**font)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc,N[0]*error[0]/loc))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1],r'N$^{-1}$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')
ax.set_ylabel('Relative error', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
canvas.print_figure('regression_tests/figs/error_energy_molecule_neumann.pdf',dpi=80)

fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
rc('font',**font)
ax.set_ylabel('Total time [s]', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
# set up data
N = 5
t_relax = numpy.array([3.9448, 6.1992, 9.0813, 12.696, 22.055])
t_fixed = numpy.array([7.5261, 12.376, 19.960, 25.412, 37.766])

speedup = t_fixed / t_relax
ind = numpy.arange(N, dtype=int)
width = 0.35

# set up plot
font = {'family':'serif','size':10}
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

print(t_relax,t_fixed)
print(speedup)
# plot log-log
bar1 = ax.bar(ind, t_fixed, width, fill=False, edgecolor='k', hatch='..'*2, linewidth=1)
bar2 = ax.bar(ind+width, t_relax, width, fill=False, edgecolor='k', hatch='/'*4, linewidth=1)

# axis labels
ax.set_ylabel('Time (s)', fontsize=10)
ax.set_xlabel('p', fontsize=10)
ax.set_xticks(ind+width)
ax.set_xticklabels( ('5','8','10','12','15') )
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
ax.legend( (bar1[0], bar2[0]), ('fixed p', 'Relaxed'), loc=2, fontsize='small' )
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceRelaxationP.pdf',dpi=80)
           ms=5, label='non-relaxed, loose parameters')
ax1.loglog(N[-3:], e1_relaxed, c='k', ls='-', lw=0.5, marker='x',
           ms=5, label='relaxed, loose parameters')

ax1.set_xlabel('$N$', fontsize=10)
ax1.set_ylabel('Relative Error')
ax1.legend(loc=1, fontsize=6.5)
ax1.grid('on')
ax1.set_title('1st-kind', fontsize=10)

# right plot: 2nd-kind
ax2 = fig.add_subplot(122)

ax2.loglog(N, e2, c='k', ls='-', lw=1.0, marker='o', mfc='w',
	       ms=5, label='non-relaxed, tight parameters')
ax2.loglog(N[-3:], e2_fixed, c='k', ls='-', lw=0.5, marker='+',
           ms=5, label='non-relaxed, loose parameters')
ax2.loglog(N[-3:], e2_relaxed, c='k', ls='-', lw=0.5, marker='x',
           ms=5, label='relaxed, loose parameters')

ax2.set_xlabel('$N$', fontsize=10)
ax2.legend(loc=1, fontsize=6.5)
ax2.set_yticklabels([])
ax2.grid('on')
ax2.set_title('2nd-kind', fontsize=10)

fig.subplots_adjust(left=0.15, bottom=0.15, right=0.87, top=0.92)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceConvergence.pdf',dpi=80)
Example #35
0
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N[0]*error[0]/N
ax.loglog(N, error, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp, c='k', marker='None', ls=':', lw=0.8, label=None)
rc('font',**font)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc,N[0]*error[0]/loc))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1],r'N$^{-1}$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')
ax.set_ylabel('Relative error', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
canvas.print_figure('regression_tests/figs/error_energy_twosphere_dirichlet.pdf',dpi=80)

fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
rc('font',**font)
ax.set_ylabel('Total time [s]', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
    1.770e-05, 1.462e-05, 1.367e-05, 1.137e-05, 1.054e-05, 9.2166e-06])

r2 = array([1.985e-03, 4.820e-04, 3.696e-04, 2.394e-04, 1.812e-04, 1.708e-04, 1.423e-04,
    1.366e-04, 1.242e-04, 1.111e-04, 9.853e-05, 8.041e-05, 6.692e-05, 5.988e-05,
    4.896e-05, 4.433e-05, 3.768e-05, 3.500e-05, 2.768e-05, 2.620e-05, 2.231e-05,
    1.997e-05, 1.744e-05, 1.623e-05, 1.419e-05, 1.245e-05, 1.006e-05, 8.2839e-06])

it1 = arange(size(r))
it2 = arange(size(r2))

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
line1 = ax.semilogy(it1,r,c='k',marker='', ls='-', mfc='w', ms=5, label='Fixed p')
line2 = ax.semilogy(it2,r2,c='k',marker='', ls=':', mfc='w', ms=5, label='Relaxed')
rc('font',**font)

# axis labels
ax.set_ylabel('Residual', fontsize=10)
ax.set_xlabel('Iteration', fontsize=10)
ax.legend( (line1, line2), ('Fixed p', 'Relaxed') )
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesResidualHistory.pdf',dpi=80)

# make an average for each case
time = numpy.mean(numpy.array(temp).reshape(-1,3), axis=1)

# calculate speedup
speedup = time[::2] / time[1::2]
print("Speedup: ", speedup)
print("fixed-p: ", time[::2])
print("relaxed-p: ", time[1::2])

ind = numpy.arange(len(speedup))
width = 0.3

# set up plot
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot
bar = ax.bar(ind+0.1, speedup, width, fill=False, edgecolor='k', hatch='..'*2, linewidth=1)

# axis labels
ax.set_xticks(ind+0.1+width/2)
ax.set_xlim(-0.4, 3)
ax.set_ylim(0, numpy.ceil(numpy.max(speedup)))
ax.set_xticklabels( ('8192','32768','131072') )
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesSpeedupRelaxation.pdf',dpi=80)
Example #38
0
def store_2ddata(data, fname, pltitle='', dir='./', fits=False, plot=True, plrange=(None, None), log=False, rollaxes=False, cmap='RdYlBu', xlab='X [pix]', ylab='Y [pix]', cbarlab=None, hdr=(), ident=True):
	"""
	Store **data** to disk as FITS and/or plot as annotated plot in PDF.

	@param [in] data 2D data array to show
	@param [in] fname Filename base to use (also fallback for plot title)
	@param [in] pltitle Plot title (if given)
	@param [in] dir Output directory
	@param [in] fits Toggle FITS output
	@param [in] plot Toggle 2D plot output as PDF
	@param [in] plrange Use this range for plotting in imshow() (None for autoscale)
	@param [in] log Take logarithm of data before storing.
	@param [in] rollaxes Roll axes for PDF plot such that (0,0) is the center
	@param [in] cmap Colormap to use for PDF
	@param [in] xlab X-axis label
	@param [in] ylab Y-axis label
	@param [in] cbarlab Colorbar label (for units)
	@param [in] hdr Additional FITS header items, give a list of tuples: [(key1, val1), (key2, val2)]
	@param [in] ident Add identification string to plots
	@returns Tuple of (fitsfile path, plotfile path)
	"""

	# Do not store empty data
	if (len(data) <= 0):
		return

	data_arr = np.asanyarray(data)
	if (log):
		data_arr = np.log10(data_arr)
	extent = None
	if (rollaxes):
		sh = data_arr.shape
		extent = (-sh[1]/2., sh[1]/2., -sh[0]/2., sh[0]/2.)

	# Check if dir exists, or create
	if (not os.path.isdir(dir)):
		os.makedirs(dir)

	fitsfile = filenamify(fname)+'.fits'
	fitspath = os.path.join(dir, fitsfile)
	plotfile = filenamify(fname)+'.pdf'
	plotpath = os.path.join(dir, plotfile)

	if (fits):
		# Generate some metadata. Also store plot settings here
		hdr_dict = dict({'filename':fitsfile, 
				'desc':fname, 
				'title':pltitle,
				'plxlab': xlab,
				'plylab': ylab,
				'pllog': log,
				'plrlxs': rollaxes,
				'plcmap': cmap,
				'plrng0': plrange[0] if plrange[0] else 0,
				'plrng1': plrange[1] if plrange[1] else 0,
				}.items()
				+ dict(hdr).items())
		hdr = mkfitshdr(hdr_dict)
		# Store data to disk
		pyfits.writeto(fitspath, data_arr, header=hdr, clobber=True, checksum=True)

	if (plot):
		#plot_from_fits(fitspath)
		pltit = fname
		if (pltitle):
			pltit = pltitle

		# Plot without GUI, using matplotlib internals
		fig = Figure(figsize=(6,6))
		ax = fig.add_subplot(111)
		# Make margin smaller
		fig.subplots_adjust(left=0.15, right=0.95, top=0.9, bottom=0.1)
		img=0
		# Colormaps
		# plus min: cmap=cm.get_cmap('RdYlBu')
		# linear: cmap=cm.get_cmap('YlOrBr')
		# gray: cmap=cm.get_cmap('gray')
		img = ax.imshow(data_arr, interpolation='nearest', cmap=cm.get_cmap(cmap), aspect='equal', extent=extent, vmin=plrange[0], vmax=plrange[1])
		ax.set_title(pltit)
		ax.set_xlabel(xlab)
		ax.set_ylabel(ylab)
		# dimension 0 is height, dimension 1 is width
		# When the width is equal or more than the height, use a horizontal bar, otherwise use vertical
		if (data_arr.shape[0]/data_arr.shape[1] >= 1.0):
			cbar = fig.colorbar(img, orientation='vertical', aspect=30, pad=0.05, shrink=0.8)
		else:
			cbar = fig.colorbar(img, orientation='horizontal', aspect=30, pad=0.12, shrink=0.8)
		if (cbarlab):
			cbar.set_label(cbarlab)

		# Add ID string
		if (ident):
			# Make ID string
			datestr = datetime.datetime.utcnow().isoformat()+'Z'
			# Put this in try-except because os.getlogin() fails in screen(1)
			try:
				idstr = "%s@%s %s %s" % (os.getlogin(), os.uname()[1], datestr, sys.argv[0])
			except OSError:
				idstr = "%s@%s %s %s" % (getpass.getuser(), os.uname()[1], datestr, sys.argv[0])

			ax.text(0.01, 0.01, idstr, fontsize=7, transform=fig.transFigure)

		canvas = FigureCanvas(fig)
		#canvas.print_figure(plotfile, bbox_inches='tight')
		canvas.print_figure(plotpath)

	return (fitspath, plotpath)
t_relax = numpy.array([1.6450, 2.3425, 4.0652, 5.7684, 8.1425, 1.0105e+01, 1.2244e+01])
t_fixed = numpy.array([3.1261, 4.7109, 7.9344, 9.8651, 1.2510e+01, 1.6292e+01, 1.7878e+01])

speedup = t_fixed / t_relax

print(t_relax, t_fixed)
print(speedup)

# set up plot
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.plot(tol,speedup,c='k',marker='o', ls='-', mfc='w', ms=5, label='')

# axis labels
#pyplot.xlim(5, 50)
#pyplot.ylim(1, 4)
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('tolerance', fontsize=10)
ax.set_xscale('log')

pyplot.axhline(y=1.0, linestyle='dashed', color='k')

pyplot.ylim(0,2.5)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceSpeedupTolerance.pdf',dpi=80)
xbar = ybar = 0.0
colors = ['#377eb8', '#ff7f00', '#4daf4a']
for th, c in zip(thetas, colors):
    beta = 2*th #  shear phase
    ax1.arrow(0.0, 0.0, length*np.cos(th), length*np.sin(th), width=0.02, head_width=0.02, length_includes_head=True, color=c)
    ax1.arrow(0.0, 0.0, -length*np.cos(th), -length*np.sin(th), width=0.02, head_width=0.02, length_includes_head=True, color=c)
    ax2.arrow(0.0, 0.0, length*np.cos(beta), length*np.sin(beta), width=0.02, head_width=0.1, length_includes_head=True, color=c)
    xbar += np.cos(beta)
    ybar += np.sin(beta)

xbar /= len(thetas)
ybar /= len(thetas)

ax2.arrow(0.0, 0.0, length*xbar, length*ybar, width=0.02, head_width=0.1, color='k')

for ax in [ax1, ax2]:
    ax.set_xlim(-1.2, 1.2)
    ax.set_ylim(-1.2, 1.2)
    ax.axhline(0.0, c='k', lw=0.5)
    ax.axvline(0.0, c='k', lw=0.5)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.add_patch(Ellipse((0.0, 0.0), 2*length, 2*length, fill=False, ec='k'))

ax1.set_title("Headless position angles")
ax2.set_title("Shear phases")

canvas = FigureCanvasPdf(fig)
fig.set_tight_layout(True)
canvas.print_figure("angularSpread.pdf", dpi=100)
# plot log-log
ax.loglog(N, e, c='k', ls='-', lw=1.0, marker='o', mfc='w', 
	      ms=5, label='non-relaxed, tight parameters')
ax.loglog(N[1:], e_fixed, c='k', ls='-', lw=0.5, marker='+',
           ms=5, label='non-relaxed, loose parameters')
ax.loglog(N[1:], e_relaxed, c='k', ls='-', lw=0.5, marker='x',
           ms=5, label='relaxed, loose parameters')

# referece line
ax.loglog(N, line_sqrtN, c='k',ls='--')

# text on plot
scale2 = 0.6    # for plot adjustment
loc = (3*N[0]+N[1])/4
tex_loc = numpy.array((loc, N[0]*e[0]/loc)) * scale2
tex_angle = - 23
ax.text(tex_loc[0], tex_loc[1]/3.5, r'$O(1/\sqrt{N})$', 
	    fontsize=8, rotation=tex_angle, rotation_mode='anchor')

# axis labels
ax.set_ylabel('Relative Error', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.set_ylim(5e-4, 1e0)
ax.legend(loc=3, fontsize=6)

fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.92)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('EthrocyteConvergence.pdf',dpi=80)
Example #42
0
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N[0]*error[0]/N
ax.loglog(N, error, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp, c='k', marker='None', ls=':', lw=0.8, label=None)
rc('font',**font)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc,N[0]*error[0]/loc))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1],r'N$^{-1}$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')
ax.set_ylabel('Relative error', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
canvas.print_figure('regression_tests/figs/error_energy_dirichlet_surface.pdf',dpi=80)

fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
rc('font',**font)
ax.set_ylabel('Total time [s]', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
Example #43
0
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N[0]*error[0]/N
ax.loglog(N, error, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp, c='k', marker='None', ls=':', lw=0.8, label=None)
rc('font',**font)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc,N[0]*error[0]/loc))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1],r'N$^{-1}$',fontsize=8,rotation=tex_angle,rotation_mode='anchor')
ax.set_ylabel('Relative error', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)
canvas.print_figure('regression_tests/figs/error_energy_neumann_surface.pdf',dpi=80)

fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)
asymp = N*log(N)*total_time[0]/(N[0]*log(N[0]))
ax.loglog(N, total_time, c='k', marker='o',ls=' ', mfc='w', ms=5, label='')
ax.loglog(N, asymp,c='k',marker='None',ls=':', lw=0.8, label=None)
loc = (3*N[0]+N[1])/4
tex_loc = array((loc, loc*log(loc)*total_time[0]/(N[0]*log(N[0]))))
tex_angle = math.atan2(log(abs(asymp[-1]-asymp[0])),log(abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1], 'NlogN', fontsize=8,rotation=tex_angle, rotation_mode='anchor')
rc('font',**font)
ax.set_ylabel('Total time [s]', fontsize=10)
ax.set_xlabel('Number of elements', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
Example #44
0
rcParams['font.size'] = '10'

# open the result file
result = open(sys.argv[1])

# set up data
N, t = numpy.loadtxt(result, dtype=float, unpack=True)

# set up plot
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)


# plot log-log
ax.loglog(N,t,color='k',marker='o', ms=5, mfc='w')
ax.loglog(N,N/20000,color='k', ls=':', ms=5, mfc='w')
loc = (3*N[0]+N[1])/4

# text of plot
tex_loc = numpy.array((loc,N[0]*t[0]/loc)) * 1.2
tex_angle = numpy.arctan2(numpy.log(abs(N[-1]/10000-N[0]/10000)),numpy.log(abs(N[-1]-N[0])))*180/numpy.pi
ax.text(tex_loc[0], 6.5*tex_loc[1],r'$O(N)$',fontsize=10,rotation=tex_angle,rotation_mode='anchor')

# axis labels
ax.set_ylabel('Time (s)', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('FMMScaling.pdf',dpi=80)
t_fixed = numpy.array([1.7921e+01, 6.6619e+01, 1.5039e+02, 2.4847e+02, 3.3733e+02, 4.2533e+02, 5.0892e+02, 5.6729e+02])

res = numpy.array([2.64378e-02, 2.31630e-02, 2.47985e-02, 2.00446e-02, 2.27640e-02, 2.30615e-02, 2.30037e-02, 2.30257e-02])

speedup = t_fixed / t_relax

print(t_relax, t_fixed)
print(speedup)

# set up plot
fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.plot(tol,speedup,c='k',marker='o', ls='-', mfc='w', ms=5, label='')

# axis labels
#pyplot.xlim(5, 50)
#pyplot.ylim(1, 4)
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('tolerance', fontsize=10)
ax.set_xscale('log')

pyplot.axhline(y=1.0, linestyle='dashed', color='k')

pyplot.ylim(0,4)
fig.subplots_adjust(left=0.195, bottom=0.21, right=0.955, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesSpeedupTolerance.pdf',dpi=80)
Example #46
0
    def save(self, fname=None, sigma_clip=None):
        r"""Saves the most recently rendered image of the Scene to disk.

        Once you have created a scene and rendered that scene to an image
        array, this saves that image array to disk with an optional filename.
        If an image has not yet been rendered for the current scene object,
        it forces one and writes it out.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            The file format is inferred from the filename's suffix. Supported
            fomats are png, pdf, eps, and ps.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)

        Returns
        -------
            Nothing

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # Modify camera, sources, etc...
        >>> sc.render()
        >>> sc.save('test.png', sigma_clip=4)

        Or alternatively:

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # save with different sigma clipping values
        >>> sc.save('raw.png')
        >>> sc.save('clipped_2.png', sigma_clip=2)
        >>> sc.save('clipped_4.png', sigma_clip=4)

        """
        if fname is None:
            sources = list(itervalues(self.sources))
            rensources = [s for s in sources if isinstance(s, RenderSource)]
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, string_types):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = "%s_Render_%s.png" % (basename, field)
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == '':
            suffix = '.png'
            fname = '%s%s' % (fname, suffix)

        self.render()

        mylog.info("Saving render %s", fname)
        # We can render pngs natively but for other formats we defer to
        # matplotlib.
        if suffix == '.png':
            self._last_render.write_png(fname, sigma_clip=sigma_clip)
        else:
            from matplotlib.figure import Figure
            from matplotlib.backends.backend_pdf import \
                FigureCanvasPdf
            from matplotlib.backends.backend_ps import \
                FigureCanvasPS
            shape = self._last_render.shape
            fig = Figure((shape[0] / 100., shape[1] / 100.))
            if suffix == '.pdf':
                canvas = FigureCanvasPdf(fig)
            elif suffix in ('.eps', '.ps'):
                canvas = FigureCanvasPS(fig)
            else:
                raise NotImplementedError(
                    "Unknown file suffix '{}'".format(suffix))
            ax = fig.add_axes([0, 0, 1, 1])
            ax.set_axis_off()
            out = self._last_render
            nz = out[:, :, :3][out[:, :, :3].nonzero()]
            max_val = nz.mean() + sigma_clip * nz.std()
            alpha = 255 * out[:, :, 3].astype('uint8')
            out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255
            out = np.concatenate([out.astype('uint8'), alpha[..., None]],
                                 axis=-1)
            # not sure why we need rot90, but this makes the orientation
            # match the png writer
            ax.imshow(np.rot90(out), origin='lower')
            canvas.print_figure(fname, dpi=100)
speedup = time[::2] / time[1::2]
speedup_1st = speedup[:len(speedup)//2]
speedup_2nd = speedup[len(speedup)//2:]

print(speedup_1st, speedup_2nd) # values in table

# set up plot
ind = numpy.arange(len(speedup)/2)
width = 0.35

fig = pyplot.figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
bar1 = ax.bar(ind, speedup_1st, width, fill=False,
	          edgecolor='k', hatch='..'*2, linewidth=1)
bar2 = ax.bar(ind+width, speedup_2nd, width, fill=False,
	          edgecolor='k', hatch='/'*3, linewidth=1)

# axis labels
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('$N$', fontsize=10)
ax.set_xticks(ind+width)
ax.set_xticklabels( ('8192','32768','131072') )
ax.legend((bar1[0], bar2[0]), ('1st-kind', '2nd-kind'),
	      loc='upper left', fontsize='small')
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceSpeedupRelaxation.pdf',dpi=80)
Example #48
0
r = array([
    1.016e-02, 2.123e-03, 6.290e-04, 2.550e-04, 1.638e-04, 1.247e-04,
    8.260e-05, 7.000e-05, 4.220e-05, 2.883e-05, 2.372e-05, 1.888e-05,
    1.394e-05, 1.168e-05, 9.4244e-06
])

it = size(p)
ind = arange(it)

# set up plot
font = {'family': 'serif', 'size': 10}
fig = Figure(figsize=(3.7, 2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.semilogy(ind, r, c='k', marker='', ls='-', mfc='w', ms=5, label='')
rc('font', **font)

ax2 = ax.twinx()
ax2.plot(ind, p, c='k', marker='o', ls=':', mfc='w', ms=5, label='')

# axis labels
ax.set_ylabel('Residual', fontsize=10)
ax.set_xlabel('Iterations', fontsize=10)
ax2.set_ylabel('p', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceResidualIterations.pdf', dpi=80)
N = array([128, 512, 2048, 8192, 32768, 131072])
e = array([1.84e-1, 9.27e-2, 4.61e-2, 2.41e-2, 1.14e-2, 5.80e-3])

line_sqrtN = 1 / np.sqrt(N)

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(3,2), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
ax.loglog(N,e,c='k',marker='o', ls='-', mfc='w', ms=5, label='')
ax.loglog(N,line_sqrtN,c='k',ls='--', mfc='w', ms=5, label='')
rc('font',**font)
loc = (3*N[0]+N[1])/4

# text on plot
# 1 / sqrt(N)
tex_loc = np.array((loc,N[0]*e[0]/loc))
tex_angle = math.atan2(np.log(np.abs(line_sqrtN[-1]-line_sqrtN[0])),np.log(np.abs(N[-1]-N[0])))*180/math.pi
ax.text(tex_loc[0], tex_loc[1]/3.5,r'$O(1/\sqrt{N})$',fontsize=8,rotation=tex_angle-10,rotation_mode='anchor')
# axis labels
ax.set_ylabel('Relative Error', fontsize=10)
ax.set_xlabel('N', fontsize=10)
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('StokesConvergence.pdf',dpi=80)

           mfc='w',
           ms=5,
           label='non-relaxed, tight parameters')
ax2.loglog(N[-3:],
           e2_fixed,
           c='k',
           ls='-',
           lw=0.5,
           marker='+',
           ms=5,
           label='non-relaxed, loose parameters')
ax2.loglog(N[-3:],
           e2_relaxed,
           c='k',
           ls='-',
           lw=0.5,
           marker='x',
           ms=5,
           label='relaxed, loose parameters')

ax2.set_xlabel('$N$', fontsize=10)
ax2.legend(loc=1, fontsize=6.5)
ax2.set_yticklabels([])
ax2.grid('on')
ax2.set_title('2nd-kind', fontsize=10)

fig.subplots_adjust(left=0.15, bottom=0.15, right=0.87, top=0.92)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('LaplaceConvergence.pdf', dpi=80)
speedup = data_fixed / data_relax

print speedup

ind = arange(N)
width = 0.3

# set up plot
font = {'family':'serif','size':10}
fig = Figure(figsize=(4,3), dpi=80)
ax = fig.add_subplot(111)

# plot log-log
bar1 = ax.bar(ind, speedup[:,0], width, color='r')
bar2 = ax.bar(ind+width, speedup[:,1],width,color='b')
bar3 = ax.bar(ind+2*width,speedup[:,2],width,color='g')
# bar2 = ax.bar(ind+width, speedup_2nd, width, color='b')
rc('font',**font)

# axis labels
ax.set_ylabel('Speedup', fontsize=10)
ax.set_xlabel('N', fontsize=10)
ax.set_xticks(ind+1.5*width)
ax.set_xticklabels( ('2048','8192','32768','131072') )
ax.legend( (bar1[0], bar2[0], bar3[0]), ('2048 panels/cell', '8192 panels/cell', '32768 panels/cell'), loc=2 )
fig.subplots_adjust(left=0.185, bottom=0.21, right=0.965, top=0.95)
canvas = FigureCanvasPdf(fig)

# plot to pdf
canvas.print_figure('EthrocyteMultipleCellSpeedup.pdf',dpi=80)