当前位置: 首页>>代码示例>>Python>>正文


Python ticker.StrMethodFormatter方法代码示例

本文整理汇总了Python中matplotlib.ticker.StrMethodFormatter方法的典型用法代码示例。如果您正苦于以下问题:Python ticker.StrMethodFormatter方法的具体用法?Python ticker.StrMethodFormatter怎么用?Python ticker.StrMethodFormatter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.ticker的用法示例。


在下文中一共展示了ticker.StrMethodFormatter方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: wrap_formatter

# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import StrMethodFormatter [as 别名]
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) 
开发者ID:holoviz,项目名称:holoviews,代码行数:22,代码来源:util.py

示例2: test_001_format_strings

# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import StrMethodFormatter [as 别名]
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) 
开发者ID:mpld3,项目名称:mplexporter,代码行数:15,代码来源:test_convertors.py

示例3: test_formatstrformatter

# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import StrMethodFormatter [as 别名]
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)) 
开发者ID:miloharper,项目名称:neural-network-animation,代码行数:10,代码来源:test_ticker.py

示例4: test_basic

# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import StrMethodFormatter [as 别名]
def test_basic(self, format, input, expected):
        fmt = mticker.StrMethodFormatter(format)
        assert fmt(*input) == expected 
开发者ID:holzschu,项目名称:python3_ios,代码行数:5,代码来源:test_ticker.py

示例5: plot_batchgen_distribution

# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import StrMethodFormatter [as 别名]
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() 
开发者ID:MIC-DKFZ,项目名称:RegRCNN,代码行数:42,代码来源:plotting.py

示例6: plot_wbc_n_missing

# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import StrMethodFormatter [as 别名]
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() 
开发者ID:MIC-DKFZ,项目名称:RegRCNN,代码行数:54,代码来源:plotting.py

示例7: plot_batchgen_stats

# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import StrMethodFormatter [as 别名]
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() 
开发者ID:MIC-DKFZ,项目名称:RegRCNN,代码行数:44,代码来源:plotting.py

示例8: render_danger_temps_graph

# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import StrMethodFormatter [as 别名]
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() 
开发者ID:Pragmatismo,项目名称:Pigrow,代码行数:50,代码来源:temp_graph.py


注:本文中的matplotlib.ticker.StrMethodFormatter方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。