Exemple #1
0
def main():
    args = get_input_args()
    df = io_lib.df_from_input(args)

    # extract parameters from arg parser
    nbins = args.nbins[0]
    range_tup = args.range
    layout_tup = args.layout
    alpha = args.alpha[0]
    do_density = args.density
    sharex = args.sharex
    sharey = args.sharey
    cols = args.cols if args.cols else [df.columns[0]]

    validate_args(args, cols, df)
    plot_lib.set_plot_styling(args)

    # no plotting if output requested
    if args.quiet:
        counts, edges = np.histogram(
            df[cols[0]], bins=nbins, range=range_tup, density=do_density)
        centers = edges[:-1] + 0.5 * np.diff(edges)
        df_out = pd.DataFrame({'bins': centers, 'counts': counts})
        io_lib.df_to_output(args, df_out)

    # otherwise do plotting
    else:
        df.hist(cols, bins=nbins, range=range_tup,
                alpha=alpha, sharex=sharex, sharey=sharey, layout=layout_tup,
                normed=do_density)

        plot_lib.refine_plot(args)
        plot_lib.show(args)
Exemple #2
0
def main():
    msg = textwrap.dedent("""
        Creates interactive xy plots.  Loosely based around matplotlib's
        pyplot.plot command.

        -----------------------------------------------------------------------
        Examples:

            * Really simple plot
                p.linspace 1 10 7 | p.plot -x c0 -y c0

            * Plot two traces
                p.linspace 0 6.28 100\\
                | p.df 'df["cos"]=np.cos(df.t)' 'df["sin"]=np.sin(df.t)'\\
                        --names t\\
                | p.plot -x t -y sin cos\\
                         --style '.-' 'o-' --alpha 1 .2 --legend best

            * Plot sea-level time series
                p.example_data -d sealevel\\
                | p.plot -x year -y sealevel_mm --style '.'\\
                --xlabel year --ylabel 'relative sea level (mm)'\\
                --title 'Sea Level Rise' --legend best --xlim 1995 2015
        -----------------------------------------------------------------------
        """)

    #  read command line arguments
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter, description=msg)

    arg_lib.add_args(parser, 'io_in', 'xy_plotting', 'decorating')

    parser.add_argument("-a",
                        "--alpha",
                        help="Set opacity level(s)",
                        nargs='+',
                        default=[1.],
                        type=float,
                        metavar='alpha')

    # parse arguments
    args = parser.parse_args()

    # get the input dataframe
    df = io_lib.df_from_input(args)

    # set the appropriate theme
    plot_lib.set_plot_styling(args)

    # draw the plot
    plot_lib.draw_xy_plot(args, df)
Exemple #3
0
    def test_set_plot_styling(self):
        """set_plot_styling() alters mpl.rcParams
        """
        args = MagicMock(plot_context=["talk"], plot_theme=["darkgrid"], plot_palette=["muted"])
        mpl.rcParams["axes.color_cycle"] = ["m", "c"]
        mpl.rcParams["axes.labelsize"] = 1
        mpl.rcParams["axes.titlesize"] = 1
        rc_pre = dict(mpl.rcParams)
        plot_lib.set_plot_styling(args)
        rc_post = dict(mpl.rcParams)
        self.assertNotEqual(rc_pre["axes.color_cycle"], rc_post["axes.color_cycle"])
        self.assertNotEqual(rc_pre["axes.labelsize"], rc_post["axes.labelsize"])

        self.assertNotEqual(rc_pre["axes.titlesize"], rc_post["axes.titlesize"])
Exemple #4
0
def main():
    msg = textwrap.dedent(
        """
        Creates interactive xy plots.  Loosely based around matplotlib's
        pyplot.plot command.

        -----------------------------------------------------------------------
        Examples:

            * Really simple plot
                p.linspace 1 10 7 | p.plot -x c0 -y c0

            * Plot two traces
                p.linspace 0 6.28 100\\
                | p.df 'df["cos"]=np.cos(df.t)' 'df["sin"]=np.sin(df.t)'\\
                        --names t\\
                | p.plot -x t -y sin cos\\
                         --style '.-' 'o-' --alpha 1 .2 --legend best

            * Plot sea-level time series
                p.example_data -d sealevel\\
                | p.plot -x year -y sealevel_mm --style '.'\\
                --xlabel year --ylabel 'relative sea level (mm)'\\
                --title 'Sea Level Rise' --legend best --xlim 1995 2015
        -----------------------------------------------------------------------
        """
    )

    #  read command line arguments
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter, description=msg)

    arg_lib.add_args(parser, 'io_in', 'xy_plotting', 'decorating')

    parser.add_argument(
        "-a", "--alpha", help="Set opacity level(s)", nargs='+', default=[1.],
        type=float, metavar='alpha')

    # parse arguments
    args = parser.parse_args()

    # get the input dataframe
    df = io_lib.df_from_input(args)

    # set the appropriate theme
    plot_lib.set_plot_styling(args)

    # draw the plot
    plot_lib.draw_xy_plot(args, df)
Exemple #5
0
    def test_set_plot_styling(self):
        """set_plot_styling() alters mpl.rcParams
        """
        args = MagicMock(
            plot_context=['talk'],
            plot_theme=['darkgrid'],
            plot_palette=['muted'],
        )
        mpl.rcParams['axes.labelsize'] = 1
        mpl.rcParams['axes.titlesize'] = 1
        rc_pre = dict(mpl.rcParams)
        plot_lib.set_plot_styling(args)
        rc_post = dict(mpl.rcParams)
        self.assertNotEqual(
            rc_pre['axes.labelsize'], rc_post['axes.labelsize'])

        self.assertNotEqual(
            rc_pre['axes.titlesize'], rc_post['axes.titlesize'])
    def test_set_plot_styling(self):
        """set_plot_styling() alters mpl.rcParams
        """
        args = MagicMock(
            plot_context=['talk'],
            plot_theme=['darkgrid'],
            plot_palette=['muted'],
        )
        mpl.rcParams['axes.labelsize'] = 1
        mpl.rcParams['axes.titlesize'] = 1
        rc_pre = dict(mpl.rcParams)
        plot_lib.set_plot_styling(args)
        rc_post = dict(mpl.rcParams)
        self.assertNotEqual(rc_pre['axes.labelsize'],
                            rc_post['axes.labelsize'])

        self.assertNotEqual(rc_pre['axes.titlesize'],
                            rc_post['axes.titlesize'])
Exemple #7
0
def main():
    args = get_input_args()
    df = io_lib.df_from_input(args)

    # extract parameters from arg parser
    nbins = args.nbins[0]
    range_tup = args.range
    layout_tup = args.layout
    alpha = args.alpha[0]
    do_density = args.density
    sharex = args.sharex
    sharey = args.sharey
    cols = args.cols if args.cols else [df.columns[0]]

    validate_args(args, cols, df)
    plot_lib.set_plot_styling(args)

    # no plotting if output requested
    if args.quiet:
        counts, edges = np.histogram(df[cols[0]],
                                     bins=nbins,
                                     range=range_tup,
                                     density=do_density)
        centers = edges[:-1] + 0.5 * np.diff(edges)
        df_out = pd.DataFrame({'bins': centers, 'counts': counts})
        io_lib.df_to_output(args, df_out)

    # otherwise do plotting
    else:
        df.hist(cols,
                bins=nbins,
                range=range_tup,
                alpha=alpha,
                sharex=sharex,
                sharey=sharey,
                layout=layout_tup,
                normed=do_density)

        plot_lib.refine_plot(args)
        plot_lib.show(args)
Exemple #8
0
def exec_plot_command(args, cmd, df):  # pragma: no cover
    from pandashells.lib import plot_lib
    plot_lib.set_plot_styling(args)
    execute(cmd, scope_entries={'df': df})
    plot_lib.refine_plot(args)
    plot_lib.show(args)
Exemple #9
0
def main():
    msg = textwrap.dedent(
        """
        Plots the emperical cumulative distribution function (ECDF).

        -----------------------------------------------------------------------
        Examples:

            * Plot ECDF for 10k samples from the standard normal distribution.
                p.rand -t normal -n 10000 | p.cdf -c c0

            * Instead of plotting, send ECDF values to stdout
                p.rand -t normal -n 10000 | p.cdf -c c0 -q | head
        -----------------------------------------------------------------------
        """
    )

    # read command line arguments
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter, description=msg)

    # specify column to use
    parser.add_argument(
        "-c", "--col", required=True, nargs=1,
        help="Column to plot distribution")
    parser.add_argument(
        '-n', '--n_points', nargs=1, type=int,
        help='Number of output points (default is twice input len)')
    parser.add_argument(
        '-q', '--quiet', action='store_true', default=False,
        help='Quiet mean no plots. Send numeric output to stdout instead')

    # parse arguments
    arg_lib.add_args(parser, 'decorating', 'io_in', 'io_out',)
    args = parser.parse_args()

    # get the input dataframe and extract column
    df = io_lib.df_from_input(args)
    x = df[args.col[0]].values

    # create the output distribution
    n_out = 2 * len(x) if args.n_points is None else args.n_points[0]
    x_out = np.linspace(min(x), max(x), n_out)
    y_out = ECDF(x)(x_out)

    # send values to stdout if quiet specified
    if args.quiet:
        df_out = pd.DataFrame(
            {'x': x_out, 'p_less': y_out, 'p_greater': 1 - y_out})
        df_out = df_out[['x', 'p_less', 'p_greater']]
        io_lib.df_to_output(args, df_out)
        return

    # set the appropriate theme ad make plot
    plot_lib.set_plot_styling(args)
    pl.plot(x_out, y_out, label='P({} < x)'.format(args.col[0]))
    pl.plot(x_out, 1. - y_out, label='P({} > x)'.format(args.col[0]))
    pl.xlabel('x')
    pl.legend(loc='best')

    plot_lib.refine_plot(args)
    plot_lib.show(args)
Exemple #10
0
def exec_plot_command(args, cmd, df):  # pragma: no cover
    from pandashells.lib import plot_lib
    plot_lib.set_plot_styling(args)
    execute(cmd, scope_entries={'df': df})
    plot_lib.refine_plot(args)
    plot_lib.show(args)