本文整理汇总了Python中mpltools.style.use函数的典型用法代码示例。如果您正苦于以下问题:Python use函数的具体用法?Python use怎么用?Python use使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了use函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
)
示例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()
示例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')
示例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')
示例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()
示例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()
示例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)
示例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'
示例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
示例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
示例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:
示例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
示例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)
示例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',