我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用seaborn.axes_style()。
def plot_1d(dataset, nbins, data): with sns.axes_style('white'): plt.rc('font', weight='bold') plt.rc('grid', lw=2) plt.rc('lines', lw=3) plt.figure(1) plt.hist(data, bins=np.arange(nbins+1), color='blue') plt.ylabel('Count', weight='bold', fontsize=24) xticks = list(plt.gca().get_xticks()) while (nbins-1) / float(xticks[-1]) < 1.1: xticks = xticks[:-1] while xticks[0] < 0: xticks = xticks[1:] xticks.append(nbins-1) xticks = list(sorted(xticks)) plt.gca().set_xticks(xticks) plt.xlim([int(np.ceil(-0.05*nbins)),int(np.ceil(nbins*1.05))]) plt.legend(loc='upper right') plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight') plt.clf() plt.close()
def plot_2d(dataset, nbins, data, extra=None): with sns.axes_style('white'): plt.rc('font', weight='bold') plt.rc('grid', lw=2) plt.rc('lines', lw=2) rows, cols = nbins im = np.zeros(nbins) for i in xrange(rows): for j in xrange(cols): im[i,j] = ((data[:,0] == i) & (data[:,1] == j)).sum() plt.imshow(im, cmap='gray_r', interpolation='none') if extra is not None: dataset += extra plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight') plt.clf() plt.close()
def plot_1d(dataset, nbins): data = np.loadtxt('experiments/uci/data/splits/{0}_all.csv'.format(dataset), skiprows=1, delimiter=',')[:,-1] with sns.axes_style('white'): plt.rc('font', weight='bold') plt.rc('grid', lw=2) plt.rc('lines', lw=3) plt.figure(1) plt.hist(data, bins=np.arange(nbins+1), color='blue') plt.ylabel('Count', weight='bold', fontsize=24) xticks = list(plt.gca().get_xticks()) while (nbins-1) / float(xticks[-1]) < 1.1: xticks = xticks[:-1] while xticks[0] < 0: xticks = xticks[1:] xticks.append(nbins-1) xticks = list(sorted(xticks)) plt.gca().set_xticks(xticks) plt.xlim([int(np.ceil(-0.05*nbins)),int(np.ceil(nbins*1.05))]) plt.legend(loc='upper right') plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight') plt.clf() plt.close()
def plot_2d(dataset, nbins, data=None, extra=None): if data is None: data = np.loadtxt('experiments/uci/data/splits/{0}_all.csv'.format(dataset), skiprows=1, delimiter=',')[:,-2:] with sns.axes_style('white'): plt.rc('font', weight='bold') plt.rc('grid', lw=2) plt.rc('lines', lw=2) rows, cols = nbins im = np.zeros(nbins) for i in xrange(rows): for j in xrange(cols): im[i,j] = ((data[:,0] == i) & (data[:,1] == j)).sum() plt.imshow(im, cmap='gray_r', interpolation='none') if extra is not None: dataset += extra plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight') plt.clf() plt.close()
def joint_plot(x, y, xlabel=None, ylabel=None, xlim=None, ylim=None, loc="best", color='#0485d1', size=8, markersize=50, kind="kde", scatter_color="r"): with sns.axes_style("darkgrid"): if xlabel and ylabel: g = SubsampleJointGrid(xlabel, ylabel, data=DataFrame(data={xlabel: x, ylabel: y}), space=0.1, ratio=2, size=size, xlim=xlim, ylim=ylim) else: g = SubsampleJointGrid(x, y, size=size, space=0.1, ratio=2, xlim=xlim, ylim=ylim) g.plot_joint(sns.kdeplot, shade=True, cmap="Blues") g.plot_sub_joint(plt.scatter, 1000, s=20, c=scatter_color, alpha=0.3) g.plot_marginals(sns.distplot, kde=False, rug=False) g.annotate(ss.pearsonr, fontsize=25, template="{stat} = {val:.2g}\np = {p:.2g}") g.ax_joint.set_yticklabels(g.ax_joint.get_yticks()) g.ax_joint.set_xticklabels(g.ax_joint.get_xticks()) return g
def plot_settings(): style = sns.axes_style('darkgrid') style['font.size'] = 12.0 style['font.family'] = 'monospace' style['font.weight'] = 'normal' style['font.sans-serif'] = ('Helveitca', 'Bitstream Vera Sans', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Avant Garde', 'sans-serif') style['font.monospace'] = ('Decima Mono', 'Bitstream Vera Sans Mono', 'Andale Mono', 'Nimbus Mono L', 'Courier New', 'Courier', 'Fixed', 'Terminal', 'monospace') style['text.color'] = '#222222' style['pdf.fonttype'] = 42 return style
def setup_figure(self): with sns.axes_style("whitegrid"): super(Visualizer, self).setup_figure()
def get_grid(self, **kwargs): with sns.axes_style("whitegrid"): grid = super(TimeSeries, self).get_grid(**kwargs) return grid
def setup_figure(self): with sns.axes_style("ticks"): super(Visualizer, self).setup_figure()
def get_grid(self, **kwargs): kwargs["data"] = self.df with sns.axes_style(self.axes_style): with sns.plotting_context(self.plotting_context): grid = sns.FacetGrid(**kwargs) return grid
def setup_figure(self): with sns.axes_style("white"): super(Visualizer, self).setup_figure()
def plot_learning_function(xdata, ydata, yerr, order, aplot, poly): with sns.axes_style('whitegrid'): sns.set_context('paper') xp = np.linspace(np.min(xdata), np.max(xdata), 1000)[:, None] plt.figure() plt.errorbar(xdata, ydata, yerr, label='Nearest similarity', marker='s') plt.plot(xp, poly(xp), '-', label='Learning function (poly of order {})'.format(order)) # plt.plot(xp, least_squares_mdl(res.x, xp), '-', label='least squares') plt.xlabel(r'Mutation level') plt.ylabel(r'Average similarity (not normalised)') plt.legend(loc='lower left') plt.savefig(aplot, transparent=True, bbox_inches='tight') plt.close()
def powerplant_map(): with sns.axes_style('darkgrid'): df = set_uncommon_fueltypes_to_other(Carma_ENTSOE_ESE_GEO_OPSD_WRI_matched_reduced()) shown_fueltypes = ['Hydro', 'Natural Gas', 'Nuclear', 'Hard Coal', 'Lignite', 'Oil'] df = df[df.Fueltype.isin(shown_fueltypes) & df.lat.notnull()] fig, ax = plt.subplots(figsize=(7,5)) scale = 5e1 #df.plot.scatter('lon', 'lat', s=df.Capacity/scale, c=df.Fueltype.map(utils.tech_colors), # ax=ax) ax.scatter(df.lon, df.lat, s=df.Capacity/scale, c=df.Fueltype.map(tech_colors2)) ax.set_xlabel('') ax.set_ylabel('') draw_basemap() ax.set_xlim(-13, 34) ax.set_ylim(35, 71.65648314) ax.set_axis_bgcolor('white') fig.tight_layout(pad=0.5) legendcols = pd.Series(tech_colors2).reindex(shown_fueltypes) handles = sum(legendcols.apply(lambda x : make_legend_circles_for([10.], scale=scale, facecolor=x)).tolist(), []) fig.legend(handles, legendcols.index, handler_map=make_handler_map_to_scale_circles_as_in(ax), ncol=3, loc="upper left", frameon=False, fontsize=11) return fig, ax
def bar_fueltype_totals(dfs, keys, figsize=(7,4), unit='GW', show_totals=False, last_as_marker=False): with sns.axes_style('darkgrid'): fig, ax = plt.subplots(1,1, figsize=figsize) if last_as_marker: as_marker = dfs[-1] dfs = dfs[:-1] as_marker_key = keys[-1] keys = keys[:-1] fueltotals = lookup(dfs, keys=keys, by='Fueltype' ,show_totals=show_totals, unit=unit) fueltotals.plot(kind="bar", ax=ax, legend='reverse', edgecolor='none', rot=75) if last_as_marker: fueltotals = lookup(as_marker, keys=as_marker_key, by='Fueltype' ,show_totals=show_totals, unit=unit) fueltotals.plot(ax=ax, label=as_marker_key, markeredgecolor='none', rot=75, marker='D', markerfacecolor='darkslategray', linestyle='None') ax.legend(loc=0) ax.set_ylabel(r'Capacity [$%s$]'%unit) ax.xaxis.grid(False) fig.tight_layout(pad=0.5) return fig, ax
def bar_matching_fueltype_totals(figsize=(7,4)): from . import data from .collection import Carma_ENTSOE_GEO_OPSD_WRI_matched_reduced matched = set_uncommon_fueltypes_to_other( Carma_ENTSOE_GEO_OPSD_WRI_matched_reduced()) matched.loc[matched.Fueltype=='Waste', 'Fueltype']='Other' geo=set_uncommon_fueltypes_to_other(data.GEO()) carma=set_uncommon_fueltypes_to_other(data.CARMA()) wri=set_uncommon_fueltypes_to_other(data.WRI()) ese=set_uncommon_fueltypes_to_other(data.ESE()) entsoe = set_uncommon_fueltypes_to_other(data.Capacity_stats()) opsd = set_uncommon_fueltypes_to_other(data.OPSD()) entsoedata = set_uncommon_fueltypes_to_other(data.ENTSOE()) matched.Capacity = matched.Capacity/1000. geo.Capacity = geo.Capacity/1000. carma.Capacity = carma.Capacity/1000. wri.Capacity = wri.Capacity/1000. ese.Capacity = ese.Capacity/1000. entsoe.Capacity = entsoe.Capacity/1000. opsd.Capacity = opsd.Capacity/1000. entsoedata.Capacity = entsoedata.Capacity/1000. with sns.axes_style('whitegrid'): fig, (ax1,ax2) = plt.subplots(1,2, figsize=figsize, sharey=True) databases = lookup([carma, entsoedata, ese, geo, opsd, wri], keys=[ 'CARMA', 'ENTSOE','ESE', 'GEO','OPSD', 'WRI'], by='Fueltype') databases.plot(kind='bar', ax=ax1, edgecolor='none') datamatched = lookup(matched, by='Fueltype') datamatched.index.name='' datamatched.name='Matched Database' datamatched.plot(kind='bar', ax=ax2, #color=cmap[3:4], edgecolor='none') ax2.legend() ax1.set_ylabel('Capacity [GW]') ax1.xaxis.grid(False) ax2.xaxis.grid(False) fig.tight_layout(pad=0.5) return fig, [ax1,ax2]
def hbar_country_totals(dfs, keys, exclude_fueltypes=['Solar', 'Wind'], figsize=(7,5), unit='GW'): with sns.axes_style('whitegrid'): fig, ax = plt.subplots(1,1, figsize=figsize) countrytotals = lookup(dfs, keys=keys, by='Country', exclude=exclude_fueltypes,show_totals=True, unit=unit) countrytotals[::-1][1:].plot(kind="barh", ax=ax, legend='reverse', edgecolor='none') ax.set_xlabel('Capacity [%s]'%unit) ax.yaxis.grid(False) ax.set_ylabel('') fig.tight_layout(pad=0.5) return fig, ax
def start_plotting(fig_size, fig_pos, style="white", rc=None, despine=False): with sns.axes_style(style, rc): fig = plt.figure(figsize=fig_size) if not fig_pos: ax = fig.add_subplot(111) else: ax = fig.add_axes(fig_pos) if despine: sns.despine(left=True) return fig, ax
def improvement_plot(consensus_data, ordered_genomes, improvement_tgt): def do_kdeplot(x, y, ax, n_levels=None, bw='scott'): try: sns.kdeplot(x, y, ax=ax, cut=0, cmap='Purples_d', shade=True, shade_lowest=False, n_levels=n_levels, bw=bw, rasterized=True) except: logger.warning('Unable to do a KDE fit to AUGUSTUS improvement.') pass with improvement_tgt.open('w') as outf, PdfPages(outf) as pdf, sns.axes_style("whitegrid"): for genome in ordered_genomes: data = pd.DataFrame(consensus_data[genome]['Evaluation Improvement']['changes']) unchanged = consensus_data[genome]['Evaluation Improvement']['unchanged'] if len(data) == 0: continue data.columns = ['transMap original introns', 'transMap intron annotation support', 'transMap intron RNA support', 'Original introns', 'Intron annotation support', 'Intron RNA support', 'transMap alignment goodness', 'Alignment goodness'] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2) for ax in [ax1, ax2, ax3]: # goodness plots are allowed to auto-set scale ax.set_xlim(0, 100) ax.set_ylim(0, 100) goodness_min = min(data['Alignment goodness']) ax4.set_xlim(goodness_min, 100) ax4.set_ylim(goodness_min, 100) do_kdeplot(data['transMap original introns'], data['Original introns'], ax1, n_levels=25, bw=2) sns.regplot(x=data['transMap original introns'], y=data['Original introns'], ax=ax1, color='#A9B36F', scatter_kws={"s": 3, 'alpha': 0.7, 'rasterized': True}, fit_reg=False) do_kdeplot(data['transMap intron annotation support'], data['Intron annotation support'], ax2, n_levels=25, bw=2) sns.regplot(x=data['transMap intron annotation support'], y=data['Intron annotation support'], ax=ax2, color='#A9B36F', scatter_kws={"s": 3, 'alpha': 0.7, 'rasterized': True}, fit_reg=False) do_kdeplot(data['transMap intron RNA support'], data['Intron RNA support'], ax3, n_levels=25, bw=2) sns.regplot(x=data['transMap intron RNA support'], y=data['Intron RNA support'], ax=ax3, color='#A9B36F', scatter_kws={"s": 3, 'alpha': 0.7, 'rasterized': True}, fit_reg=False) do_kdeplot(data['transMap alignment goodness'], data['Alignment goodness'], ax4, n_levels=20, bw=1) sns.regplot(x=data['transMap alignment goodness'], y=data['Alignment goodness'], ax=ax4, color='#A9B36F', scatter_kws={"s": 3, 'alpha': 0.7, 'rasterized': True}, fit_reg=False) fig.suptitle('AUGUSTUS metric improvements for {:,} transcripts in {}.\n' '{:,} transMap transcripts were chosen.'.format(len(data), genome, unchanged)) for ax in [ax1, ax2, ax3, ax4]: ax.set(adjustable='box-forced', aspect='equal') fig.subplots_adjust(hspace=0.3) multipage_close(pdf, tight_layout=False)
def comparison_1dim(by='Country', include_WEPP=True, include_VRE=False, year=2015, how='hbar', figsize=(7,5)): """ Plots a horizontal bar chart with capacity on x-axis, ``by`` on y-axis. Parameters ---------- by : string, defines how to group data Allowed values: 'Country' or 'Fueltype' """ red_w_wepp, red_wo_wepp, wepp, statistics = gather_comparison_data(include_WEPP=include_WEPP, include_VRE=include_VRE, year=year) if include_WEPP: stats = lookup([red_w_wepp, red_wo_wepp, wepp, statistics], keys=['Matched dataset w/ WEPP', 'Matched dataset w/o WEPP', 'WEPP only', 'Statistics OPSD'], by=by)/1000 else: stats = lookup([red_wo_wepp, statistics], keys=['Matched dataset w/o WEPP', 'Statistics OPSD'], by=by)/1000 if how == 'hbar': with sns.axes_style('darkgrid'): font={'size' : 24} plt.rc('font', **font) fig, ax = plt.subplots(figsize=figsize) stats.plot.barh(ax=ax, stacked=False, colormap='jet') ax.set_xlabel('Installed Capacity [GW]') ax.yaxis.label.set_visible(False) #ax.set_facecolor('#d9d9d9') # gray background ax.set_axisbelow(True) # puts the grid behind the bars ax.grid(color='white', linestyle='dotted') # adds white dotted grid ax.legend(loc='best') ax.invert_yaxis() return fig, ax if how == 'scatter': stats.loc[:, by] = stats.index.astype(str) #Needed for seaborne if len(stats.columns)-1 >= 3: g = sns.pairplot(stats, diag_kind='kde', hue=by, palette='Set2', size=figsize[1], aspect=figsize[0]/figsize[1]) else: g = sns.pairplot(stats, diag_kind='kde', hue=by, palette='Set2', size=figsize[1], aspect=figsize[0]/figsize[1], x_vars=stats.columns[0], y_vars=stats.columns[1]) for i in range(0, len(g.axes)): for j in range(0, len(g.axes[0])): g.axes[i,j].set(xscale='log', yscale='log', xlim=(1,200), ylim=(1,200)) return g.fig, g.axes