本文整理汇总了Python中matplotlib.pyplot.rc_context函数的典型用法代码示例。如果您正苦于以下问题:Python rc_context函数的具体用法?Python rc_context怎么用?Python rc_context使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rc_context函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _fig_size_cntx
def _fig_size_cntx(fig, fig_size_inches, tight_layout):
"""Resize a figure in a context
Parameters
----------
fig : matplotlib.figure.Figure
The figure to resize
fig_size_inches : tuple
The (height, width) to use in the context. If None, the size
is not changed
tight_layout : boolean
When True, tight layout is used.
"""
orig_size = fig.get_size_inches()
orig_layout = fig.get_tight_layout()
if fig_size_inches is not None:
fig.set_size_inches(*fig_size_inches)
fig.set_tight_layout(tight_layout)
if tight_layout:
rc_params = {'savefig.bbox': 'tight'}
else:
rc_params = {'savefig.bbox': 'standard'}
try:
with plt.rc_context(rc_params):
yield fig
finally:
fig.set_size_inches(*orig_size)
fig.set_tight_layout(orig_layout)
示例2: filterstats
def filterstats(input_fn, output_dir, topn=None,
maxeerates=[0.25, 0.5, 0.75, 1, 1.25, 1.5], maxns=None):
if not os.path.isdir(output_dir):
raise ValueError("directory {} does not exist".format(output_dir))
minlen_fn = os.path.join(output_dir, "filterstats_minlen.txt")
trunclen_fn = os.path.join(output_dir, "filterstats_trunclen.txt")
plot_fn = os.path.join(output_dir, "filterstats_plot.png")
minlen, trunclen = _stats(
input_fn=input_fn,
topn=topn,
maxeerates=maxeerates,
maxns=maxns)
minlen.to_csv(minlen_fn, sep="\t", float_format="%.3f", index=False)
trunclen.to_csv(trunclen_fn, sep="\t", float_format="%.3f", index=False)
# custom rc. svg.fonttype": "none" corrects the conversion of text in PDF
# and SVG files
rc = {
"xtick.labelsize": 8,
"ytick.labelsize": 8,
"axes.labelsize": 10,
"legend.fontsize": 10,
"svg.fonttype": "none"}
with plt.rc_context(rc=rc):
_plot(minlen, trunclen, plot_fn)
示例3: stats
def stats(input_fn, output_dir, topn=None):
if not os.path.isdir(output_dir):
raise ValueError("directory {} does not exist".format(output_dir))
len_dist_fn = os.path.join(output_dir, "stats_lendist.txt")
qual_dist_fn = os.path.join(output_dir, "stats_qualdist.txt")
qual_summ_fn = os.path.join(output_dir, "stats_qualsumm.txt")
len_dist_plot_fn = os.path.join(output_dir, "stats_lendist_plot.png")
qual_dist_plot_fn = os.path.join(output_dir, "stats_qualdist_plot.png")
qual_summ_plot_fn = os.path.join(output_dir, "stats_qualsumm_plot.png")
len_dist, qual_dist, qual_summ = _stats(input_fn=input_fn, topn=topn)
len_dist.to_csv(len_dist_fn, sep="\t", float_format="%.3f", index=False)
qual_dist.to_csv(qual_dist_fn, sep="\t", float_format="%.3f", index=False)
qual_summ.to_csv(qual_summ_fn, sep="\t", float_format="%.3f", index=False)
# custom rc. "svg.fonttype: none" corrects the conversion of text in PDF
# and SVG files
rc = {
"xtick.labelsize": 8,
"ytick.labelsize": 8,
"axes.labelsize": 10,
"legend.fontsize": 10,
"svg.fonttype": "none"}
with plt.rc_context(rc=rc):
_plot_len_dist(len_dist, len_dist_plot_fn)
_plot_qual_dist(qual_dist, qual_dist_plot_fn)
_plot_qual_summ(qual_summ, qual_summ_plot_fn)
示例4: plot_alpha
def plot_alpha(metadata, category, hue):
import seaborn as sns
with plt.rc_context(dict(sns.axes_style("darkgrid"),
**sns.plotting_context("notebook", font_scale=2))):
width = len(metadata[category].unique())
plt.figure(figsize=(width*4, 8))
sns.boxplot(x=category, y='Alpha diversity',
data=metadata.sort(category), hue=hue, palette='cubehelix')
示例5: minorticksubplot
def minorticksubplot(xminor, yminor, i):
rc = {'xtick.minor.visible': xminor,
'ytick.minor.visible': yminor}
with plt.rc_context(rc=rc):
ax = fig.add_subplot(2, 2, i)
assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor
assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor
示例6: test_get_color_cycle
def test_get_color_cycle(self):
if mpl_ge_150:
colors = [(1., 0., 0.), (0, 1., 0.)]
prop_cycle = plt.cycler(color=colors)
with plt.rc_context({"axes.prop_cycle": prop_cycle}):
result = utils.get_color_cycle()
assert result == colors
示例7: view
def view(self, test=False):
"""Displays the graph"""
if test:
self._attr["style"] = True
AttrConf.MPL_STYLE["interactive"] = False
if self._attr["concat"]:
if self._attr["style"]:
with plt.rc_context(AttrConf.MPL_STYLE):
self._plot_concat()
else:
self._plot_concat()
else:
if self._attr["style"]:
with plt.rc_context(AttrConf.MPL_STYLE):
self._plot(self._attr["permute"])
else:
self._plot(self._attr["permute"])
示例8: create_icon_axes
def create_icon_axes(fig, ax_position, lw_bars, lw_grid, lw_border, rgrid):
"""
Create a polar axes containing the matplotlib radar plot.
Parameters
----------
fig : matplotlib.figure.Figure
The figure to draw into.
ax_position : (float, float, float, float)
The position of the created Axes in figure coordinates as
(x, y, width, height).
lw_bars : float
The linewidth of the bars.
lw_grid : float
The linewidth of the grid.
lw_border : float
The linewidth of the Axes border.
rgrid : array-like
Positions of the radial grid.
Returns
-------
ax : matplotlib.axes.Axes
The created Axes.
"""
with plt.rc_context({'axes.edgecolor': MPL_BLUE,
'axes.linewidth': lw_border}):
ax = fig.add_axes(ax_position, projection='polar')
ax.set_axisbelow(True)
N = 7
arc = 2. * np.pi
theta = np.arange(0.0, arc, arc / N)
radii = np.array([2, 6, 8, 7, 4, 5, 8])
width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3])
bars = ax.bar(theta, radii, width=width, bottom=0.0, align='edge',
edgecolor='0.3', lw=lw_bars)
for r, bar in zip(radii, bars):
color = *cm.jet(r / 10.)[:3], 0.6 # color from jet with alpha=0.6
bar.set_facecolor(color)
ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
ax.grid(lw=lw_grid, color='0.9')
ax.set_rmax(9)
ax.set_yticks(rgrid)
# the actual visible background - extends a bit beyond the axis
ax.add_patch(Rectangle((0, 0), arc, 9.58,
facecolor='white', zorder=0,
clip_on=False, in_layout=False))
return ax
示例9: prepare
def prepare(self):
sns.set_style('ticks')
sns.set_context('paper')
with plt.rc_context(plot_params):
self.fig = plt.figure(figsize=(7, 7))
gs = plt.GridSpec(3, 2)
self.ax = {
'ispectrum': self.fig.add_subplot(gs[2, :]),
'scatter': self.fig.add_subplot(gs[:2, :]),
}
# self.ax['violin'] = self.fig.add_subplot(gs[1:, -1])
self.gs = gs
示例10: view
def view(self, test=False):
"""Displays the graph"""
if test:
self._attr["style"] = True
AttrConf.MPL_STYLE["interactive"] = False
permute = self._attr["permute"] and not self._attr["concat"]
if self._attr["style"]:
with plt.rc_context(AttrConf.MPL_STYLE):
self._resolve(permute, self._attr["concat"])
else:
self._resolve(permute, self._attr["concat"])
示例11: stats
def stats(input_fn, output_dir, step=100, replace=False, seed=0):
if not os.path.isdir(output_dir):
raise ValueError("directory {} does not exist".format(output_dir))
sample_summ_fn = os.path.join(output_dir, "tablestats_samplesumm.txt")
otu_summ_fn = os.path.join(output_dir, "tablestats_otusumm.txt")
rarecurve_fn = os.path.join(output_dir, "tablestats_rarecurve.txt")
rarecurve_plot_fn = os.path.join(output_dir, "tablestats_rarecurve_plot.png")
table = micca.table.read(input_fn)
# sample summary
sample_summ = pd.DataFrame({
"Depth": table.sum(),
"NOTU": (table > 0).sum(),
"NSingle": (table == 1).sum()},
columns=["Depth", "NOTU", "NSingle"])
sample_summ.index.name = "Sample"
sample_summ.sort_values(by="Depth", inplace=True)
sample_summ.to_csv(sample_summ_fn, sep='\t')
# OTU summary
otu_summ = pd.DataFrame({
"N": table.sum(axis=1),
"NSample": (table > 0).sum(axis=1)},
columns=["N", "NSample"])
otu_summ.index.name = "OTU"
otu_summ.sort_values(by="N", inplace=True, ascending=False)
otu_summ.to_csv(otu_summ_fn, sep='\t')
# rarefaction curves
rarecurve = micca.table.rarecurve(table, step=step, replace=replace,
seed=seed)
rarecurve.to_csv(rarecurve_fn, sep='\t', float_format="%.0f", na_rep="NA")
# custom rc. "svg.fonttype: none" corrects the conversion of text in PDF
# and SVG files
rc = {
"xtick.labelsize": 8,
"ytick.labelsize": 8,
"axes.labelsize": 10,
"legend.fontsize": 10,
"svg.fonttype": "none"}
with plt.rc_context(rc=rc):
fig = plt.figure(figsize=(10, 6))
plt.plot(rarecurve.index, rarecurve.to_numpy(), color="k")
plt.xlabel("Depth")
plt.ylabel("#OTUs")
fig.savefig(rarecurve_plot_fn, dpi=300, bbox_inches='tight', format="png")
示例12: prepare
def prepare(self):
sns.set_style('ticks')
sns.set_context('paper')
with plt.rc_context(plot_params):
self.fig = plt.figure(figsize=(7, 7))
gs = plt.GridSpec(3, 12)
self.ax = {
'spectrum': self.fig.add_subplot(gs[:2, 4:]),
'ISI': self.fig.add_subplot(gs[0, :4]),
'cycle': self.fig.add_subplot(gs[1, :4]),
'vs_freq': self.fig.add_subplot(gs[2, :4]),
}
self.ax['cycle_ampl'] = self.ax['cycle'].twinx()
self.ax['circ'] = self.fig.add_subplot(gs[2, 4:8])
self.ax['contrast'] = self.fig.add_subplot(gs[2, 8:])
示例13: prepare
def prepare(self):
sns.set_style('ticks')
sns.set_context('paper')
with plt.rc_context(plot_params):
self.fig = plt.figure(figsize=(7, 7))
gs = plt.GridSpec(3, 2)
self.ax = {
'scatter': self.fig.add_subplot(gs[-1, :]),
# 'spectrum': self.fig.add_subplot(gs[1:, :-1]),
'ISI': self.fig.add_subplot(gs[1, 1]),
'EOD': self.fig.add_subplot(gs[1, 0]),
}
self.ax['scatter_base'] = self.fig.add_subplot(gs[0, :])
self.ax['EOD_ampl'] = self.ax['EOD'].twinx()
self.gs = gs
示例14: plot_dendrogram
def plot_dendrogram(clustering, size=10):
link = clustering['linkage']
labels = clustering['labels']
link_function, colors = get_dendrogram_color_fun(link, clustering['reorder_vec'],
labels)
# set figure properties
figsize = (size, size*.6)
with sns.axes_style('white'):
fig = plt.figure(figsize=figsize)
# **********************************
# plot dendrogram
# **********************************
with plt.rc_context({'lines.linewidth': size*.125}):
dendrogram(link, link_color_func=link_function,
orientation='top')
示例15: plot_stacked_bar
def plot_stacked_bar(df):
import seaborn as sns
with plt.rc_context(dict(sns.axes_style("darkgrid"),
**sns.plotting_context("notebook", font_scale=1.8))):
f, ax = plt.subplots(1, figsize=(10, 10))
x = list(range(len(df.columns)))
bottom = np.array([0] * len(df.columns))
cat_percents = []
for id_ in df.index:
color = '#' + ''.join(np.random.choice(list('ABCDEF123456789'), 6))
ax.bar(x, df.loc[id_], color=color, bottom=bottom, align='center')
bottom = df.loc[id_] + bottom
cat_percents.append(''.join(["[{0:.2f}] ".format(x) for x in df.loc[id_].tolist()]))
legend_labels = [' '.join(e) for e in zip(cat_percents, df.index.tolist())]
ax.set_xticks(x)
ax.set_xticklabels(df.columns.tolist())
ax.set_ylim([0, 1])
ax.legend(legend_labels, loc='center left', bbox_to_anchor=(1, 0.5))