• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python style.use函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mpltools.style.use函数的典型用法代码示例。如果您正苦于以下问题:Python use函数的具体用法?Python use怎么用?Python use使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: plot_perf

def plot_perf(df, engines, title, filename=None):
    from matplotlib.pyplot import figure, rc

    try:
        from mpltools import style
    except ImportError:
        pass
    else:
        style.use('ggplot')

    rc('text', usetex=True)

    fig = figure(figsize=(4, 3), dpi=100)
    ax = fig.add_subplot(111)

    for engine in engines:
        ax.plot(df.size, df[engine], label=engine, lw=2)

    ax.set_xlabel('Number of Rows')
    ax.set_ylabel('Time (s)')
    ax.set_title(title)
    ax.legend(loc='best')
    ax.tick_params(top=False, right=False)

    fig.tight_layout()

    if filename is not None:
        fig.savefig(filename)
开发者ID:xguse,项目名称:pandas,代码行数:28,代码来源:bench_with_subset.py


示例2: plot

    def plot(self):
        dfn = joinpath(DATA_DIR, ('%s.pypkl' % self.id))
        with open(dfn, 'rb') as f:
            mean_lists = pickle.load(f)
            std_lists = pickle.load(f)
            gmean_lists = pickle.load(f)
            hmean_lists = pickle.load(f)

        if use_mpl_style:
            style.use('ggplot')

        x_lists = numpy.array(self.asic_area_list) * 0.01
        legend_labels=['-'.join(['%d'%a for a in alloc_config]) for alloc_config in self.alloc_configs]
        def cb_func(axes,fig):
            matplotlib.rc('xtick', labelsize=8)
            matplotlib.rc('ytick', labelsize=8)
            matplotlib.rc('legend', fontsize=8)
            axes.legend(axes.lines, legend_labels, loc='upper right',
                    title='Acc3, 4, 5, 6 alloc', bbox_to_anchor=(0.85,0.55,0.2,0.45))

        plot_data(x_lists, mean_lists,
                xlabel='Total ASIC allocation',
                ylabel='Speedup (mean)',
                xlim=(0, 0.5),
                #ylim=(127, 160),
                figsize=(4, 3),
                ms_list=(8,),
                #xlim=(0, 0.11),
                cb_func=cb_func,
                figdir=FIG_DIR,
                ofn='%s-%s.%s' % (self.id,
                    '-'.join([s[-1:] for s in self.kids]), self.fmt)
                )
开发者ID:liangwang,项目名称:lumos,代码行数:33,代码来源:main.py


示例3: show_gauge

def show_gauge(gauge):
    import matplotlib.pyplot as plt
    from mpltools import style
    style.use('ggplot')
    plotter = GaugePlotting(gauge)
    plotter.plot(plt)
    plt.show()
开发者ID:mnpk,项目名称:gauge,代码行数:7,代码来源:gaugeplot.py


示例4: do_plot

def do_plot(numpy_stats, mpl_stats, mahotas_stats, skimage_stats, sklearn_stats):
    from mpltools import style
    from matplotlib import pyplot as plt
    import datetime
    style.use('ggplot')

    def do_plot(s, name):
        import numpy as np
        plt.fill_between(np.concatenate(([min_date], s.datetimes)), np.concatenate(([0], s.lines/1000.)))
        plt.plot(np.concatenate(([min_date], s.datetimes)), np.concatenate(([0], s.lines/1000.)) , color="k", lw=2)
        plt.text(tx, s.lines.max()/1000.*.7, name)

    tx = datetime.datetime(2002,2,1)
    min_date = numpy_stats.datetimes[0]
    plt.subplot(5,1,1)
    do_plot(numpy_stats, 'numpy')
    plt.subplot(5,1,2)
    do_plot(mpl_stats, 'matplotlib')
    plt.subplot(5,1,3)
    do_plot(mahotas_stats, 'mahotas')
    plt.subplot(5,1,4)
    do_plot(skimage_stats, 'skimage')
    plt.subplot(5,1,5)
    do_plot(sklearn_stats, 'sklearn')
    plt.tight_layout()
    plt.savefig('nr_lines.png')
开发者ID:luispedro,项目名称:luispedro_org,代码行数:26,代码来源:jugfile.py


示例5: plot_logs

def plot_logs(*logs_with_labels):
    from pylab import figure
    from matplotlib import rc
    rc('ps', useafm=True)
    rc('pdf', use14corefonts=True)
    rc('text', usetex=True)
    rc('font', family='sans-serif')
    rc('font', **{'sans-serif': ['Computer Modern']})

    try:
        from mpltools import style
        style.use('ggplot')
        rc('axes', grid=False)
    except ImportError:
        print >> sys.stderr, 'mpltools not installed, using standard (boring) style'

    fig = figure()
    curves = [(read_log(filename), label)
                      for filename, label in (ll.strip().split(':')
                                              for ll in logs_with_labels)]

    plot_convergence(fig.gca(), curves)
    fig.set_size_inches(6, 4)
    fig.savefig('convergence.pdf', bbox_inches='tight')

    fig = figure()
    plot_convergence_envelope(fig.gca(), curves)
    fig.set_size_inches(6, 4)
    fig.savefig('convergence_envelope.pdf', bbox_inches='tight')
开发者ID:BerengereG,项目名称:contrib,代码行数:29,代码来源:plot_learning.py


示例6: plot_res

def plot_res(res, png_path, covs, covariate, cluster_df, weights_df=None):
    from matplotlib import pyplot as plt
    from mpltools import style
    style.use('ggplot')

    region = "{chrom}_{start}_{end}".format(**res)
    if png_path.endswith('show'):
        png = None
    elif png_path.endswith(('.png', '.pdf')):
        png = "%s.%s%s" % (png_path[:-4], region, png_path[-4:])
    elif png_path:
        png = "%s.%s.png" % (png_path.rstrip("."), region)

    if is_numeric(getattr(covs, covariate)):
        f = plot_continuous(covs, cluster_df, covariate, res['chrom'], res, png)
    else:
        f = plt.figure(figsize=(11, 4))
        ax = f.add_subplot(1, 1, 1)
        if 'spaghetti' in png_path and cluster_df.shape[0] > 1:
            plot_dmr(covs, cluster_df, covariate, res['chrom'], res, png,
                    weights_df)
        else:
            plot_hbar(covs, cluster_df, covariate, res['chrom'], res, png)
        plt.title('p-value: %.3g %s: %.3f' % (res['p'], covariate, res['coef']))
    f.set_tight_layout(True)
    if png:
        plt.savefig(png)
    else:
        plt.show()
    plt.close()
开发者ID:brentp,项目名称:clustermodel,代码行数:30,代码来源:__main__.py


示例7: precision_recall

def precision_recall():
#   from sklearn.metrics import roc_auc_score
#   from sklearn.metrics import roc_curve
  from sklearn.metrics import precision_recall_curve
  from sklearn.metrics import auc
  from sklearn.metrics import classification_report
  from mpltools import style
  style.use('ggplot')

  makes = ['bmw', 'ford']
  types = ['sedan', 'SUV']
  args = makes + types
  config = get_config(args)
  (dataset, config) = fgu.get_all_metadata(config)


  for ii, attrib_name in enumerate(args):
  #   attrib_name = 'bmw'

    attrib_clf = AttributeClassifier.load('../../../attribute_classifiers/{}.dat'.format(attrib_name))
    bnet = BayesNet(config, dataset['train_annos'],
                    dataset['class_meta'], [attrib_clf], desc=str(args))

    res = bnet.create_attrib_res_on_images()

    attrib_selector = AttributeSelector(config, dataset['class_meta'])
  #   attrib_meta = attrib_selector.create_attrib_meta([attrib_clf.name])
    pos_classes = attrib_selector.class_ids_for_attribute(attrib_name)
    true_labels = np.array(res.class_index.isin(pos_classes))


    print "--------------{}-------------".format(attrib_name)
    print res[str.lower(attrib_name)].describe()

    print classification_report(true_labels, np.array(res[str.lower(attrib_name)]) > 0.65,
                                target_names=['not-{}'.format(attrib_name),
                                              attrib_name])



    precision, recall, thresholds = precision_recall_curve(true_labels, np.array(res[str.lower(attrib_name)]))
    score = auc(recall, precision)
    print("Area Under Curve: %0.2f" % score)
#     score = roc_auc_score(true_labels, np.array(res[str.lower(attrib_name)]))
#     fpr, tpr, thresholds = roc_curve(true_labels, np.array(res[str.lower(attrib_name)]))
    plt.subplot(2,2,ii+1)
#     plt.plot(fpr, tpr)
    plt.plot(recall, precision, label='Precision-Recall curve')
    plt.title('Precision-Recall: {}'.format(attrib_name))
#     plt.xlabel('False Positive Rate')
#     plt.ylabel('True Positive Rate')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.legend(['area = {}'.format(score)])

  plt.draw()
  plt.show()
开发者ID:yairmov,项目名称:carUnderstanding,代码行数:57,代码来源:experiments.py


示例8: main

def main(argv):
    style.use('ggplot')
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-i', '--infile', type=argparse.FileType('r'),
                        default=sys.stdin)
    parser.add_argument('-o', '--outfile', type=str, required=True)
    parser.add_argument('--stats-file', type=argparse.FileType('w'))
    parser.add_argument('--threeprime-trimmed', type=str)
    parser.add_argument('--three-prime-nucs', type=int, default=1)
    parser.add_argument('--convert-single-g', action='store_true')
    args = parser.parse_args(argv)
    df = pd.read_table(args.infile, index_col=None)
    if args.convert_single_g:
        df = df.apply(convert_single_g, axis=1)
    df = df[df['OFFSET_FROM_START'] == 0]
    if args.threeprime_trimmed is not None:
        if args.threeprime_trimmed == '':
            df = df[df['3PTRIMMED'].isnull()]
        else:
            df = df[df['3PTRIMMED'] == args.threeprime_trimmed]
    df = calculate_num_times_map(df)
    df = df.apply(lambda x: pd.Series(
        [x['ORIGINAL_SEQUENCE'][-1].upper() + \
        x['THREEPRIME_OF_CLEAVAGE'][0:args.three_prime_nucs].upper(),
        float(x['COUNT']) / float(x['NUM_TIMES_MAP'])]), axis=1)
    s = df.groupby(0).sum().sort(columns=1, ascending=False)
    s.plot(kind='bar')
    ax = plt.gca()
    ax.legend().set_visible(False)
    plt.savefig(args.outfile, format='eps')
    s = s.reset_index()
    total = s[1].sum()
    gs_pos_one = s[s[0].map(lambda x: x[1] == 'G')][1].sum()
    as_pos_zero = s[s[0].map(lambda x: x[0] == 'A')][1].sum()
    gs_exclusive = s[s[0].map(lambda x: x[1] == 'G' and x[0] != 'A')][1].sum()
    as_exclusive = s[s[0].map(lambda x: x[0] == 'G' and x[1] != 'G')][1].sum()
    gs_or_as_pos_zero = s[s[0].map(lambda x: x[0] == 'A' or x[0] == 'G')][1].sum()
    gs_both_exclusive = s[s[0].map(lambda x: 'G' in x and x[0] != 'A')][1].sum()
    gs_or_as_pos_zero_exclusive = s[s[0].map(lambda x: (x[0] == 'A' or x[0] == 'G') and x[1] != 'G')][1].sum()
    gs_pos_zero = s[s[0].map(lambda x: x[0] == 'G')][1].sum()
    if args.stats_file:
        for frac, string in [
                (gs_pos_one / total, 'Fraction Gs at position 1: %f\n'),
                (as_pos_zero / total, 'Fraction As at position 0: %f\n'),
                (gs_exclusive / total, 'Fraction Gs at position 1 with no As: %f\n'),
                (as_exclusive / total, 'Fraction As at position 0 with no Gs: %f\n'),
                (gs_or_as_pos_zero / total, 'Fraction As or Gs at pos 0: %f\n'),
                (gs_pos_zero / total, 'Fraction Gs at position 0: %f\n'),
                ((as_exclusive / (gs_both_exclusive + as_exclusive)), 'Fraction A over total: %f\n'),
                (total, 'Total: %f\n')
        ]:
            args.stats_file.write(string % frac)
开发者ID:dkoppstein,项目名称:prime-and-realign,代码行数:52,代码来源:find_dinucleotide_at_junction.py


示例9: basic_sin

def basic_sin():
    from mpltools import style
    style.use('ggplot')
    t = np.arange(0.0, 2.0, 0.1)
    s = np.sin(2*np.pi*t)
    s2 = np.cos(2*np.pi*t)
    pp.plot(t, s, 'o-', lw=4.1)
    pp.plot(t, s2, 'o-', lw=4.1)
    pp.xlabel('time(s)')
    #pp.xlabel('time(s) _ % $ \\')
    pp.ylabel('Voltage (mV)')
    pp.title('Easier than easy $\\frac{1}{2}$')
    pp.grid(True)
    return 'Simple $\sin$ plot with some labels'
开发者ID:Caasar,项目名称:matplotlib2tikz,代码行数:14,代码来源:testfunctions.py


示例10: config_plots

def config_plots():

    # matplotlib has some annoying warnings we will ignore
    import warnings
    warnings.filterwarnings('ignore', module='matplotlib')
    warnings.filterwarnings('ignore', module='mpltools')

    from mpltools import style
    style.use('ggplot')

    import matplotlib as mpl
    mpl.rcParams['figure.figsize'] = (10.0, 6.0)
    mpl.rcParams['figure.dpi'] = 300.0
    mpl.rcParams['xtick.labelsize'] = 12.0
    mpl.rcParams['ytick.labelsize'] = 12.0
    mpl.rcParams['axes.labelsize'] = 16.0
    mpl.rcParams['axes.titlesize'] = 18.0
    mpl.rcParams['legend.fontsize'] = 16.0
开发者ID:VirtualWatershed,项目名称:capstone,代码行数:18,代码来源:capstone.py


示例11: plot_graph

def plot_graph(G, titl='', nodesize=300, widthsize=1.5, plotfname='/tmp/tmp.png'):
    import matplotlib as mpl
    mpl.use('Agg', warn=False)
    import matplotlib.pyplot as plt
    from mpltools import style, layout
    style.use('ggplot')

    cm = plt.get_cmap('cool')
    cm.set_under('w')

    f = plt.figure(1)
    ax = f.add_subplot(1,1,1)

    obs = open('obs.txt', 'r').read().split('\n')
    obs = [o.decode('utf-8')[:-1] for o in obs if len(o) > 0]
    txtstr = ''
    # for k, v in enumerate(obs[::-1]):
    #     txtstr += '%d: {%s}' % (len(obs) - k - 1, v) + '\n'


    # titl = '%d nodes, %d edges' % (G.number_of_nodes(), G.number_of_edges())
    f.text(0.02, 0.98, txtstr, transform=ax.transAxes, verticalalignment='top')
    plt.title(titl)

    pos = nx.get_node_attributes(G,'xy')

    nodes = nx.draw_networkx_nodes(G, pos, cmap = cm, node_color='c', labels=None, with_labels=False, ax=ax, node_size=nodesize)
    edges = nx.draw_networkx_edges(G, pos, width=widthsize, ax=ax)

    pos_short = {}
    # for i in range(0, len(obs)):
    #     pos_short[i] = '%d' % i
    for k, v in enumerate(obs):
        pos_short[k] = '{%s}' % v
    labels = nx.draw_networkx_labels(G, pos, labels=pos_short, font_size=8)

    plt.axis('off')
    f.set_facecolor('w')

    plt.savefig(plotfname, dpi=300, bbox_inches='tight')
    plt.clf()
    return 0
开发者ID:lisjin,项目名称:fca-viz,代码行数:42,代码来源:vizgraph.py


示例12: jjinking

Creation date   : 2014.02.13
Last Modified   : 2015.01.30
Modified By     : Jin Kim jjinking(at)gmail(dot)com
'''

import csv
import cPickle
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import Queue
import sys
from collections import defaultdict
from contextlib import closing
from datetime import datetime
from mpltools import style; style.use('ggplot')
from sklearn import cross_validation
from sklearn.ensemble import RandomForestClassifier

import dataio

def df_equal(df1, df2, decimals=None):
    '''
    Compare the values of two pandas DataFrame objects element by element,
    and if every single element is equal, return True

    Parameter decimals determines the number of decimal places to round decimal
    values before comparing
    '''
    # First, compare the sizes
    if df1.shape != df2.shape:
开发者ID:ddofer,项目名称:Kaggle-HUJI-ML,代码行数:31,代码来源:eda-ExploratoryDataAnalysis.py


示例13: file

perf stat -I1000 -x, -o file ...
toplev -I1000 -x, -o file ... 
interval-plot.py file (or stdin)
delimeter must be ,
this is for data that is not normalized.''')
p.add_argument('--xkcd', action='store_true', help='enable xkcd mode')
p.add_argument('--style', help='set mpltools style (e.g. ggplot)')
p.add_argument('file', help='CSV file to plot (or stdin)', nargs='?')
p.add_argument('--output', '-o', help='Output to file. Otherwise show.', 
               nargs='?')
args = p.parse_args()

if args.style:
    try:
        from mpltools import style
        style.use(args.style)
    except ImportError:
        print "Need mpltools for setting styles (pip install mpltools)"

import gen_level

try:
    import brewer2mpl
    all_colors = brewer2mpl.get_map('Paired', 'Qualitative', 12).hex_colors
except ImportError:
    print "Install brewer2mpl for better colors (pip install brewer2mpl)"
    all_colors = ('green','orange','red','blue',
    	      'black','olive','purple','#6960EC', '#F0FFFF',
              '#728C00', '#827B60', '#F87217', '#E55451', # 16
              '#F88017', '#C11B17', '#17BFC2', '#C48793') # 20
开发者ID:Naoya-Horiguchi,项目名称:pmu-tools,代码行数:30,代码来源:interval-plot.py


示例14: leg_width

color3 = '#9acd32'
color2 = '#ff0000'

lw1=4
aph=.7

# set the linewidth of each legend object
def leg_width(lg,fs):
    for legobj in lg.legendHandles:
        legobj.set_linewidth(fs)

#
# plotting
#

style.use('dark_background')



# isotherms tilted

fig = plt.figure(figsize=(17,9.))
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')


ax.plot(mu2,mu2,linewidth=lw1,alpha=aph,color=color2)
ax.plot(mu2,cmu2,linewidth=lw1,alpha=aph,color=color1)
ax.plot(mu2,tmu2,linewidth=lw1,alpha=aph,color=color3)
开发者ID:crocha700,项目名称:classes,代码行数:30,代码来源:dis_relation.py


示例15:

import sys
import os
import cPickle as pickle
from pandas import DataFrame, Series
import pandas as pd
import matplotlib.pyplot as plt
from mpltools import style
from mpltools import layout
style.use(['ggplot', 'pof'])
almost_black = '#262626'
from database import Database


cwd = os.path.dirname(os.path.abspath(__file__))
datadir = os.path.join(os.path.split(cwd)[0], 'data')
resultsdir = os.path.join(os.path.split(cwd)[0], 'results')

marketing = {'passive_marketing': ['environmental_impact', 'investment', 'govt_incentives', 'pv_education', 'rate_changes', 'industry_growth'],
			 'active_marketing': ['online_review', 'past_work', 'event_marketing', 'channel_partnering', 'webtools', 'promotions', 'contact', 'bragging']}


pie_colors = { 'environmental_impact': '#7C8FB0', 
			'investment': '#EEAD51', 
			'govt_incentives': '#8CC43D', 
			'pv_education': '#2B292A', 
			'rate_changes': '#FED700',
			'industry_growth': '#426986',
			'online_review': '#8B8878', 
			'past_work': '#426986', 
			'event_marketing': '#87CEFA', 
			'channel_partnering': '#EEAD51', 
开发者ID:matt-stringer,项目名称:twitter-marketing-analysis,代码行数:31,代码来源:counts.py


示例16: print

# It is made available under the MIT License

from __future__ import print_function

try:
    from gensim import corpora, models, similarities
except:
    print("import gensim failed.")
    print()
    print("Please install it")
    raise

try:
    from mpltools import style

    style.use("ggplot")
except:
    print("Could not import mpltools: plots will not be styled correctly")

import matplotlib.pyplot as plt
import numpy as np
from os import path

if not path.exists("./data/ap/ap.dat"):
    print("Error: Expected data to be present at data/ap/")
    print("Please cd into ./data & run ./download_ap.sh")

corpus = corpora.BleiCorpus("./data/ap/ap.dat", "./data/ap/vocab.txt")
model = models.ldamodel.LdaModel(corpus, num_topics=100, id2word=corpus.id2word, alpha=None)

for ti in xrange(84):
开发者ID:NguyenNhatNam,项目名称:BuildingMachineLearningSystemsWithPython,代码行数:31,代码来源:blei_lda.py


示例17:

from mpltools import style
style.use('jfm')

import matplotlib as mpl

mpl.rcParams['figure.figsize'] = [5.0,3.3]
mpl.rcParams['figure.dpi'] = 300
mpl.rcParams['savefig.dpi'] = 300
#mpl.rcParams['savefig.bbox'] = 'tight'
#mpl.rcParams['savefig.pad_inches'] = 0.05
mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['font.serif'] = ['Computer Modern Roman']
mpl.rcParams['text.usetex'] = True
开发者ID:RupertDodkins,项目名称:ARCONS-pipeline-1,代码行数:13,代码来源:figureHeader.py


示例18: plot

def plot(file,  pstyle = 'ggplot', output=None, seq=None, xkcd=False):

    # op_sum = {'1':['L1-dcache-loads','L1-dcache-stores','L1-dcache-prefetches','L1-icache-loads'],
    #           '2':['L1-dcache-load-misses','L1-dcache-store-misses','L1-dcache-prefetch-misses','L1-icache-load-misses'],
    #           '3':[ 'LLC-loads','LLC-stores','LLC-prefetches'],
    #           '4':['LLC-load-misses','LLC-store-misses','LLC-prefetch-misses'],
    #           '5':['dTLB-loads','dTLB-stores','iTLB-loads'],
    #           '6':['dTLB-load-misses','dTLB-store-misses','iTLB-load-misses'],
    #           'Bandwidth':['offcore_response_corewb_local_dram_0','offcore_response_prefetch_any_llc_miss_0','LLC-prefetches','cache-misses']}
   # op_div = [['cache-references','uops_retired_any'],['cache-misses','uops_retired_any'], ['instructions','cycles'],
   #           ['cache-misses','cache-references']]


    #enable for i7

    op_sum = {
        'contention': ['cache-misses'],
        'band': ['cache-references', 'cache-misses'],
        'total_bandwidth': ['cache-references']
    }

    op_div= [['instructions','cycles'],['cache-misses','cache-references'],['cache-references','cycles'], ['cache-misses','cycles']]


    print  pstyle
    if  pstyle:
        try:
            from mpltools import style
            style.use( pstyle)
        except ImportError:
            print "Need mpltools for setting  styles (pip install mpltools)"

    import gen_level

    try:
        import brewer2mpl
        all_colors = brewer2mpl.get_map('Paired', 'Qualitative', 12).hex_colors
    except ImportError:
        print "Install brewer2mpl for better colors (pip install brewer2mpl)"
        all_colors = ('green','orange','red','blue',
                  'black','olive','purple','#6960EC', '#F0FFFF',
                  '#728C00', '#827B60', '#F87217', '#E55451', # 16
                  '#F88017', '#C11B17', '#17BFC2', '#C48793') # 20

    cur_colors = collections.defaultdict(lambda: all_colors)
    assigned = dict()

    if  file:
        try:
            inf = open( file, "r")
        except:
            return
    else:
        inf = sys.stdin

    rc = csv.reader(inf)
    timestamps = dict()
    value = dict()

    val = ""
    for r in rc:
        if burst:
            if len(r) == 2:
                ts=0
                val, event = r
            else:
                continue

        if not burst:
            # timestamp,event,value
            if len(r) < 3:
                continue
            print r
            if len(r) >= 5:
                ts, event, val, thresh, desc = r
            elif len(r) >= 4:
                ts, val, unit, event = r
            else:
                ts, val, event = r


        if event not in assigned:
            level = gen_level.get_level(event)
            assigned[event] = cur_colors[level][0]
            cur_colors[level] = cur_colors[level][1:]
            if len(cur_colors[level]) == 0:
                cur_colors[level] = all_colors
            value[event] = []
            timestamps[event] = []
        timestamps[event].append(float(ts))
        try:
            value[event].append(float(val.replace("%","")))
        except ValueError:
            value[event].append(0.0)

    levels = dict()
    for j in assigned.keys():
        levels[gen_level.get_level(j)] = True

    if xkcd:
#.........这里部分代码省略.........
开发者ID:navaneethrameshan,项目名称:PMU-burst,代码行数:101,代码来源:intervalplot.py


示例19: processPlot

    def processPlot(self):
        self.preparePlot()
        if os.path.isfile(os.path.join(self.home, 'data_sets.csv')):
            with open(os.path.join(self.home, 'data_sets.csv')) as file_handle:
                csv_file = csv.reader(file_handle)
                row_cnt = 0
                for row_string in csv_file:
                    if row_cnt == 0:
                        pass
                    else:
                        self.plot_set[row_string[0]] = [row_string[1], row_string[2], row_string[3]]
                    row_cnt += 1


            sorted_set = self.plot_set.keys()
            sorted_set.sort()
            seq_cnt = 1

            for seq in sorted_set:
                print 'Processing - %s of %s' % (seq_cnt, len(sorted_set))
                seq_cnt += 1
                plot_text = self.plot_set[seq][2]

                for p in range(len(self.plots)):
                    print 'Processing set - %s of %s' % (p + 1, len(self.plots))
                    style.use('mpl_dark_harlan')
                    fig = plt.figure(p + 1)
                    ax = fig.add_subplot(111)
                    ax2 = ax.twinx()
                    ax_array = self.array_builder()
                    self.prepare_plot(self.plots[p])
                    self.grapher(ax_array, ax, ax2)

                    ax.set_xlim(left=mdates.strpdate2num(self.date_axis)(self.plot_set[seq][0]),
                                right=mdates.strpdate2num(self.date_axis)(self.plot_set[seq][1]))

                    plt.title('%s - %s' % (seq, (self.plots[p].split('_')[1].replace('-', ' ').replace('.csv', ''))))
                    ax.set_ylabel(self.y_label)

                    if len(self.sec_array_keys) == 1:
                        ax2.set_ylabel(self.sec_array_keys[0])
                    else:
                        ax2.set_ylabel(self.y2_label)

                    ax.set_xlabel(self.x_label)
                    ax.set_xticklabels(ax_array.keys()[0], rotation=45, fontsize=8)
                    ax.xaxis.set_major_formatter(mdates.DateFormatter(self.date_legend))
                    fig.autofmt_xdate()

                    plt.grid(True)
                    ax.legend(loc=2, borderaxespad=1., fontsize=10)
                    ax2.legend(loc=1, borderaxespad=1., fontsize=10)

                    # fig.text(.1, .1, plot_text, horizontalalignment='center')

                    self.prim_array_keys = []
                    self.sec_array_keys = []

                    fig.subplots_adjust(left=0.06, bottom=0.12, right=0.94, top=0.94, wspace=None, hspace=None)
                    fig.set_size_inches(22, 16, forward=True)

                    if self.graph_type.lower() == "pdf":
                        self.savePdf()

                    else:
                        plt.show()

                    plt.close()


        print 'Processing complete'
开发者ID:harlanaubuchon,项目名称:py,代码行数:71,代码来源:reprizent.py


示例20: style

"""
===============
Multiple styles
===============

You can specify multiple plot styles by passing a list of style names to
`style.use`. The styles are evaluated from the first to last element of the
list, so if there are settings that are defined in multiple styles, the
settings in the later style files will override those in the earlier files.

In this example, the 'ggplot' style alters the colors of elements to make the plot pretty, and the 'pof' style (Physics of Fluids journal) alters the figure size so that it fits in a column, alters line and text sizes, etc.
"""

import numpy as np
import matplotlib.pyplot as plt

from mpltools import style

style.use(["ggplot", "pof"])

x = np.linspace(0, 2 * np.pi)
plt.plot(x, np.cos(x))
plt.xlabel("x label")
plt.ylabel("y label")
plt.title("title")

plt.show()
开发者ID:tonysyu,项目名称:mpltools,代码行数:27,代码来源:plot_multiple_styles.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mplwidget.MplWidget类代码示例发布时间:2022-05-27
下一篇:
Python mpldatacursor.datacursor函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap