Beispiel #1
0
def plot_downstream(clwe, table, output, ylim):
    df = pd.read_csv(data_file(table))
    df = df[df.clwe == clwe]
    df = df.assign(
        refine=pd.Categorical(df['refine'], ['Original', '+retrofit', '+synthetic']),
        language=pd.Categorical(df['language'], ['DE', 'ES', 'FR', 'IT', 'JA', 'RU', 'ZH', 'AVG'])
    )
    g = p9.ggplot(df, p9.aes(x='language', y='accuracy', fill='refine'))
    g += p9.geom_bar(position='dodge', stat='identity', width=.8)
    g += p9.coord_cartesian(ylim=ylim)
    g += p9.scale_fill_manual(['#999999', '#EA5F94', '#FFB14E'])
    g += p9.theme_void(base_size=FONT_SIZE, base_family='Arial')
    g += p9.theme(
        plot_background=p9.element_rect(fill='white'),
        panel_grid_major_y=p9.element_line(),
        axis_text_x=p9.element_text(margin={'t': 10}),
        axis_text_y=p9.element_text(margin={'r': 8}),
        legend_position=(.7, .9),
        legend_direction='horizontal',
        legend_title=p9.element_blank(),
        legend_text=p9.element_text(size=FONT_SIZE),
        legend_box_margin=0,
        figure_size=(12, 3)
    )
    g.save(filename=output_file(output))
Beispiel #2
0
    def plot_fusion(self):
        """
        plot fusion count
        """

        p9.theme_set(p9.theme_void())
        for ref in self.pos_dict:
            if ref in self.df_tsne.columns:
                out_plot_file = f'{self.out_prefix}_{ref}_fusion.pdf'
                plot = p9.ggplot(self.df_tsne, p9.aes(x="tSNE_1", y="tSNE_2", color=ref)) + \
                    p9.geom_point(size=0.2) + \
                    p9.theme_bw() + \
                    p9.scale_color_gradient(low="lightgrey",high="blue")
                plot.save(out_plot_file)
Beispiel #3
0
def plot_patch(patch, vmin=None, vmax=None, round_digits=1, threshold=None):
    if len(patch.shape) == 1:
        patch = patch.reshape(1, -1)
    if threshold is None:
        threshold = patch.mean()
    vmin = vmin or patch.min()
    vmax = vmax or patch.max()

    tile_height = tile_width = 0.95

    hshift = 0
    vshift = 0.5 * tile_height

    plotr = pd.DataFrame({
        'x': (
            np.tile(np.arange(patch.shape[1]), patch.shape[0]).flatten()
            + hshift
        ),
        'y': (
            - np.repeat(np.arange(patch.shape[0]), patch.shape[1]).flatten()
            + vshift
        ),
        'value': np.round(patch.flatten(), round_digits),
        'color_text': patch.flatten() < threshold
    })

    return (
        p9.ggplot(p9.aes('x', 'y'))
        + p9.geom_tile(plotr, p9.aes(width=tile_width, height=tile_height))
        + p9.geom_text(plotr, p9.aes(label='value', color='color_text'))
        + p9.aes(fill='value')
        + p9.coord_equal(expand=False)
        + p9.theme_void()
        + p9.scales.scale_fill_gradient(
            high='#f0f0f0', low='#252525', guide=False)
        + p9.scales.scale_color_gray(breaks=[False, True], guide=False)
    )
Beispiel #4
0
    def pictures(self, mode='bw', subset=None, n_random=10):
        """Returns a picture of the selected images.

        Creates either a colored or a black-white picture of the selected
        images.

        Args:
            mode: Should the picture be black-white ('bw') or in color
                ('color')?
            subset: Optional list of picture indices that should be included in
                the dataframe. If specified, n_random will be ignored.
            n_random: Optional number of randomly selected images. If neither
                subset nor n_random are specified, all images will be included.

        Returns:
            A plotnine object including all pictures with their label.

        Raises:
            NotImplementedError: mode must be either 'bw' or 'color'."""
        dataframe = self.rgb_dataframe(subset=subset, n_random=n_random)
        if mode == 'bw':
            fill_key = 'rgb_bw'
        elif mode == 'color':
            fill_key = 'rgb'
        else:
            raise NotImplementedError("Pictures are either in black-white"
                                      "('bw') or in color ('color').")
        picture = (
            gg.ggplot(dataframe, gg.aes(x='x', y='y', fill=fill_key)) +
            gg.geom_tile() + gg.theme_void() +
            gg.theme(legend_position='none') + gg.scale_fill_manual(
                values={key: key
                        for key in dataframe[fill_key].unique()}) +
            gg.facet_wrap('image_id', labeller=self.labeller) +
            gg.scale_y_reverse() + gg.coord_fixed())
        return picture
Beispiel #5
0
    def test_theme_void(self):
        p = self.g + labs(title='Theme Void') + theme_void()

        assert p + _theme == 'theme_void'
Beispiel #6
0
    def test_theme_void(self):
        p = self.g + labs(title='Theme Void') + theme_void()

        assert p + _theme == 'theme_void'
Beispiel #7
0
gradient = (
    (0.99, 0.88, 0.87),
    (0.98, 0.62, 0.71),
    (0.86, 0.20, 0.59),
    bcolor, bcolor,
    bcolor_darker, bcolor_darker)

df1 = df[:n//3:9]
df2 = df[n//3:2*n//3]
df3 = df[2*n//3::12]

p = (ggplot(aes('x', 'y', color='y', fill='y'))
     + annotate(geom='label', x=0.295, y=0.495, label='pl  tnine',
                label_size=1.5, label_padding=.1, size=24,
                fill=bcolor_lighter, color=bcolor)
     + geom_point(df1, size=8, stroke=0, show_legend=False)
     + geom_line(df2, size=2, color=bcolor_darker, show_legend=False)
     + geom_bar(df3, aes('x+.06'), stat='identity', size=0, show_legend=False)

     + scale_color_gradientn(colors=gradient)
     + scale_fill_gradientn(colors=gradient)
     + theme_void()
     + theme(figure_size=(3.6, 3.6)))

p.save('logo.pdf', pad_inches=-0.04)

# Remove the project name
p.layers = p.layers.__class__(p.layers[1:])
p.save('logo-small.pdf', pad_inches=-0.04)
Beispiel #8
0
bcolor_darker = '#631d41'

gradient = ((0.99, 0.88, 0.87), (0.98, 0.62, 0.71), (0.86, 0.20, 0.59), bcolor,
            bcolor, bcolor_darker, bcolor_darker)

df1 = df[:n // 3:9]
df2 = df[n // 3:2 * n // 3]
df3 = df[2 * n // 3::12]

p = (ggplot(aes('x', 'y', color='y', fill='y')) + annotate(geom='label',
                                                           x=0.295,
                                                           y=0.495,
                                                           label='pl  tnine',
                                                           label_size=1.5,
                                                           label_padding=.1,
                                                           size=24,
                                                           fill=bcolor_lighter,
                                                           color=bcolor) +
     geom_point(df1, size=8, stroke=0, show_legend=False) +
     geom_line(df2, size=2, color=bcolor_darker, show_legend=False) +
     geom_bar(df3, aes('x+.06'), stat='identity', size=0, show_legend=False) +
     scale_color_gradientn(colors=gradient) +
     scale_fill_gradientn(colors=gradient) + theme_void() +
     theme(figure_size=(3.6, 3.6)))

p.save('logo.pdf', pad_inches=-0.04)

# Remove the project name
p.layers = p.layers.__class__(p.layers[1:])
p.save('logo-small.pdf', pad_inches=-0.04)
Beispiel #9
0
def plot_sinew_inputs(df, var=None, sweep_ind="sweep_ind"):
    r"""Inspect a sinew design

    Create a scatterplot matrix with hues. Often used to visualize a sinew
    design before evaluating the model functions.

    Usually called as a dispatch from plot_auto().

    Args:
        df (Pandas DataFrame): Input design data
        var (list of strings): Variables to plot
        sweep_ind (string): Sweep index column in df

    Returns:
        Seaborn scatterplot matrix

    Examples:

        >>> import grama as gr
        >>> import matplotlib.pyplot as plt
        >>> from grama.models import make_cantilever_beam
        >>> md = make_cantilever_beam()
        >>> ## Dispatch from autoplotter
        >>> (
        >>>     md
        >>>     >> gr.ev_sinews(df_det="swp", skip=True)
        >>>     >> gr.pt_auto()
        >>> )
        >>> ## Re-create without metadata
        >>> (
        >>>     md
        >>>     >> gr.ev_sinews(df_det="swp")
        >>>     >> gr.pt_sinew_inputs(var=md.var)
        >>> )

    """
    if var is None:
        raise ValueError("Must provide input columns list as keyword var")

    ## Define helpers
    labels_blank = lambda v: [""] * len(v)
    breaks_min = lambda lims: (lims[0], 0.5 * (lims[0] + lims[1]), lims[1])

    ## Make blank figure
    fig = (
        df
        >> ggplot()
        + geom_blank()
        + theme_void()
    ).draw(show=False)

    gs = gridspec.GridSpec(len(var), len(var))
    for i, v1 in enumerate(var):
        for j, v2 in enumerate(var):
            ax = fig.add_subplot(gs[i, j])
            ## Switch labels
            if j == 0:
                labels_y = _sci_format
            else:
                labels_y = labels_blank
            if i == len(var) - 1:
                labels_x = _sci_format
            else:
                labels_x = labels_blank

            ## Label
            if i == j:
                p = (
                    df
                    >> ggplot()
                    + annotate(
                        "label",
                        x=0,
                        y=0,
                        label=v1,
                    )
                    + theme_void()
                    + guides(color=None)
                )

            ## Scatterplot
            else:
                p = (
                    df
                    >> ggplot(aes(v2, v1, color="factor("+sweep_ind+")"))
                    + geom_point(size=0.1)
                    + scale_x_continuous(
                        breaks=breaks_min,
                        labels=labels_x,
                    )
                    + scale_y_continuous(
                        breaks=breaks_min,
                        labels=labels_y,
                    )
                    + guides(color=None)
                    + theme_minimal()
                    + theme(
                        axis_title=element_text(va="top", size=12),
                    )
                )

            _ = p._draw_using_figure(fig, [ax])


    ## Plot
    # NB Returning the figure causes a "double plot" in Jupyter....
    fig.show()
Beispiel #10
0
def plot_scattermat(df, var=None):
    r"""Create a scatterplot matrix

    Create a scatterplot matrix. Often used to visualize a design (set of inputs
    points) before evaluating the functions.

    Usually called as a dispatch from plot_auto().

    Args:
        var (list of strings): Variables to plot

    Returns:
        ggplot: Scatterplot matrix

    Examples:

        >>> import grama as gr
        >>> import matplotlib.pyplot as plt
        >>> from grama.models import make_cantilever_beam
        >>> md = make_cantilever_beam()
        >>> ## Dispatch from autoplotter
        >>> (
        >>>     md
        >>>     >> gr.ev_sample(n=100, df_det="nom", skip=True)
        >>>     >> gr.pt_auto()
        >>> )
        >>> ## Re-create plot without metadata
        >>> (
        >>>     md
        >>>     >> gr.ev_sample(n=100, df_det="nom")
        >>>     >> gr.pt_scattermat(var=md.var)
        >>> )

    """
    if var is None:
        raise ValueError("Must provide input columns list as keyword var")

    ## Define helpers
    labels_blank = lambda v: [""] * len(v)
    breaks_min = lambda lims: (lims[0], 0.5 * (lims[0] + lims[1]), lims[1])

    ## Make blank figure
    fig = (
        df
        >> ggplot()
        + geom_blank()
        + theme_void()
    ).draw(show=False)

    gs = gridspec.GridSpec(len(var), len(var))
    for i, v1 in enumerate(var):
        for j, v2 in enumerate(var):
            ax = fig.add_subplot(gs[i, j])
            ## Switch labels
            if j == 0:
                labels_y = _sci_format
            else:
                labels_y = labels_blank
            if i == len(var) - 1:
                labels_x = _sci_format
            else:
                labels_x = labels_blank

            ## Density
            if i == j:
                xmid = 0.5 * (
                    df[v1].min() + df[v1].max()
                )

                p = (
                    df
                    >> ggplot(aes(v1))
                    + geom_density()
                    + scale_x_continuous(
                        breaks=breaks_min,
                        labels=labels_x,
                    )
                    + scale_y_continuous(
                        breaks=breaks_min,
                        labels=labels_y,
                    )
                    + annotate(
                        "label",
                        x=xmid,
                        y=0,
                        label=v1,
                        va="bottom",
                    )
                    + theme_minimal()
                    + labs(title=v1)
                )

            ## Scatterplot
            else:
                p = (
                    df
                    >> ggplot(aes(v2, v1))
                    + geom_point()
                    + scale_x_continuous(
                        breaks=breaks_min,
                        labels=labels_x,
                    )
                    + scale_y_continuous(
                        breaks=breaks_min,
                        labels=labels_y,
                    )
                    + theme_minimal()
                    + theme(
                        axis_title=element_text(va="top", size=12),
                    )
                )

            _ = p._draw_using_figure(fig, [ax])


    ## Plot
    # NB Returning the figure causes a "double plot" in Jupyter....
    fig.show()