Python matplotlib.pyplot.boxplot() Examples

The following are code examples for showing how to use matplotlib.pyplot.boxplot(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Cheapest-Flights-bot   Author: PhoenixDD   File: Flight Analysis.py    MIT License 6 votes vote down vote up
def task_3_IQR(flight_data):
    plot=plt.boxplot(flight_data['Price'],patch_artist=True)
    for median in plot['medians']:
        median.set(color='#fc0004', linewidth=2)
    for flier in plot['fliers']:
        flier.set(marker='+', color='#e7298a')
    for whisker in plot['whiskers']:
        whisker.set(color='#7570b3', linewidth=2)
    for cap in plot['caps']:
        cap.set(color='#7570b3', linewidth=2)
    for box in plot['boxes']:
        box.set(color='#7570b3', linewidth=2)
        box.set(facecolor='#1b9e77')
    plt.matplotlib.pyplot.savefig('task_3_iqr.png')
    clean_data=[]
    for index,row in flight_data.loc[flight_data['Price'].isin(plot['fliers'][0].get_ydata())].iterrows():
        clean_data.append([row['Price'],row['Date_of_Flight']])
    return pd.DataFrame(clean_data, columns=['Price', 'Date_of_Flight']) 
Example 2
Project: imRICnn   Author: johanna-rock   File: plotting.py    The Unlicense 6 votes vote down vote up
def plot_stat_from_tuples(value_tuples, plot_name, vertical_axis=False):
    if not visualize:
        return
    plt.subplots()

    categories = list(set([r[0] for r in value_tuples]))
    x = range(1, len(categories)+1)
    values = []
    for c in categories:
        cvalues = [v[1] for v in value_tuples if v[0] == c and v[1] is not None]
        values.append(cvalues)

    if vertical_axis:
        plt.boxplot(x, values)
        plt.xticks(x, categories, rotation='vertical')
    else:
        plt.boxplot(values, labels=categories)
    save_or_show_plot(plot_name) 
Example 3
Project: tschdata   Author: tum-lkn   File: basic_processor.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_delays(self):
        """
        Plot delay distribution for all motes
        :return:
        """
        plt.figure()
        delays = []
        for addr in gl_mote_range:
            delays.append(self.get_delays(addr))

        plt.boxplot(delays, showmeans=True, showfliers=False)

        plt.ylabel('delay, s')
        plt.xlabel('mote #')
        plt.grid(True)

        # return means
        return [np.mean(d) for d in delays if len(d) > 0] 
Example 4
Project: tschdata   Author: tum-lkn   File: basic_processor.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_avg_hops(self):
        """
        Plot the distribution of the number of hops for all packets for all motes.
        :return:
        """

        plt.figure()
        hops = []
        for addr in gl_mote_range:
            hops.append(self.get_avg_hops(addr))
        plt.boxplot(hops)

        plt.ylim((0, 5))

        plt.ylabel('hops')
        plt.xlabel('mote #') 
Example 5
Project: SUMO_dy_public   Author: DayuanTan   File: plotXMLAttr.py    GNU General Public License v3.0 6 votes vote down vote up
def main(tag, attr, *xmlfiles):
    data = []
    for xmlfile in xmlfiles:
        stats = Statistics('%s %s' % (tag, attr))
        for elem in parse(xmlfile, tag):
            stats.add(float(elem.getAttribute(attr)), elem.id)
        print(stats)
        data.append(stats.values)
    try:
        import matplotlib.pyplot as plt
    except Exception as e:
        sys.exit(e)
    fig = plt.figure()
    plt.xticks(range(len(xmlfiles)), xmlfiles)
    plt.ylabel("%s %s" % (tag, attr))
    plt.boxplot(data)
    plt.show() 
Example 6
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 6 votes vote down vote up
def _bxp_test_helper(
        stats_kwargs={}, transform_stats=lambda s: s, bxp_kwargs={}):
    np.random.seed(937)
    logstats = mpl.cbook.boxplot_stats(
        np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)), **stats_kwargs)
    fig, ax = plt.subplots()
    if bxp_kwargs.get('vert', True):
        ax.set_yscale('log')
    else:
        ax.set_xscale('log')
    # Work around baseline images generate back when bxp did not respect the
    # boxplot.boxprops.linewidth rcParam when patch_artist is False.
    if not bxp_kwargs.get('patch_artist', False):
        mpl.rcParams['boxplot.boxprops.linewidth'] = \
            mpl.rcParams['lines.linewidth']
    ax.bxp(transform_stats(logstats), **bxp_kwargs) 
Example 7
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 6 votes vote down vote up
def test_boxplot():
    # Randomness used for bootstrapping.
    np.random.seed(937)

    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig, ax = plt.subplots()

    ax.boxplot([x, x], bootstrap=10000, notch=1)
    ax.set_ylim((-30, 30))

    # Reuse testcase from above for a labeled data test
    data = {"x": [x, x]}
    fig, ax = plt.subplots()
    ax.boxplot("x", bootstrap=10000, notch=1, data=data)
    ax.set_ylim((-30, 30)) 
Example 8
Project: yarll   Author: arnomoonens   File: envs_statistics.py    MIT License 6 votes vote down vote up
def main():
    args = parser.parse_args()

    _, _, env_spec_files = next(os.walk(args.envs_dir))
    values = None
    for env_spec_file in env_spec_files:
        with open(os.path.join(args.envs_dir, env_spec_file)) as f:
            envs = json.load(f)
            if values is None:
                values = [{} for _ in range(len(envs))]
            for i, env in enumerate(envs):
                for key, value in env.items():
                    if key == "name":
                        continue
                    values[i].setdefault(key, []).append(value)
    keys = values[0].keys()
    for key in keys:
        fig = plt.figure()
        plt.boxplot([env[key] for env in values])
        plt.title(key)
        fig.canvas.set_window_title(key)
    plt.show() 
Example 9
Project: bokeh-playground   Author: andrewgryan   File: main.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    facecolor = "SteelBlue"
    values = np.random.randn(100)
    tenth = np.percentile(values, 10)
    ninetieth = np.percentile(values, 90)
    print(tenth, ninetieth)
    width = 0.05
    height = ninetieth - tenth
    x = 1 - (width / 2)
    y = tenth
    patch = mpl.patches.Rectangle((x, y), width, height, edgecolor='black', facecolor=facecolor)
    ax = plt.gca()
    ax.add_patch(patch)
    boxes = plt.boxplot(values, patch_artist=True)
    for box in boxes['boxes']:
        box.set(facecolor=facecolor)
    # plt.show()
    plt.savefig("double-box") 
Example 10
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 6 votes vote down vote up
def _bxp_test_helper(
        stats_kwargs={}, transform_stats=lambda s: s, bxp_kwargs={}):
    np.random.seed(937)
    logstats = mpl.cbook.boxplot_stats(
        np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)), **stats_kwargs)
    fig, ax = plt.subplots()
    if bxp_kwargs.get('vert', True):
        ax.set_yscale('log')
    else:
        ax.set_xscale('log')
    # Work around baseline images generate back when bxp did not respect the
    # boxplot.boxprops.linewidth rcParam when patch_artist is False.
    if not bxp_kwargs.get('patch_artist', False):
        mpl.rcParams['boxplot.boxprops.linewidth'] = \
            mpl.rcParams['lines.linewidth']
    ax.bxp(transform_stats(logstats), **bxp_kwargs) 
Example 11
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 6 votes vote down vote up
def test_boxplot():
    # Randomness used for bootstrapping.
    np.random.seed(937)

    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig, ax = plt.subplots()

    ax.boxplot([x, x], bootstrap=10000, notch=1)
    ax.set_ylim((-30, 30))

    # Reuse testcase from above for a labeled data test
    data = {"x": [x, x]}
    fig, ax = plt.subplots()
    ax.boxplot("x", bootstrap=10000, notch=1, data=data)
    ax.set_ylim((-30, 30)) 
Example 12
Project: phoneticSimilarity   Author: ronggong   File: anova_calculation.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def box_plot(data, feature_name):
    # notched plot
    fig = plt.figure()
    plt.boxplot(data, 1, "r+")
    plt.ylabel("Value distribution", fontsize=15)
    plt.xticks([1, 2, 3], ["Professional", "Amateur\ntrain val", "Amateur\ntest"], fontsize=15)
    # plt.title(feature_name)
    plt.tight_layout()
    return fig 
Example 13
Project: Pesquisas   Author: danilopcarlotti   File: statistical_analysis.py    Apache License 2.0 5 votes vote down vote up
def plotarbox(self,tupleT,title):
		plt.boxplot(tupleT)
		plt.title(title)
		plt.tight_layout()
		plt.savefig(title+".png", dpi=80) 
Example 14
Project: classification-of-encrypted-traffic   Author: SalikLP   File: data_exploration.py    MIT License 5 votes vote down vote up
def createBoxplotsFromColumns(title,param, param1):

    plt.title(title)
    plt.boxplot([param,param1])

    plt.savefig('boxplots/boxplot:%s.png' % title,dpi=300)
    plt.gcf().clear() 
Example 15
Project: stylometry   Author: worldwise001   File: __init__.py    MIT License 5 votes vote down vote up
def boxplot_single(filename, data, xr=None, yr=None, x_title='', y_title='', title=None):
    if title is None:
        title = filename

    author_labels = []
    author_data = []
    for author in data:
        author_labels.append(author)
        author_data.append(data[author])

    for start in range(0, len(data), 50):
        end = start+50
        if end > len(data):
            end = len(data)
        width = end-start
        fig = plt.figure(figsize=(width,12), dpi=600)
        ax = plt.axes()

        bp = plt.boxplot(author_data[start:end], positions=range(1, width+1), widths = 0.8)
        plt.xlim(0, width+1)
        ax.set_xticklabels(author_labels[start:end], rotation=70)
        ax.set_xticks(range(1, width+1))
        if xr is not None:
            plt.xlim(xr)
        if yr is not None:
            plt.ylim(yr)
        plt.xlabel(x_title)
        plt.ylabel(y_title)
        plt.title(title)
        plt.tight_layout()

        plt.savefig('%s_%d.png' % (filename,start), format='png')
        plt.savefig('%s_%d.eps' % (filename,start), format='eps')
        plt.close() 
Example 16
Project: MLPractices   Author: carefree0910   File: DataToolkit.py    MIT License 5 votes vote down vote up
def box_plot(self):
        plt.figure()
        plt.boxplot(self._data, vert=False, showmeans=True)
        plt.show() 
Example 17
Project: amplicon_sequencing_pipeline   Author: thomasgurry   File: AutoPlot.py    MIT License 5 votes vote down vote up
def plotAlphaDiversities(self, alphaDiversityFile, figure_filename):
        # Take an alpha diversity file and create a box plot
        with open(alphaDiversityFile,'r') as fid:
            all_lines = fid.readlines()
            alpha_diversities = [float(line.split()[1]) for line in all_lines[1:]]
            sampleIDs = [line.split()[0] for line in all_lines[1:]]
            figure()
            plt.boxplot(alpha_diversities)
            plt.xlabel('Sample category')
            plt.ylabel('Alpha diversity')
            plt.savefig(figure_filename) 
Example 18
Project: PyMAP   Author: AminMahpour   File: Stats.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, beta_list, sample_id, lab):
        fl = Transform(beta_list, sample_id, lab)
        pp.boxplot(fl, labels=[i.name for i in lab])
        pp.show() 
Example 19
Project: tschdata   Author: tum-lkn   File: basic_processor.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_delay_per_mote(self, addr):
        """
        Plot the delay distribution for motes
        :return:
        """
        plt.figure()
        plt.boxplot(self.get_delays(addr))
        plt.grid(True) 
Example 20
Project: HiCembler   Author: lpryszcz   File: test_plot.py    GNU General Public License v3.0 5 votes vote down vote up
def main(fn, method="ward"): #
    d, bin_chr, bin_position, contig2size = load_matrix(fn, remove_shorter=0)
    sizes = np.diff(bin_position, axis=1)[:, 0] / 1000
    contacts = d.diagonal()
    print d.sum(), d.diagonal().sum()
    # get bins
    bins = np.arange(1, 101, 5)
        
    # get counts
    contacts = [[] for i in range(len(bins)+1)]
    for s, c in zip(np.digitize(sizes, bins, right=1), d.diagonal()):
        contacts[s].append(c)
    print len(contacts), len(bins), len(sizes)#, contacts# np.digitize(sizes, bins, right=1)
    plt.title("HiC contacts at given distance")
    plt.boxplot(contacts[:-1], 1, '', positions=bins, widths=.75*bins[0])#; plt.legend("HiC data")
    plt.xticks(rotation=90)

    plt.xlabel("contig size [kb]")
    plt.ylabel("self contacts")
    plt.xlim(xmin=-bins[0])
    plt.ylim(ymin=0)#, ymax=20)
    #plt.yscale('log')
    #plt.show()
    outfn = fn+".selfcontacts.png"
    plt.savefig(outfn)
    print "Figure saved as: %s"%outfn 
Example 21
Project: rgz_rcnn   Author: chenwuperth   File: prob_vs_cl.py    MIT License 5 votes vote down vote up
def plot_prob_cl_box(prob_cl_mapping_list, plot_outliers=False):
    ks = prob_cl_mapping_list.keys()
    ks.sort()
    for i, classname in enumerate(ks):
        v = prob_cl_mapping_list[classname]
        data = [[], [], [], []]
        labels = ['0.6~0.7', '0.7~0.8', '0.8~0.9', '0.9~1.0']
        prob_list = v[0]
        cl_list = v[1]
        for cl, prob in zip(cl_list, prob_list):
            if 0.6 <= cl < 0.7:
                ind = 0
            elif 0.7 <= cl < 0.8:
                ind = 1
            elif 0.8 <= cl < 0.9:
                ind = 2
            elif 0.9 <= cl <= 1.0:
                ind = 3
            else:
                raise Exception("invalid CL: %.3f" % cl)
            data[ind].append(prob)
        ax = plt.subplot(3, 2, i + 1)
        if (plot_outliers):
            symb = '+'
        else:
            symb = ''
        plt.boxplot(data, labels=labels, sym=symb)
        plt.xlabel('Consensus level')
        plt.grid(True, linestyle='-', which='major', color='lightgrey',
               alpha=0.5, axis='y')
        if (i % 2 == 0):
            #plt.ylabel('Classification probability')
            plt.ylabel('Probability')
        # if (not plot_outliers):
        #     plt.ylim([0.6, 1.0])
        ax.set_title('%s' % classname.replace('_', 'C_') + 'P')
    #plt.suptitle('Probability vs. Consensus level')
    plt.tight_layout(h_pad=0.0)
    plt.show() 
Example 22
Project: SUMO_dy_public   Author: DayuanTan   File: plotFlows.py    GNU General Public License v3.0 5 votes vote down vote up
def get_options(args=None):
    optParser = OptionParser()
    optParser.add_option("-d", "--detector-file", dest="detfile",
                         help="read detectors from FILE (mandatory)", metavar="FILE")
    optParser.add_option("-c", "--flow-column", dest="flowcol", default="qPKW",
                         help="which column contains flows", metavar="STRING")
    optParser.add_option("-z", "--respect-zero", action="store_true", dest="respectzero",
                         default=False, help="respect detectors without data (or with permanent zero) with zero flow")
    optParser.add_option("-i", "--interval", type="int", default=60, help="aggregation interval in minutes")
    optParser.add_option("--long-names", action="store_true", dest="longnames",
                         default=False, help="do not use abbreviated names for detector groups")
    optParser.add_option("--edge-names", action="store_true", dest="edgenames",
                         default=False, help="include detector group edge name in output")
    optParser.add_option("-b", "--begin", type="float", default=0, help="begin time in minutes")
    optParser.add_option("-e", "--end", type="float", default=None, help="end time in minutes")
    optParser.add_option("-o", "--csv-output", dest="csv_output", help="write plot data with prefix", metavar="FILE")
    optParser.add_option("--extension", help="extension for saving plots", default="png")
    optParser.add_option("-s", "--show", action="store_true", default=False, help="show plot directly")
    optParser.add_option("-g", "--group-by", dest="groupby", help="group detectors (all, none, type) ", default="all")
    optParser.add_option("-t", "--type-filter", dest="typefilter", help="only show selected types")
    optParser.add_option("-r", "--reference-flow", dest="reference", help="reference flow file that should not be grouped", metavar="FILE")
    optParser.add_option("--id-filter", dest="idfilter", help="filter detector ids")
    optParser.add_option("--single-plot", action="store_true", dest="singleplot", default=False, help="put averything in a single plot")
    #optParser.add_option("--boxplot", action="store_true", dest="boxplot", default=False, help="boxplot")
    optParser.add_option("-m", "--max-files", type="int", dest="maxfiles", help="limit number of input files")
    optParser.add_option("-n", "--no-legend", dest="nolegend", action="store_true", default=False, help="dont draw legend")
    optParser.add_option("-v", "--verbose", action="store_true", default=False, help="tell me what you are doing")
    options, args = optParser.parse_args(args=args)
    options.flowfiles = args
    if options.maxfiles is not None:
        options.flowfiles = options.flowfiles[:options.maxfiles]
    print(options.flowfiles)
    if not options.detfile or not options.flowfiles:
        optParser.print_help()
        sys.exit()
    return options 
Example 23
Project: SUMO_dy_public   Author: DayuanTan   File: plotFlows.py    GNU General Public License v3.0 5 votes vote down vote up
def plot(options, allData, prefix="", linestyle="-"):
    if not options.singleplot:
        fig = plt.figure()

    labelsuffix = ""
    if prefix != "":
        labelsuffix = "_%s" % prefix
    plt.ylabel("Avg. Simulation Flow %s" % prefix)

    plt.xlabel("Minutes")
    x = range(int(options.begin), int(options.end), options.interval)
    #if options.boxplot:
    #    for f, data in zip(options.flowfiles, allData):
    #        label = f[-12:-4] + labelsuffix
    #        #plt.plot(x, data, label=label, linestyle=linestyle)
    #        label = label.replace(";","_")
    #        if options.csv_output is not None:
    #            write_csv(x, data, options.csv_output + label + ".csv")
    #    for f, data in zip(options.flowfiles, allData[:1]):
    #        label = f[-12:-4] + labelsuffix
    #        plt.plot(x, data, label=label, linestyle=linestyle)
    #        label = label.replace(";","_")
    #    plt.boxplot(x, allData[1:])
    #else:
    for f, data in zip(options.flowfiles, allData):
        label = f[-12:-4] + labelsuffix
        plt.plot(x, data, label=label, linestyle=linestyle)
        label = label.replace(";","_")
        if options.csv_output is not None:
            write_csv(x, data, options.csv_output + label + ".csv")
    if not options.nolegend:
        plt.legend(loc='best')
    if not options.singleplot:
        plt.savefig(label + "." + options.extension) 
Example 24
Project: SUMO_dy_public   Author: DayuanTan   File: duaIterate_analysis.py    GNU General Public License v3.0 5 votes vote down vote up
def matplot(output):
    if output is not None:
        import matplotlib
        if output != 'SHOW':
            matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        plt.boxplot(parse_trip_durations())
        if output == 'SHOW':
            plt.show()
        else:
            plt.savefig(output)
            plt.close() 
Example 25
Project: psychrometric-chart-makeover   Author: buds-lab   File: categorical.py    MIT License 5 votes vote down vote up
def restyle_boxplot(self, artist_dict, color, props):
        """Take a drawn matplotlib boxplot and make it look nice."""
        for box in artist_dict["boxes"]:
            box.update(dict(facecolor=color,
                            zorder=.9,
                            edgecolor=self.gray,
                            linewidth=self.linewidth))
            box.update(props["box"])
        for whisk in artist_dict["whiskers"]:
            whisk.update(dict(color=self.gray,
                              linewidth=self.linewidth,
                              linestyle="-"))
            whisk.update(props["whisker"])
        for cap in artist_dict["caps"]:
            cap.update(dict(color=self.gray,
                            linewidth=self.linewidth))
            cap.update(props["cap"])
        for med in artist_dict["medians"]:
            med.update(dict(color=self.gray,
                            linewidth=self.linewidth))
            med.update(props["median"])
        for fly in artist_dict["fliers"]:
            fly.update(dict(markerfacecolor=self.gray,
                            marker="d",
                            markeredgecolor=self.gray,
                            markersize=self.fliersize))
            fly.update(props["flier"]) 
Example 26
Project: psychrometric-chart-makeover   Author: buds-lab   File: categorical.py    MIT License 5 votes vote down vote up
def draw_box_lines(self, ax, data, support, density, center):
        """Draw boxplot information at center of the density."""
        # Compute the boxplot statistics
        q25, q50, q75 = np.percentile(data, [25, 50, 75])
        whisker_lim = 1.5 * iqr(data)
        h1 = np.min(data[data >= (q25 - whisker_lim)])
        h2 = np.max(data[data <= (q75 + whisker_lim)])

        # Draw a boxplot using lines and a point
        if self.orient == "v":
            ax.plot([center, center], [h1, h2],
                    linewidth=self.linewidth,
                    color=self.gray)
            ax.plot([center, center], [q25, q75],
                    linewidth=self.linewidth * 3,
                    color=self.gray)
            ax.scatter(center, q50,
                       zorder=3,
                       color="white",
                       edgecolor=self.gray,
                       s=np.square(self.linewidth * 2))
        else:
            ax.plot([h1, h2], [center, center],
                    linewidth=self.linewidth,
                    color=self.gray)
            ax.plot([q25, q75], [center, center],
                    linewidth=self.linewidth * 3,
                    color=self.gray)
            ax.scatter(q50, center,
                       zorder=3,
                       color="white",
                       edgecolor=self.gray,
                       s=np.square(self.linewidth * 2)) 
Example 27
Project: psychrometric-chart-makeover   Author: buds-lab   File: categorical.py    MIT License 5 votes vote down vote up
def draw_stripplot(self, ax, kws):
        """Draw the points onto `ax`."""
        # Set the default zorder to 2.1, so that the points
        # will be drawn on top of line elements (like in a boxplot)
        for i, group_data in enumerate(self.plot_data):
            if self.plot_hues is None or not self.dodge:

                if self.hue_names is None:
                    hue_mask = np.ones(group_data.size, np.bool)
                else:
                    hue_mask = np.array([h in self.hue_names
                                         for h in self.plot_hues[i]], np.bool)
                    # Broken on older numpys
                    # hue_mask = np.in1d(self.plot_hues[i], self.hue_names)

                strip_data = group_data[hue_mask]

                # Plot the points in centered positions
                cat_pos = np.ones(strip_data.size) * i
                cat_pos += self.jitterer(len(strip_data))
                kws.update(c=self.point_colors[i][hue_mask])
                if self.orient == "v":
                    ax.scatter(cat_pos, strip_data, **kws)
                else:
                    ax.scatter(strip_data, cat_pos, **kws)

            else:
                offsets = self.hue_offsets
                for j, hue_level in enumerate(self.hue_names):
                    hue_mask = self.plot_hues[i] == hue_level
                    strip_data = group_data[hue_mask]

                    # Plot the points in centered positions
                    center = i + offsets[j]
                    cat_pos = np.ones(strip_data.size) * center
                    cat_pos += self.jitterer(len(strip_data))
                    kws.update(c=self.point_colors[i][hue_mask])
                    if self.orient == "v":
                        ax.scatter(cat_pos, strip_data, **kws)
                    else:
                        ax.scatter(strip_data, cat_pos, **kws) 
Example 28
Project: psychrometric-chart-makeover   Author: buds-lab   File: categorical.py    MIT License 5 votes vote down vote up
def boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None,
            orient=None, color=None, palette=None, saturation=.75,
            width=.8, dodge=True, fliersize=5, linewidth=None,
            whis=1.5, notch=False, ax=None, **kwargs):

    plotter = _BoxPlotter(x, y, hue, data, order, hue_order,
                          orient, color, palette, saturation,
                          width, dodge, fliersize, linewidth)

    if ax is None:
        ax = plt.gca()
    kwargs.update(dict(whis=whis, notch=notch))

    plotter.plot(ax, kwargs)
    return ax 
Example 29
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_sym2():
    # Randomness used for bootstrapping.
    np.random.seed(937)

    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig, [ax1, ax2] = plt.subplots(1, 2)

    ax1.boxplot([x, x], bootstrap=10000, sym='^')
    ax1.set_ylim((-30, 30))

    ax2.boxplot([x, x], bootstrap=10000, sym='g')
    ax2.set_ylim((-30, 30)) 
Example 30
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_sym():
    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig, ax = plt.subplots()

    ax.boxplot([x, x], sym='gs')
    ax.set_ylim((-30, 30)) 
Example 31
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_autorange_whiskers():
    # Randomness used for bootstrapping.
    np.random.seed(937)

    x = np.ones(140)
    x = np.hstack([0, x, 2])

    fig1, ax1 = plt.subplots()
    ax1.boxplot([x, x], bootstrap=10000, notch=1)
    ax1.set_ylim((-5, 5))

    fig2, ax2 = plt.subplots()
    ax2.boxplot([x, x], bootstrap=10000, notch=1, autorange=True)
    ax2.set_ylim((-5, 5)) 
Example 32
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_with_CIarray():
    # Randomness used for bootstrapping.
    np.random.seed(937)

    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    CIs = np.array([[-1.5, 3.], [-1., 3.5]])

    # show 1 boxplot with mpl medians/conf. intervals, 1 with manual values
    ax.boxplot([x, x], bootstrap=10000, usermedians=[None, 1.0],
               conf_intervals=CIs, notch=1)
    ax.set_ylim((-30, 30)) 
Example 33
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_no_weird_whisker():
    x = np.array([3, 9000, 150, 88, 350, 200000, 1400, 960],
                 dtype=np.float64)
    ax1 = plt.axes()
    ax1.boxplot(x)
    ax1.set_yscale('log')
    ax1.yaxis.grid(False, which='minor')
    ax1.xaxis.grid(False) 
Example 34
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_bad_medians_1():
    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig, ax = plt.subplots()
    with pytest.raises(ValueError):
        ax.boxplot(x, usermedians=[1, 2]) 
Example 35
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_bad_medians_2():
    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig, ax = plt.subplots()
    with pytest.raises(ValueError):
        ax.boxplot([x, x], usermedians=[[1, 2], [1, 2]]) 
Example 36
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_zorder():
    x = np.arange(10)
    fix, ax = plt.subplots()
    assert ax.boxplot(x)['boxes'][0].get_zorder() == 2
    assert ax.boxplot(x, zorder=10)['boxes'][0].get_zorder() == 10 
Example 37
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_bad_ci_2():
    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig, ax = plt.subplots()
    with pytest.raises(ValueError):
        ax.boxplot([x, x], conf_intervals=[[1, 2], [1]]) 
Example 38
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_mod_artist_after_plotting():
    x = [0.15, 0.11, 0.06, 0.06, 0.12, 0.56, -0.56]
    fig, ax = plt.subplots()
    bp = ax.boxplot(x, sym="o")
    for key in bp:
        for obj in bp[key]:
            obj.set_color('green') 
Example 39
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_manage_xticks():
    _, ax = plt.subplots()
    ax.set_xlim(0, 4)
    old_xlim = ax.get_xlim()
    np.random.seed(0)
    y1 = np.random.normal(10, 3, 20)
    y2 = np.random.normal(3, 1, 20)
    ax.boxplot([y1, y2], positions=[1, 2], manage_ticks=False)
    new_xlim = ax.get_xlim()
    assert_array_equal(old_xlim, new_xlim) 
Example 40
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_not_single():
    fig, ax = plt.subplots()
    ax.boxplot(np.random.rand(100), positions=[3])
    ax.boxplot(np.random.rand(100), positions=[5])
    fig.canvas.draw()
    assert ax.get_xlim() == (2.5, 5.5)
    assert list(ax.get_xticks()) == [3, 5]
    assert [t.get_text() for t in ax.get_xticklabels()] == ["3", "5"] 
Example 41
Project: expt-analysis   Author: google   File: data_analysis.py    Apache License 2.0 5 votes vote down vote up
def PandasBoxPlt(
    df, col, by, ylim=None, yscale=None, pltTitle=None, figSize=None):

  # demonstrate how to customize the display different elements:
  boxprops = dict(linestyle='-', linewidth=4, color='k')
  medianprops = dict(linestyle='-', linewidth=4, color='k')

  bp = df.boxplot(
      column=col, by=by,
      showfliers=False, showmeans=True,
      boxprops=boxprops, medianprops=medianprops)

  if yscale is not None:
    plt.yscale(yscale)
  [ax_tmp.set_xlabel('') for ax_tmp in np.asarray(bp).reshape(-1)]
  fig = np.asarray(bp).reshape(-1)[0].get_figure()

  if figSize is not None:
    fig.set_size_inches(figSize[0], figSize[1])

  plt.xticks(rotation=45)
  axes = plt.gca()

  if pltTitle is not None:
    plt.title(pltTitle)

  if ylim is not None:
    axes.set_ylim(ylim)

  return plt.show() 
Example 42
Project: pythonscripts   Author: mickaelsilva   File: alleleSizeStats.py    GNU General Public License v2.0 5 votes vote down vote up
def buildPlot(nparray,ReturnValues):
	
	try:
		plt.close('all')
	except:
		pass
	if not ReturnValues	:
		plt.figure()
	else:
		fig,ax = plt.subplots(figsize=(20,10))
		#bp=plt.boxplot(nparray,patch_artist=True)
		bp=plt.boxplot(nparray, whis=[5,95])
	
	
		
	handles, labels = plt.gca().get_legend_handles_labels()

	#print labels
	handle_list, label_list = [], []
	by_label = OrderedDict(zip(labels, handles))
	
	frame1 = plt.gca()			
	frame1.axes.get_xaxis().set_visible(False)
	frame1.axes.get_xaxis().set_ticks([])
	plt.ylabel('nucleotide length of the gene')
	plt.title("allele size comparison per gene for "+str(len(nparray))+"genes")
	
	#for box in bp['boxes']:
		# change outline color
	#	box.set( color='white', linewidth=2)
    # change fill color
	#	box.set( facecolor = 'black' )
	
	#plt.setp(bp['boxes'], color='blue')
	plt.setp(bp['whiskers'], color='blue')
	plt.setp(bp['fliers'],marker='o', markerfacecolor='green',linestyle='none')
	
	return plt,ax,fig,bp 
Example 43
Project: mousestyles   Author: berkeley-stat222   File: path_diversity_plotting.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plot_box(list_of_arrays, title="Box Plot of Distribution", width=4,
             height=4):
    r"""
    Make a box plot of the desired metric (path length, speed, angle, etc)
    per mouse, day or strain.

    Parameters
    ----------
    list_of_arrays : list
        each element of the list is a numpy array containing data on the
        metric to be plotted per mouse, day, or strain.Data is typically
        generated from another function in the package.

    title : str
        desired title of the plot

    width : int
        first argument in figure size specifying width of plot

    height : int
        second argument in figure size specifying height of plot

    Returns
    -------
    box plot : box plot of the desired metric combinations
    """
    if len(list_of_arrays) == 0:
        raise ValueError("List of arrays can not be empty")
    if type(title) != str:
        raise TypeError("Title must be a string")
    if type(list_of_arrays) != list:
        raise TypeError("List of arrays must be a list")
    plt.boxplot(list_of_arrays)
    plt.title(title)
    plt.figure(figsize=(width, height))
    plt.show() 
Example 44
Project: MedicalSegmentation   Author: ThomasT3563   File: compute_display_metrics.py    GNU General Public License v3.0 5 votes vote down vote up
def display_metric_boards(confusion_matrix,TruePos,GT_sum,PR_sum,
                          labels_names,labels_numbers):
    """
        Use with compute stats
        With board returned by compute_stats, plot graphs of different metrics
            - accuracy, balanced accuracy
            - dice score, balanced dice score 
    """
    
    print("\nConfusion matrix:")
    print(confusion_matrix)

    accuracy_TAB = TruePos/GT_sum
    accuracy = np.mean(np.sum(TruePos,axis=1)/np.sum(GT_sum,axis=1))
    balanced_acc = np.mean(accuracy_TAB)
    print("\naccuracy          = %7.7s" % accuracy)
    print("balanced accuracy = %7.7s" % balanced_acc)
    
    #figure accuracy
    plt.figure()
    plt.boxplot(accuracy_TAB[:,:],sym='x',whis=5,labels=labels_names)
    plt.title("Accuracy Boxplot")
    plt.show()
    
    smooth = 1
    dice_TAB = (2*TruePos+smooth) / (GT_sum+PR_sum+smooth)
    dice = (2*np.sum(TruePos)+smooth)/(np.sum(GT_sum)+np.sum(PR_sum)+smooth)
    balanced_dice = np.mean(dice_TAB)
    
    print("\ndice              = %7.7s" % dice)
    print("balanced dice     = %7.7s" % balanced_dice)
    
    #figure dice
    plt.figure()
    plt.boxplot(dice_TAB[:,:],sym='x',whis=5,labels=labels_names)
    plt.title("Dice Boxplot")
    plt.show()
    
    return (accuracy_TAB,accuracy,balanced_acc),(dice_TAB,dice,balanced_dice) 
Example 45
Project: riboSeed   Author: nickp60   File: riboSpec.py    MIT License 5 votes vote down vote up
def make_silly_boxplot(vals, outpath, names=None, title="", yline=None):  #pragma: nocover
    """
    yline can either be an number or a tuple: (25%, 50%, 75% quartiles)
    """
    fig = pyplot.figure(figsize=(6, 6)) # in inches
    ax = pyplot.axes()
    if isinstance(vals[0], list):
        pyplot.boxplot(vals, 0, 'rs', 1)
        if names is not None:
            assert len(names) == len(vals), \
                "number of names does not equal number of sets!"
            ax.set_xticklabels(names)

        for i, data in enumerate(vals) :
            for d in data:
                pyplot.scatter(x=i + 1 + random.uniform(-.1, .2),
                               y=d + random.uniform(-.2, .2),
                               alpha=.3)
    else:
        pyplot.boxplot(vals, 0, 'rs', 1)
        for d in vals:
            pyplot.scatter(x=1 + random.uniform(-.1, .1),
                        y=d + random.uniform(-.2, .2),
                        alpha=.3)
    if yline is not None:
        if isinstance(yline, tuple):
            # print(yline)
            assert len(yline)== 3,\
                "yline must either be a single number or a 3-lenght tuple"
            pyplot.axhline(yline[0], color="green", linestyle="--"),
            pyplot.axhline(yline[1], color="green"),
            pyplot.axhline(yline[2], color="green", linestyle="--"),
        else:
            pyplot.axhline(yline, color="green"),
    pyplot.title(title)
    fig.savefig(outpath)
    pyplot.close(fig) 
Example 46
Project: reactIDR   Author: carushi   File: evaluate_IDR_csv.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_boxplot_class(self, dict_count, prefix):
        for sp in ["all", "canonical"]:
            answer = set_positive_negative(dict_count[0]['ref'], sp)
            fig=plt.figure(1)
            count = 0
            # for score_type in ["count", "score", "IDR", "IDR-HMM-final", "BUMHMM", "noHMMIDR", 'PROBer']:
            for score_type in ["count", "score", "IDR-HMM-final"]:
                all_data = []
                row_labels = []
                for i, sample in enumerate(["case", "cont"]):
                    if score_type == "score" and sample == "cont":  continue
                    if score_type not in dict_count[i]:
                        continue
                    pos = self.get_pos(sample, score_type)
                    if score_type == "score":
                        pred = [float(val) for val in dict_count[i][score_type] if val == val]
                    elif score_type == "count":
                        pred = [log_count(val) for val in dict_count[i][score_type]]
                    else:
                        pred = [one_minus_nan_float(val) if "IDR" in score_type else nan_float(val) for val in dict_count[i][score_type]]
                    # pred = normalized_vec(pred)
                    if len(pred) != len(answer):
                        print('Length error:', score_type)
                        print('score length=', len(answer), score_type+" length=", len(pred))
                        return
                    all_data.append([pred[i] for i in range(len(pred)) if answer[i] == pos and pred[i] == pred[i]])
                    all_data.append([pred[i] for i in range(len(pred)) if answer[i] != pos and pred[i] == pred[i]])
                    row_labels.extend([sample+"_"+["a", "s"][i]+"\n"+score_type[0:7], sample+"_"+["s", "a"][i]+"\n"+score_type[0:7]])
                plt.figure()
                # print(prefix, score_type, len(all_data), len(row_labels), row_labels)
                if len(all_data) == 0:
                    continue
                assert len(all_data) == len(row_labels)
                plt.boxplot(all_data, labels=row_labels, showmeans=True)
                plt.savefig(prefix+"_"+sp+"_"+score_type+"_boxplot_idr.pdf")
                plt.clf() 
Example 47
Project: adversarial_time_to_event   Author: paidamoyo   File: metrics.py    MIT License 5 votes vote down vote up
def box_plots(empirical, predicted, name='data', time='days', log_domain=True):
    plt.figure()
    if log_domain:
        plt.yscale('log')
    plt.boxplot(x=predicted, sym='o', notch=0, whis='range')
    plt.scatter(x=np.arange(start=1, stop=len(predicted) + 1), y=empirical, color='purple', label='empirical')
    plt.legend(loc='best', fontsize=10)
    plt.xticks(fontsize=5)
    plt.ylabel('t ({})'.format(time))
    plt.xlabel('Observation index')
    plt.savefig('plots/{}_box_plot'.format(name)) 
Example 48
Project: adversarial_time_to_event   Author: paidamoyo   File: metrics.py    MIT License 5 votes vote down vote up
def hist_plots(samples, name, xlabel, empirical=None):
    plt.figure()
    plt.axvline(x=np.mean(samples), color='grey', label='mean', linestyle='--', )
    if empirical:
        plt.axvline(x=empirical, color='purple', label='empirical', linestyle='--', )
    plt.legend(loc='best', fontsize=10)
    plt.hist(samples, bins=25)
    plt.xlabel(xlabel)
    plt.savefig("plots/{}_hist".format(name))
    plt.figure()
    plt.boxplot(x=samples, sym='o', notch=0, whis='range')
    plt.scatter(x=1, y=np.mean(samples), color='purple', label='mean')
    plt.legend(loc='best', fontsize=10)
    plt.savefig('plots/{}_box_plot'.format(name)) 
Example 49
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_dates_pandas(pd):
    # smoke test for boxplot and dates in pandas
    data = np.random.rand(5, 2)
    years = pd.date_range('1/1/2000',
                          periods=2, freq=pd.DateOffset(years=1)).year
    plt.figure()
    plt.boxplot(data, positions=years) 
Example 50
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 5 votes vote down vote up
def test_boxplot_sym2():
    # Randomness used for bootstrapping.
    np.random.seed(937)

    x = np.linspace(-7, 7, 140)
    x = np.hstack([-25, x, 25])
    fig, [ax1, ax2] = plt.subplots(1, 2)

    ax1.boxplot([x, x], bootstrap=10000, sym='^')
    ax1.set_ylim((-30, 30))

    ax2.boxplot([x, x], bootstrap=10000, sym='g')
    ax2.set_ylim((-30, 30))