本文整理匯總了Python中matplotlib.backends.backend_pdf.PdfPages方法的典型用法代碼示例。如果您正苦於以下問題:Python backend_pdf.PdfPages方法的具體用法?Python backend_pdf.PdfPages怎麽用?Python backend_pdf.PdfPages使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib.backends.backend_pdf
的用法示例。
在下文中一共展示了backend_pdf.PdfPages方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: missing_rate_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def missing_rate_plot(consensus_data, ordered_genomes, biotypes, missing_plot_tgt):
"""Missing genes/transcripts"""
base_title = 'Number of missing orthologs in consensus set'
gene_missing_df = json_biotype_counter_to_df(consensus_data, 'Gene Missing')
gene_missing_df.columns = ['biotype', 'Genes', 'genome']
transcript_missing_df = json_biotype_counter_to_df(consensus_data, 'Transcript Missing')
transcript_missing_df.columns = ['biotype', 'Transcripts', 'genome']
df = transcript_missing_df.merge(gene_missing_df, on=['genome', 'biotype'])
df = pd.melt(df, id_vars=['biotype', 'genome'])
ylabel = 'Number of genes or transcripts'
af = luigi.local_target.atomic_file(missing_plot_tgt.path)
with PdfPages(af.tmp_path) as pdf:
tot_df = df.groupby(['genome', 'biotype', 'variable']).aggregate(sum).reset_index()
generic_barplot(tot_df, pdf, '', ylabel, base_title, x='genome', y='value',
col='variable', row_order=ordered_genomes)
for biotype in biotypes:
biotype_df = biotype_filter(df, biotype)
if biotype_df is None:
continue
biotype_df = biotype_df.groupby(['genome', 'variable']).aggregate(sum).reset_index()
title = base_title + ' for biotype {}'.format(biotype)
generic_barplot(biotype_df, pdf, '', ylabel, title, x='genome', y='value',
col='variable', row_order=ordered_genomes)
af.move_to_final_destination()
示例2: plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def plot(contraction, which_layer, per, lear, tags=LAB):
result = sort(contraction, which_layer, per, lear, tags=LAB)
fig = plt.figure()
ax1 = fig.add_subplot(111)
x = result[:, 0]
y = result[:, 1]
ax1.scatter(x[0:n_train_each], y[0:n_train_each], s=11,
c='b', marker="o", label='Planes', alpha=0.5)
ax1.scatter(x[n_train_each + 1:n_train], y[n_train_each + 1:n_train],
s=11, c='r', marker="o", label='Horses', alpha=0.5)
plt.legend(loc='upper right')
plt.axis('off')
# plt.show()
pp = PdfPages('%s_P%s_L%s.pdf' % (which_layer, per, lear))
pp.savefig(fig)
pp.close()
return fig
#%%
示例3: test_composite_image
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def test_composite_image():
# Test that figures can be saved with and without combining multiple images
# (on a single set of axes) into a single composite image.
X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))
Z = np.sin(Y ** 2)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim(0, 3)
ax.imshow(Z, extent=[0, 1, 0, 1])
ax.imshow(Z[::-1], extent=[2, 3, 0, 1])
plt.rcParams['image.composite_image'] = True
with PdfPages(io.BytesIO()) as pdf:
fig.savefig(pdf, format="pdf")
assert len(pdf._file._images) == 1
plt.rcParams['image.composite_image'] = False
with PdfPages(io.BytesIO()) as pdf:
fig.savefig(pdf, format="pdf")
assert len(pdf._file._images) == 2
示例4: get_next_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def get_next_plot(self):
if self.pdf is None:
plt.rc('pdf', fonttype=42)
self.pdf = PdfPages(self.pdfpath)
newfig = False
if self.pidx == 0 or self.pidx == self.rows * self.cols:
# Start a new pdf page
if self.fig is not None:
if self.save_tight: plt.tight_layout()
self.pdf.savefig(self.fig, bbox_inches=self.bbox_inches)
self.fig = None
newfig = True
self.pidx = 0
self.pidx += 1
if newfig: self.fig = plt.figure()
self.plotcount += 1
return self.fig.add_subplot(self.rows, self.cols, self.pidx)
示例5: save_fig
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def save_fig(fig, name, dpi=400):
pp = PdfPages(name)
pp.savefig(fig, bbox_inches='tight', pad_inches=0, dpi=dpi)
pp.close()
################################################### dataSeries (2-dimensional np.ndarray), figSize (tuple, length=2) -> fig
# dataSeries (list of np.ndarray), figSize (tuple, length=2) -> fig
# stackNum starts from 0, which means no stack but just a bar.
# each row of dataSeries is one data type.
# number of stackNum indicates the dats to be stacked.
# e.g., if length of dataSeries is 7, and stack Num is 2,
# dataSeries[0] and dataSereis[1] should be stacked on same bar
# dataSeries[1] and dataSereis[2] should be stacked on same bar
# dataSeries[3] and dataSereis[4] should be stacked on same bar
# Other details should be implemented in inheritor
示例6: volcano_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def volcano_plot(self, label, pdf, colors="YlGnBu_r", log_bins=True):
"""
Create a volcano plot (p-value vs. functional score).
*label* is the data label (barcode, variant, etc.)
*pdf* is an open PdfPages instance.
The p-values used are the regression p-values (p-value of non-zero slope). Due to the large number of points, we use a hexbin plot showing the density instead of a scatter plot.
"""
self.logger.info("Creating volcano plot ({})".format(label))
# get the data
data = self.store.select(
"/main/{}/scores".format(label), "columns=['score', 'pvalue_raw']"
)
volcano_plot(
data,
pdf,
title="{} ({})".format(self.name, label.title()),
colors=colors,
log_bins=log_bins,
)
示例7: visualize
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def visualize(file_path):
entries = []
with open(file_path) as f:
entries = [json.loads(line) for line in f.readlines() if line.strip()]
if not entries:
print('There is no data in file {}'.format(file_path))
return
pdf = backend_pdf.PdfPages("process_info.pdf")
idx = 0
names = [name for name in entries[0].keys() if name != 'time']
times = [entry['time'] for entry in entries]
for name in names:
values = [entry[name] for entry in entries]
fig = plt.figure()
ax = plt.gca()
ax.yaxis.set_major_formatter(tick.ScalarFormatter(useMathText=True))
plt.ticklabel_format(style='sci', axis='y', scilimits=(-2,3))
plt.plot(times, values, colors[idx % len(colors)], marker='x', label=name)
plt.xlabel('Time (sec)')
plt.ylabel(name)
plt.ylim(ymin=0)
plt.legend(loc = 'upper left')
pdf.savefig(fig)
idx += 1
plt.show()
pdf.close()
print('Generated process_info.pdf from {}'.format(file_path))
示例8: save_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def save_plot(is_save, save_path):
if is_save:
pdf = PdfPages(save_path)
pdf.savefig(bbox_inches='tight')
pdf.close()
示例9: setup_class
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def setup_class(cls):
if pdf_output:
from matplotlib.backends.backend_pdf import PdfPages
cls.pdf = PdfPages("predict_functional.pdf")
示例10: tm_para_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def tm_para_plot(tm_data, ordered_genomes, biotypes, para_tgt, unfiltered_para_tgt):
"""transMap paralogy plots"""
for key, tgt in [['Paralogy', para_tgt], ['UnfilteredParalogy', unfiltered_para_tgt]]:
legend_labels = ['= 1', '= 2', '= 3', '\u2265 4']
title_string = 'Proportion of transcripts that have multiple alignments'
biotype_title_string = 'Proportion of {} transcripts that have multiple alignments'
df = json_biotype_nested_counter_to_df(tm_data, key)
# we want a dataframe where each row is the counts, in genome order
# we construct the transpose first
r = []
df[key] = pd.to_numeric(df[key])
# make sure genomes are in order
df['genome'] = pd.Categorical(df['genome'], ordered_genomes, ordered=True)
df = df.sort_values('genome')
for biotype, biotype_df in df.groupby('biotype'):
for genome, genome_df in biotype_df.groupby('genome'):
high_para = genome_df[genome_df[key] >= 4]['count'].sum()
counts = dict(list(zip(genome_df[key], genome_df['count'])))
r.append([biotype, genome, counts.get(1, 0), counts.get(2, 0), counts.get(3, 0), high_para])
df = pd.DataFrame(r, columns=['biotype', 'genome', '1', '2', '3', '\u2265 4'])
sum_df = df.groupby('genome', sort=False).aggregate(sum).T
plot_fn = generic_unstacked_barplot if len(df.columns) <= 5 else generic_stacked_barplot
box_label = 'Number of\nalignments'
af = luigi.local_target.atomic_file(tgt.path)
with PdfPages(af.tmp_path) as pdf:
plot_fn(sum_df, pdf, title_string, legend_labels, 'Number of transcripts', ordered_genomes, box_label)
for biotype in biotypes:
biotype_df = biotype_filter(df, biotype)
if biotype_df is not None:
biotype_df = biotype_df.drop(['genome', 'biotype'], axis=1).T
title_string = biotype_title_string.format(biotype)
plot_fn(biotype_df, pdf, title_string, legend_labels, 'Number of transcripts', ordered_genomes,
box_label)
af.move_to_final_destination()
示例11: tm_gene_family_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def tm_gene_family_plot(tm_data, ordered_genomes, biotypes, gene_family_tgt):
"""transMap gene family collapse plots."""
try:
df = json_biotype_nested_counter_to_df(tm_data, 'Gene Family Collapse')
except ValueError: # no gene family collapse. probably the test set.
with gene_family_tgt.open('wb') as outf:
pass
return
df['Gene Family Collapse'] = pd.to_numeric(df['Gene Family Collapse'])
tot_df = df[['Gene Family Collapse', 'genome', 'count']].\
groupby(['genome', 'Gene Family Collapse']).aggregate(sum).reset_index()
tot_df = tot_df.sort_values('Gene Family Collapse')
af = luigi.local_target.atomic_file(gene_family_tgt.path)
with PdfPages(af.tmp_path) as pdf:
g = sns.factorplot(y='count', col='genome', x='Gene Family Collapse', data=tot_df, kind='bar',
col_order=ordered_genomes, col_wrap=4)
g.fig.suptitle('Number of genes collapsed during gene family collapse')
g.set_xlabels('Number of genes collapsed to one locus')
g.set_ylabels('Number of genes')
g.fig.subplots_adjust(top=0.9)
multipage_close(pdf, tight_layout=False)
for biotype in biotypes:
biotype_df = biotype_filter(df, biotype)
if biotype_df is None:
continue
biotype_df = biotype_df.sort_values('Gene Family Collapse')
g = sns.factorplot(y='count', col='genome', x='Gene Family Collapse', data=biotype_df, kind='bar',
col_order=[x for x in ordered_genomes if x in set(biotype_df.genome)], col_wrap=4)
g.fig.suptitle('Number of genes collapsed during gene family collapse for {}'.format(biotype))
g.set_xlabels('Number of genes collapsed to one locus')
g.set_ylabels('Number of genes')
g.fig.subplots_adjust(top=0.9)
multipage_close(pdf, tight_layout=False)
af.move_to_final_destination()
示例12: tx_modes_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def tx_modes_plot(consensus_data, ordered_genomes, tx_mode_plot_tgt):
ordered_groups = ['transMap', 'transMap+TM', 'transMap+TMR', 'transMap+TM+TMR', 'TM', 'TMR', 'TM+TMR', 'CGP', 'PB',
'exRef', 'other']
ordered_groups = OrderedDict([[frozenset(x.split('+')), x] for x in ordered_groups])
def split_fn(s):
return ordered_groups.get(frozenset(s['Transcript Modes'].replace('aug', '').split(',')), 'Other')
modes_df = json_biotype_counter_to_df(consensus_data, 'Transcript Modes')
df = modes_df.pivot(index='genome', columns='Transcript Modes').transpose().reset_index()
df['Modes'] = df.apply(split_fn, axis=1)
df = df[['Modes'] + ordered_genomes]
ordered_values = [x for x in ordered_groups.values() if x in set(df['Modes'])]
af = luigi.local_target.atomic_file(tx_mode_plot_tgt.path)
with PdfPages(af.tmp_path) as pdf:
title_string = 'Transcript modes in protein coding consensus gene set'
ylabel = 'Number of transcripts'
if len(ordered_genomes) > 1:
df['Ordered Modes'] = pd.Categorical(df['Modes'], ordered_values, ordered=True)
df = df.sort_values('Ordered Modes')
df = df[['Ordered Modes'] + ordered_genomes].set_index('Ordered Modes')
df = df.fillna(0)
generic_stacked_barplot(df, pdf, title_string, df.index, ylabel, ordered_genomes, 'Transcript mode(s)',
bbox_to_anchor=(1.25, 0.7))
else:
generic_barplot(pd.melt(df, id_vars='Modes'), pdf, 'Transcript mode(s)', ylabel, title_string, x='Modes',
y='value', order=ordered_values)
af.move_to_final_destination()
示例13: split_genes_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def split_genes_plot(tm_data, ordered_genomes, split_plot_tgt):
af = luigi.local_target.atomic_file(split_plot_tgt.path)
with PdfPages(af.tmp_path) as pdf:
df = json_biotype_counter_to_df(tm_data, 'Split Genes')
df.columns = ['category', 'count', 'genome']
title = 'Split genes'
if len(ordered_genomes) > 1:
g = generic_barplot(pdf=pdf, data=df, x='genome', y='count', col='category', xlabel='', col_wrap=2,
sharey=False, ylabel='Number of transcripts or genes', row_order=ordered_genomes,
title=title)
else:
g = generic_barplot(pdf=pdf, data=df, x='category', y='count', ylabel='Number of transcripts or genes',
title=title, xlabel='Category')
af.move_to_final_destination()
示例14: pb_support_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def pb_support_plot(consensus_data, ordered_genomes, pb_genomes, pb_support_tgt):
af = luigi.local_target.atomic_file(pb_support_tgt.path)
with PdfPages(af.tmp_path) as pdf:
pb_genomes = [x for x in ordered_genomes if x in pb_genomes] # fix order
df = json_biotype_counter_to_df(consensus_data, 'IsoSeq Transcript Validation')
if len(df) == 0:
# no support information
return
df.columns = ['IsoSeq Transcript Validation', 'Number of transcripts', 'genome']
ax = sns.factorplot(data=df, x='genome', y='Number of transcripts', hue='IsoSeq Transcript Validation',
kind='bar', row_order=pb_genomes)
ax.set_xticklabels(rotation=90)
ax.fig.suptitle('Isoforms validated by at least one IsoSeq read')
multipage_close(pdf, tight_layout=False)
af.move_to_final_destination()
示例15: completeness_plot
# 需要導入模塊: from matplotlib.backends import backend_pdf [as 別名]
# 或者: from matplotlib.backends.backend_pdf import PdfPages [as 別名]
def completeness_plot(consensus_data, ordered_genomes, biotypes, completeness_plot_tgt, gene_biotype_map,
transcript_biotype_map):
def adjust_plot(g, gene_count, tx_count):
for ax, c in zip(*[g.axes[0], [gene_count, tx_count]]):
_ = ax.set_ylim(0, c)
ax.spines['top'].set_edgecolor('#e74c3c')
ax.spines['top'].set_linewidth(2)
ax.spines['top'].set_visible(True)
ax.spines['top'].set_linestyle('dashed')
df = json_grouped_biotype_nested_counter_to_df(consensus_data, 'Completeness')
af = luigi.local_target.atomic_file(completeness_plot_tgt.path)
with PdfPages(af.tmp_path) as pdf:
tot_df = df.groupby(by=['genome', 'category']).aggregate(np.sum).reset_index()
tot_df = sort_long_df(tot_df, ordered_genomes)
title = 'Number of comparative genes/transcripts present'
g = generic_barplot(pdf=pdf, data=tot_df, x='genome', y='count', col='category', xlabel='',
sharey=False, ylabel='Number of genes/transcripts', title=title,
col_order=['Gene', 'Transcript'], close=False, palette=choose_palette(ordered_genomes))
adjust_plot(g, len(gene_biotype_map), len(transcript_biotype_map))
multipage_close(pdf, tight_layout=False)
for biotype in biotypes:
biotype_df = biotype_filter(df, biotype)
if biotype_df is not None:
biotype_df = sort_long_df(biotype_df, ordered_genomes)
gene_biotype_count = len({i for i, b in gene_biotype_map.items() if b == biotype})
tx_biotype_count = len({i for i, b in transcript_biotype_map.items() if b == biotype})
title = 'Number of comparative genes/transcripts present for biotype {}'.format(biotype)
g = generic_barplot(pdf=pdf, data=biotype_df, x='genome', y='count', col='category', xlabel='',
sharey=False, ylabel='Number of genes/transcripts',
title=title, col_order=['Gene', 'Transcript'], close=False,
palette=choose_palette(ordered_genomes))
adjust_plot(g, gene_biotype_count, tx_biotype_count)
multipage_close(pdf, tight_layout=False)
af.move_to_final_destination()