예제 #1
0
 def draw(self, **kwargs):
     """
     Returns a histogram of a kde mixture of points drawn from 
     all mutational distributions at the selected frequencies.
     """
     canvas = toyplot.Canvas(kwargs.get("width", 350),
                             kwargs.get("height", 250))
     axes = canvas.cartesian(
         xlabel="fitness effect",
         yshow=False,
     )
     mixture = np.concatenate([
         i._dist.rvs(**i._params, size=10000) * i._neg for i in self.mlist
     ])
     weights = np.concatenate(
         [np.repeat(self.freq[i], 10000) for i in range(len(self.mlist))])
     kernel = stats.gaussian_kde(dataset=mixture, weights=weights)
     xpoints = np.linspace(self.mlist.min, self.mlist.max, 500)
     yvalues = kernel.pdf(xpoints)
     mark = axes.fill(
         xpoints,
         yvalues,
         style={
             "stroke": toyplot.color.Palette()[0],
             "stroke-width": 1.5,
             "fill": toyplot.color.Palette()[0],
             "fill-opacity": 0.33,
         },
     )
     axes.x.ticks.locator = toyplot.locator.Extended(only_inside=True)
     axes.x.ticks.show = True
     return canvas, axes, mark
예제 #2
0
파일: pca.py 프로젝트: shihuang047/ipyrad
    def _setup_canvas_and_axes(self):
        """
        Setup and style the Canvas size and Cartesian axes styles.
        """
        # get axis labels for PCA or TSNE plot
        if self.variance[self.ax0] >= 0.0:
            xlab = "PC{} ({:.1f}%) explained".format(
                self.ax0, self.variance[self.ax0] * 100)
            ylab = "PC{} ({:.1f}%) explained".format(
                self.ax1, self.variance[self.ax1] * 100)
        else:
            xlab = "{} component 1".format(self.pcatool._model)
            ylab = "{} component 2".format(self.pcatool._model)

        if not self.axes:
            self.canvas = toyplot.Canvas(self.width, self.height)  # 400, 300)
            self.axes = self.canvas.cartesian(
                grid=(1, 5, 0, 1, 0, 4),  # <- leaves room for legend
                xlabel=xlab,
                ylabel=ylab,
            )
        else:
            self.axes.x.label.text = xlab
            self.axes.y.label.text = ylab

        # style axes
        self.axes.x.spine.style["stroke-width"] = 2.25
        self.axes.y.spine.style["stroke-width"] = 2.25
        self.axes.x.ticks.labels.style["font-size"] = "12px"
        self.axes.y.ticks.labels.style["font-size"] = "12px"
        self.axes.x.label.style['font-size'] = "14px"
        self.axes.y.label.style['font-size'] = "14px"
예제 #3
0
def test_axes_text():
    canvas = toyplot.Canvas()
    axes = canvas.axes()
    x = numpy.linspace(0, 1)
    y = numpy.sin(x * 10)
    text = ["s%s" % index for index in range(len(x))]
    axes.text(x, y, text, annotation=False)
    assert_canvas_matches(canvas, "axes-text")
예제 #4
0
def test_axes_tick_titles():
    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.x.ticks.locator = toyplot.locator.Explicit(
        locations=[-0.5, 0, 0.5], titles=["Foo", "Bar", "Baz"])
    axes.y.ticks.locator = toyplot.locator.Explicit(
        locations=[-0.5, 0, 0.5], titles=["Red", "Green", "Blue"])
    assert_canvas_matches(canvas, "axes-tick-titles")
예제 #5
0
def test_axes_scatterplot_singular():
    x = numpy.linspace(0, 2 * numpy.pi)
    y = numpy.sin(x)

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.plot(x, y)
    axes.scatterplot(x[0], y[0], color="red")
    assert_canvas_matches(canvas, "axes-scatterplot-singular")
예제 #6
0
def test_axes_bars_one_boundary():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    y1 = numpy.mean(observations, axis=1)

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.bars(y1, baseline=None)
    assert_canvas_matches(canvas, "axes-bars-one-boundary")
예제 #7
0
def test_axes_scatterplot_one_variable():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    y = numpy.mean(observations, axis=1)

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.scatterplot(y)
    assert_canvas_matches(canvas, "axes-scatterplot-one-variable")
예제 #8
0
def test_axes_bars_one_magnitude():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    y = numpy.mean(observations, axis=1)

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.bars(y)
    assert_canvas_matches(canvas, "axes-bars-one-magnitude")
예제 #9
0
def generate():

    # read in the list of members and their presenting histories
    with open('members.yaml', 'r') as fd:
        members = yaml.load(fd)

    # convert to a pandas dataframe
    members = pd.DataFrame.from_dict(members).T
    members.index.name = 'name'

    # read in the pickled doodle poll
    with open("doodle_poll.pkl", "rb") as fd:
        doodle_poll = pickle.load(fd)

    # count the number of volunteer contributions
    for t in ('paper', 'plot'):
        members['vcount_'+t] = doodle_poll.query('type == @t').sum()

    members = members.fillna(0)

    # generate plotss of the current standings and render them to html files
    for contribution in ["papers", "plots"]:
        pool = members
        data = np.column_stack((pool[contribution.lower()],
                                pool["vcount_"+contribution.lower()[:-1]]))
        canvas = toyplot.Canvas(800, 500)
        axes = canvas.axes(bounds=(80, -200, 50, -120))
        mark = axes.bars(data, baseline="stacked")
        axes.x.ticks.locator = toyplot.locator.Explicit(labels=pool.index)
        axes.label.text = contribution
        axes.x.ticks.labels.angle = 30
        axes.x.ticks.show = True
        axes.x.ticks.labels.style = {"baseline-shift":0, "text-anchor":"end", "-toyplot-anchor-shift":"-6px"}
        axes.x.ticks.labels.offset = 8
        axes.y.label.text = "Times presented"
        axes.y.ticks.locator = toyplot.locator.Integer()
        axes.coordinates.show = False
        palette = toyplot.color.Palette()
        canvas.legend([
            ("Finished (past)", "rect", {"fill":palette.css(0),}),
            ("Volunteered (future)", "rect", {"fill":palette.css(1),}),
        ], corner=("right", 80, 80, 50),)
        toyplot.html.render(canvas, fobj="templates/"+contribution.lower()+"_history.html")

    # read in this week's presenters
    with open('selected_presenters.yaml', 'r') as fd:
        presenters = yaml.load(fd)

    presenters = pd.DataFrame.from_dict(presenters).T
    presenters.index.name = 'name'

    # render the page
    env = Environment(loader=FileSystemLoader('templates'))
    template = env.get_template('index.html')
    with open('build/index.html', 'w') as fd:
        fd.write(template.render(dates = [pd.to_datetime(item).to_pydatetime().strftime("%d. %B %Y") for item in presenters.index] , presenters=presenters))
예제 #10
0
def test_axes_plot_one_variable_x():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    x = numpy.linspace(0, 1, len(observations))
    y = numpy.mean(observations, axis=1)

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.plot(x, y)
    assert_canvas_matches(canvas, "axes-plot-one-variable-x")
예제 #11
0
def test_axes_bars_n_boundaries_along_y():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    series = numpy.column_stack((numpy.min(observations, axis=1), numpy.mean(
        observations, axis=1), numpy.max(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.bars(series, along="y", baseline=None)
    assert_canvas_matches(canvas, "axes-bars-n-boundaries-along-y")
예제 #12
0
def test_axes_bars_n_magnitudes_titles():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    series = numpy.column_stack(
        (numpy.mean(observations, axis=1), numpy.std(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.bars(series, baseline="stacked", title=["mean", "standard deviation"])
    assert_canvas_matches(canvas, "axes-bars-n-magnitudes-titles")
예제 #13
0
파일: tests.py 프로젝트: satishgoda/toyplot
def test_axes_bars_n_magnitudes_along_y():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    series = numpy.column_stack(
        (numpy.mean(observations, axis=1), numpy.std(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.cartesian()
    axes.bars(series, along="y")
    assert_canvas_matches(canvas, "axes-bars-n-magnitudes-along-y")
예제 #14
0
def test_axes_bars_one_magnitude_centers():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    x = numpy.linspace(0, 1, len(observations))
    y = numpy.mean(observations, axis=1)

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.bars(x, y)
    assert_canvas_matches(canvas, "axes-bars-one-magnitude-centers")
예제 #15
0
파일: tests.py 프로젝트: satishgoda/toyplot
def test_axes_bars_one_boundary_centers():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    x = numpy.linspace(0, 1, len(observations))
    y1 = numpy.mean(observations, axis=1)

    canvas = toyplot.Canvas()
    axes = canvas.cartesian()
    axes.bars(x, y1, baseline=None)
    assert_canvas_matches(canvas, "axes-bars-one-boundary-centers")
예제 #16
0
def test_axes_scatterplot_n_variables_along_y():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    series = numpy.column_stack((numpy.min(observations, axis=1), numpy.mean(
        observations, axis=1), numpy.max(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.scatterplot(series, along="y")
    assert_canvas_matches(canvas, "axes-scatterplot-n-variables-along-y")
예제 #17
0
 def get_canvas_and_axes(self, axes):
     if axes:
         self.canvas = None
         self.axes = axes
     else:
         self.canvas = toyplot.Canvas(
             height=self.style.height,
             width=self.style.width,
         )
         self.axes = self.canvas.cartesian(padding=self.style.padding, )
예제 #18
0
파일: tests.py 프로젝트: satishgoda/toyplot
def test_axes_scatterplot_one_variable_fill():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    y = numpy.mean(observations, axis=1)
    color = numpy.arange(len(observations))

    canvas = toyplot.Canvas()
    axes = canvas.cartesian()
    axes.scatterplot(y, color=color)
    assert_canvas_matches(canvas, "axes-scatterplot-one-variable-fill")
예제 #19
0
파일: tests.py 프로젝트: satishgoda/toyplot
def test_axes_plot_n_variables():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    series = numpy.column_stack((numpy.min(observations, axis=1), numpy.mean(
        observations, axis=1), numpy.max(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.cartesian()
    axes.plot(series)
    assert_canvas_matches(canvas, "axes-plot-n-variables")
예제 #20
0
def test_axes_bars_n_magnitudes_wiggle():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    series = numpy.column_stack(
        (numpy.mean(observations, axis=1), numpy.std(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.bars(series, baseline="wiggle")
    assert_canvas_matches(canvas, "axes-bars-n-magnitudes-wiggle")
예제 #21
0
def depthplot(data, samples=None, dims=(0, 0), xmax=50, outprefix=None):
    """ plots histogram of coverages across clusters"""

    ## select samples to be plotted, requires depths info
    if not samples:
        samples = data.samples.keys()
        samples.sort()

    subsamples = OrderedDict([(i, data.samples[i]) for i in samples])

    ## get canvas dimensions based on n-samples
    if any(dims):
        ## user-supplied dimensions (...)
        print("userdims")
    else:
        if len(subsamples) <= 4:
            ## set dimension to N samples
            dims = (1, len(subsamples))
        else:
            dims = (len(subsamples) / 4, 4)

    ## create canvas
    canvas = toyplot.Canvas(width=250 * dims[1], height=200 * dims[0])

    ## fill in each panel of canvas with a sample
    for panel, sample in enumerate(subsamples):
        axes = canvas.axes(grid=(dims[0], dims[1], panel), gutter=20)
        axes.x.domain.xmax = xmax
        axes.label.text = sample

        ## statistical called bins
        statdat = subsamples[sample].depths["statmin"]
        sdat = np.histogram(statdat, range(50))

        ## majrule called bins
        maj = data.samples[sample].depths["mjmin"]
        majdat = maj[maj < data.paramsdict["mindepth_statistical"]]
        mdat = np.histogram(majdat, range(50))

        ## excluded bins
        tots = data.samples[sample].depths["total"]
        totsdat = tots[tots < data.paramsdict["mindepth_majrule"]]
        edat = np.histogram(totsdat, range(50))

        # ## set ymax using highest bin...
        # #ymax = ...
        # heights = np.column_stack((sdat,mdat,edat))
        axes.bars(sdat)
        axes.bars(mdat)
        axes.bars(edat)

    ## return objects to be saved...
    if outprefix:
        toyplot.html.render(canvas, fobj=outprefix + ".html")
        toyplot.svg.render(canvas, fobj=outprefix + ".svg")
예제 #22
0
    def _preview_topology(self):
        """
        Reads in the tree file, and saves a .png with rectangular and circular topology previews.

        :return: toyplot.Canvas object
        """
        self.log.debug('reading tree')
        # read in the tree
        self.tree = toytree.tree(open(self.tree_file, 'r').read(),
                                 tree_format=0)

        # drop / replace nodes
        if self.args.replace_nodes:
            for idx in self.args.replace_nodes:
                self.tree.idx_dict[idx].add_sister(name='%d_replaced' % idx,
                                                   dist=1)
                self.tree.idx_dict[idx].detach()
            # saving the node names now saves some work
            self.args.replace_nodes = [
                '%d_replaced' % idx for idx in self.args.replace_nodes
            ]
        else:
            # save empty list
            self.args.replace_nodes = []
        if self.args.drop_nodes:
            [self.tree.idx_dict[idx].detach() for idx in self.args.drop_nodes]

        # outgroup rooting
        if self.args.root:
            self.tree = self.tree.root(
                names=[self.tree.idx_dict[self.args.root].name])

        self.tree = toytree.tree(self.tree.write())

        # set dimensions of the canvas
        preview = toyplot.Canvas(width=800,
                                 height=400,
                                 style={'background-color': 'white'})
        # dissect canvas into two cartesian areas
        ax0 = preview.cartesian(bounds=('5%', '48%', '5%', '95%'))
        ax1 = preview.cartesian(bounds=('52%', '95%', '5%', '95%'))

        # call draw with the 'axes' argument to pass it to a specific cartesian area
        self.log.debug('drawing preview')
        self.tree.draw(axes=ax0, layout='r', tip_labels=False)
        self.tree.draw(axes=ax1, layout='c', tip_labels=False)

        # hide the axes coordinates
        ax0.show = False
        ax1.show = False

        # render to image
        png.render(preview, self.args.topo)
        self.log.info('rendered preview %s' % self.args.topo)
        return preview
예제 #23
0
def test_canvas_time():
    canvas = toyplot.Canvas()
    frame = canvas.time(0.3, 0.4)
    nose.tools.assert_equal(frame.time(), 0.3)
    numpy.testing.assert_almost_equal(frame.duration(), 0.1)
    nose.tools.assert_equal(frame.index(), 0)

    frame = canvas.time(0.3, 0.4, 5)
    nose.tools.assert_equal(frame.time(), 0.3)
    numpy.testing.assert_almost_equal(frame.duration(), 0.1)
    nose.tools.assert_equal(frame.index(), 5)
예제 #24
0
def test_axes_bars_n_boundaries_centers():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    x = numpy.linspace(0, 1, len(observations))
    series = numpy.column_stack((numpy.min(observations, axis=1), numpy.mean(
        observations, axis=1), numpy.max(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.bars(x, series, baseline=None)
    assert_canvas_matches(canvas, "axes-bars-n-boundaries-centers")
예제 #25
0
def step_impl(context):
  context.canvas = toyplot.Canvas(style={"background-color":"white"}, width=600, height=600)
  axes = context.canvas.axes()
  scatterplot = axes.scatterplot(numpy.arange(10))
  def callback(frame):
    if frame.index() == 0:
      for i in numpy.arange(10):
        frame.set_datum_style(scatterplot, 0, i, {"opacity":0})
    else:
      frame.set_datum_style(scatterplot, 0, frame.index() - 1, {"opacity":1})
  context.canvas.animate(11, callback)
예제 #26
0
파일: tests.py 프로젝트: satishgoda/toyplot
def test_axes_bars_n_magnitudes_centers():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    x = numpy.linspace(0, 1, len(observations))
    series = numpy.column_stack(
        (numpy.mean(observations, axis=1), numpy.std(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.cartesian()
    axes.bars(x, series)
    assert_canvas_matches(canvas, "axes-bars-n-magnitudes-centers")
예제 #27
0
def test_axes_scatterplot_n_variables_x():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    x = numpy.linspace(0, 1, len(observations))
    series = numpy.column_stack((numpy.min(observations, axis=1), numpy.mean(
        observations, axis=1), numpy.max(observations, axis=1)))

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.scatterplot(x, series)
    assert_canvas_matches(canvas, "axes-scatterplot-n-variables-x")
예제 #28
0
def test_axes_palettes():
    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.fill(numpy.sin(numpy.linspace(0, 2 * numpy.pi, 100)),
              style={"fill-opacity": 0.5})
    axes.plot(numpy.sin(numpy.linspace(0, 2 * numpy.pi, 100)), marker="o")
    axes.fill(numpy.cos(numpy.linspace(0, 2 * numpy.pi, 100)),
              style={"fill-opacity": 0.5})
    axes.plot(numpy.cos(numpy.linspace(0, 2 * numpy.pi, 100)), marker="o")
    axes.fill((numpy.linspace(0, 1, 100)), style={"fill-opacity": 0.5})
    axes.plot((numpy.linspace(0, 1, 100)), marker="o")
    assert_canvas_matches(canvas, "axes-palettes")
예제 #29
0
파일: tests.py 프로젝트: satishgoda/toyplot
def test_axes_bars_one_magnitude_edges():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    x = numpy.cumsum(numpy.random.random(len(observations) + 1))
    x1 = x[:-1]
    x2 = x[1:]
    y = numpy.mean(observations, axis=1)

    canvas = toyplot.Canvas()
    axes = canvas.cartesian()
    axes.bars(x1, x2, y)
    assert_canvas_matches(canvas, "axes-bars-one-magnitude-edges")
예제 #30
0
def test_axes_bars_one_boundary_edges():
    numpy.random.seed(1234)
    observations = numpy.random.normal(loc=1, size=(25, 100))
    x = numpy.cumsum(numpy.random.random(len(observations) + 1))
    x1 = x[:-1]
    x2 = x[1:]
    y1 = numpy.mean(observations, axis=1)

    canvas = toyplot.Canvas()
    axes = canvas.axes()
    axes.bars(x1, x2, y1, baseline=None)
    assert_canvas_matches(canvas, "axes-bars-one-boundary-edges")