Python matplotlib.ticker.StrMethodFormatter() Examples

The following are 11 code examples of matplotlib.ticker.StrMethodFormatter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.ticker , or try the search function .
Example #1
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def wrap_formatter(formatter):
    """
    Wraps formatting function or string in
    appropriate matplotlib formatter type.
    """
    if isinstance(formatter, ticker.Formatter):
        return formatter
    elif callable(formatter):
        args = [arg for arg in _getargspec(formatter).args
                if arg != 'self']
        wrapped = formatter
        if len(args) == 1:
            def wrapped(val, pos=None):
                return formatter(val)
        return ticker.FuncFormatter(wrapped)
    elif isinstance(formatter, basestring):
        if re.findall(r"\{(\w+)\}", formatter):
            return ticker.StrMethodFormatter(formatter)
        else:
            return ticker.FormatStrFormatter(formatter) 
Example #2
Source File: test_convertors.py    From mplexporter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_001_format_strings(self):
        conversions = [
            ("{x}", {'format_string': '', 'prefix': '', 'suffix': ''}),
            ("{x:#x}", {'format_string': '#x', 'prefix': '', 'suffix': ''}),
            ("{x:.2f}", {'format_string': '.2f', 'prefix': '', 'suffix': ''}),
            ("{x:.2%}", {'format_string': '.2%', 'prefix': '', 'suffix': ''}),
            ("P{x:.2%}", {'format_string': '.2%', 'prefix': 'P', 'suffix': ''}),
            ("P{x:.2%} 100", {'format_string': '.2%', 'prefix': 'P', 'suffix': ' 100'}),
        ]
        for mpl_fmt, d3_fmt in conversions: 
            formatter = ticker.StrMethodFormatter(mpl_fmt)
            cnvrt = StrMethodTickFormatterConvertor(formatter)
            self.assertEqual(cnvrt.output, d3_fmt) 
Example #3
Source File: test_ticker.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_formatstrformatter():
    # test % style formatter
    tmp_form = mticker.FormatStrFormatter('%05d')
    nose.tools.assert_equal('00002', tmp_form(2))

    # test str.format() style formatter
    tmp_form = mticker.StrMethodFormatter('{x:05d}')
    nose.tools.assert_equal('00002', tmp_form(2)) 
Example #4
Source File: test_ticker.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_basic(self, format, input, expected):
        fmt = mticker.StrMethodFormatter(format)
        assert fmt(*input) == expected 
Example #5
Source File: plotting.py    From RegRCNN with Apache License 2.0 5 votes vote down vote up
def plot_batchgen_distribution(cf, pids, p_probs, balance_target, out_file=None):
    """plot top n_pids probabilities for drawing a pid into a batch.
    :param cf: experiment config object
    :param pids: sorted iterable of patient ids
    :param p_probs: pid's drawing likelihood, order needs to match the one of pids.
    :param out_file:
    :return:
    """
    n_pids = len(pids)
    zip_sorted = np.array(sorted(list(zip(p_probs, pids)), reverse=True))
    names, probs = zip_sorted[:n_pids,1], zip_sorted[:n_pids,0].astype('float32') * 100
    try:
        names = [str(int(n)) for n in names]
    except ValueError:
        names = [str(n) for n in names]
    lowest_p = min(p_probs)*100
    fig, ax = plt.subplots(1,1,figsize=(17,5), dpi=200)
    rects = ax.bar(names, probs, color=cf.blue, alpha=0.9, edgecolor=cf.blue)
    ax = plt.gca()
    ax.text(0.8, 0.92, "Lowest prob.: {:.5f}%".format(lowest_p), transform=ax.transAxes, color=cf.white,
            bbox=dict(boxstyle='round', facecolor=cf.blue, edgecolor='none', alpha=0.9))
    ax.yaxis.set_major_formatter(StrMethodFormatter('{x:g}'))
    ax.set_xticklabels(names, rotation="vertical", fontsize=7)
    plt.margins(x=0.01)
    plt.subplots_adjust(bottom=0.15)
    if balance_target=="class_targets":
        balance_target = "Class"
    elif balance_target=="lesion_gleasons":
        balance_target = "GS"
    ax.set_title(str(balance_target)+"-Balanced Train Generator: Sampling Likelihood per PID")
    ax.set_axisbelow(True)
    ax.grid(axis='y')
    ax.set_ylabel("Sampling Likelihood (%)")
    ax.set_xlabel("PID")
    plt.tight_layout()

    if out_file is not None:
        plt.savefig(out_file)

    plt.close() 
Example #6
Source File: plotting.py    From RegRCNN with Apache License 2.0 5 votes vote down vote up
def plot_batchgen_stats(cf, stats, empties, target_name, unique_ts, out_file=None):
    """Plot bar chart showing RoI frequencies and empty-sample count of batch stats recorded by BatchGenerator.
    :param cf: config.
    :param stats: statistics as supplied by BatchGenerator class.
    :param out_file: path to save plot.
    """

    total_samples = cf.num_epochs*cf.num_train_batches*cf.batch_size
    if target_name=="class_targets":
        target_name = "Class"
        label_dict = {cl_id: label for (cl_id, label) in cf.class_id2label.items()}
    elif target_name=="lesion_gleasons":
        target_name = "Lesion's Gleason Score"
        label_dict = cf.gs2label
    elif target_name=="rg_bin_targets":
        target_name = "Regression-Bin ID"
        label_dict = cf.bin_id2label
    else:
        raise NotImplementedError
    names = [label_dict[t_id].name for t_id in unique_ts]
    colors = [label_dict[t_id].color for t_id in unique_ts]

    title = "Training Target Frequencies"
    title += "\nempty samples: {}".format(empties)
    rects = plt.bar(names, stats['roi_counts'], color=colors, alpha=0.9, edgecolor=colors)
    ax = plt.gca()

    ax.yaxis.set_major_formatter(StrMethodFormatter('{x:g}'))
    ax.set_title(title)
    ax.set_axisbelow(True)
    ax.grid()
    ax.set_ylabel(r"#RoIs")
    ax.set_xlabel(target_name)

    total_count = np.sum(stats["roi_counts"])
    labels = ["{:.0f}%".format(count/total_count*100) for count in stats["roi_counts"]]
    label_bar(ax, rects, labels, colors)

    if out_file is not None:
        plt.savefig(out_file)

    plt.close() 
Example #7
Source File: test_ticker.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_formatstrformatter():
    # test % style formatter
    tmp_form = mticker.FormatStrFormatter('%05d')
    nose.tools.assert_equal('00002', tmp_form(2))

    # test str.format() style formatter
    tmp_form = mticker.StrMethodFormatter('{x:05d}')
    nose.tools.assert_equal('00002', tmp_form(2)) 
Example #8
Source File: test_ticker.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_basic(self, format, input, expected):
        fmt = mticker.StrMethodFormatter(format)
        assert fmt(*input) == expected 
Example #9
Source File: test_ticker.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_basic(self, format, input, expected):
        fmt = mticker.StrMethodFormatter(format)
        assert fmt(*input) == expected 
Example #10
Source File: plotting.py    From RegRCNN with Apache License 2.0 4 votes vote down vote up
def plot_wbc_n_missing(cf, df, outfile, fs=11, ax=None):
    """ WBC (weighted box clustering) has parameter n_missing, which shows how many boxes are missing per cluster.
        This function plots the average relative amount of missing boxes sorted by cluster score.
    :param cf: config.
    :param df: dataframe.
    :param outfile: path to save image under.
    :param fs: fontsize.
    :param ax: axes object.
    """

    bins = np.linspace(0., 1., 10)
    names = ["{:.1f}".format((bins[i]+(bins[i+1]-bins[i])/2.)*100) for i in range(len(bins)-1)]
    classes = df.pred_class.unique()
    colors = [cf.class_id2label[cl_id].color for cl_id in classes]

    binned_df = df.copy()
    binned_df.loc[:,"pred_score"] = pd.cut(binned_df["pred_score"], bins)

    close=False
    if ax is None:
        ax = plt.subplot()
        close=True
    width = 1 / (len(classes) + 1)
    group_positions = np.arange(len(names))
    legend_handles = []

    for ix, cl_id in enumerate(classes):
        cl_df = binned_df[binned_df.pred_class==cl_id].groupby("pred_score").agg({"cluster_n_missing": 'mean'})
        ax.bar(group_positions + ix * width, cl_df.cluster_n_missing.values, width=width, color=colors[ix],
                       alpha=0.4 + ix / 2 / len(classes), edgecolor=colors[ix])
        legend_handles.append(mpatches.Patch(color=colors[ix], label=cf.class_dict[cl_id]))

    title = "Fold {} WBC Missing Preds\nAverage over scores and classes: {:.1f}%".format(cf.fold, df.cluster_n_missing.mean())
    ax.set_title(title, fontsize=fs)
    ax.legend(handles=legend_handles, title="Class", loc="best", fontsize=fs, title_fontsize=fs)
    ax.set_xticks(group_positions + (len(classes) - 1) * width / 2)
    # ax.xaxis.set_major_formatter(StrMethodFormatter('{x:.1f}')) THIS WONT WORK... no clue!
    ax.set_xticklabels(names)
    ax.tick_params(axis='both', which='major', labelsize=fs)
    ax.tick_params(axis='both', which='minor', labelsize=fs)

    ax.set_axisbelow(True)
    ax.grid()
    ax.set_ylabel(r"Average Missing Preds per Cluster (%)", fontsize=fs)
    ax.set_xlabel("Prediction Score", fontsize=fs)

    if close:
        if cf.server_env:
            IO_safe(plt.savefig, fname=outfile, _raise=False)
        else:
            plt.savefig(outfile)
        plt.close() 
Example #11
Source File: temp_graph.py    From Pigrow with GNU General Public License v3.0 4 votes vote down vote up
def render_danger_temps_graph(date_list, temp_list, graph_path, ymin, ymax, toocold, dangercold, toohot, dangerhot):
    print("Making EpiphanyHermit's damger temps by hour graph...")
    from matplotlib.lines import Line2D
    from matplotlib.patches import Polygon
    from matplotlib.ticker import StrMethodFormatter

    # Colors for the danger temps
    dangercoldColor = 'xkcd:purplish blue'
    toocoldColor = 'xkcd:light blue'
    toohotColor = 'xkcd:orange'
    dangerhotColor = 'xkcd:red'

    # Group the data by hour
    dangerhotArray = [0]*24
    toohotArray = [0]*24
    toocoldArray = [0]*24
    dangercoldArray = [0]*24
    for i in range(len(date_list)):
        h = int(date_list[i].strftime('%H'))
        if temp_list[i] >= dangerhot:
            dangerhotArray[h] += 1
        elif temp_list[i] >= toohot:
            toohotArray[h] += 1
        elif temp_list[i] <= dangercold:
            dangercoldArray[h] += 1
        elif temp_list[i] <= toocold:
            toocoldArray[h] += 1

    ind = np.arange(24)  # the x locations for the groups
    width = 0.25  # the width of the bars

    fig, ax = plt.subplots()
    rects1 = ax.bar(ind - width/2, dangercoldArray, width, yerr=None, color=dangercoldColor, label='DC')
    rects2 = ax.bar(ind - width/4, toocoldArray, width, yerr=None, color=toocoldColor, label='TC')
    rects3 = ax.bar(ind + width/4, toohotArray, width, yerr=None, color=toohotColor, label='TH')
    rects4 = ax.bar(ind + width/2, dangerhotArray, width, yerr=None, color=dangerhotColor, label='DH')

    # Add some text for labels, title and custom x-axis tick labels, etc.
    fig.suptitle('Dangerous Temperature by Hour', fontsize=14, fontweight='bold')
    ax.set_ylabel('Counts')
    ax.set_title(min(date_list).strftime("%B %d, %Y") + ' - ' + max(date_list).strftime("%B %d, %Y"), fontsize=10)
    ax.set_xticks(ind)
    labels = ('00:00', '01:00', '02:00', '03:00', '04:00','05:00','06:00','07:00','08:00','09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00')
    ax.set_xticklabels(labels,rotation=45)
    ax.legend()
    print("danger temps created and saved to " + graph_path)
    plt.savefig(graph_path)
    fig.clf()