我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用seaborn.swarmplot()。
def plot_group(data_frame, path_output): # optional import import seaborn as sns path_output_image = os.path.join(path_output, "summary_statistics.png") # # Plotting swarmplot # plt.figure(num=None, figsize=(15, 7), dpi=120) # sns.set_style("whitegrid") # # plt.title('Violin plot with single measurements') # sns.violinplot(x="Group", y="DAB+ area", data=data_frame, inner=None) # sns.swarmplot(x="Group", y="DAB+ area", data=data_frame, color="w", alpha=.5) # plt.savefig(path_output_image) # # plt.tight_layout() sns.set_style("whitegrid") sns.set_context("talk") plt.figure(num=None, figsize=(15, 7), dpi=120) plt.ylim(0, 100) plt.title('Box plot') sns.boxplot(x="Group", y="DAB+ area, %", data=data_frame) plt.tight_layout() plt.savefig(path_output_image, dpi=300)
def swarm(data,x,y,xscale='linear',yscale='linear'): # set default pretty settings from Seaborn sns.set(style="white", palette="muted") sns.set_context("notebook", font_scale=1, rc={"lines.linewidth": 0.2}) # createthe plot g = sns.swarmplot(x=x, y=y, data=data, palette='RdYlGn') plt.tick_params(axis='both', which='major', pad=10) g.set(xscale=xscale) g.set(yscale=yscale) # Setting plot limits start = data[y].min().min() plt.ylim(start,); sns.despine()
def draw(self): def plot_facet(data, color): sns.swarmplot( x=data[self._groupby[-1]], y=data["coquery_invisible_corpus_id"], order=sorted(self._levels[-1]), palette=self.options["color_palette_values"], data=data) self.g.map_dataframe(plot_facet) ymax = options.cfg.main_window.Session.Corpus.get_corpus_size() self.g.set(ylim=(0, ymax)) self.g.set_axis_labels(self.options["label_x_axis"], self.options["label_y_axis"])
def plot_facet(self, data, color, x=None, y=None, levels_x=None, levels_y=None, palette=None, **kwargs): ax = kwargs.get("ax", plt.gca()) corpus_id = "coquery_invisible_corpus_id" params = {"data": data, "palette": palette} self.horizontal = True if not x and not y: params.update({"x": corpus_id}), self._xlab = x self._ylab = "" elif x and not y: params.update({"x": x, "y": corpus_id, "order": levels_x}) self.horizontal = False self._xlab = x self._ylab = "Corpus position" elif y and not x: params.update({"y": y, "x": corpus_id, "order": levels_y}) self._xlab = "Corpus position" self._ylab = y elif x and y: params.update({"x": corpus_id, "y": y, "hue": x, "order": levels_y, "hue_order": levels_x}) self._xlab = "Corpus position" self._ylab = y sns.swarmplot(**params) return ax
def plot_swarms(df, axes, palette): for exp, ax in zip(["dots", "sticks"], axes): exp_df = df.query("experiment == @exp") ax.axhline(.5, .1, .9, dashes=(5, 2), color=".6") ax.set(ylim=(.4, .9), yticks=[.4, .5, .6, .7, .8, .9]) sns.pointplot(x="roi", y="acc", data=exp_df, palette=palette, join=False, ci=None, ax=ax) points_to_lines(ax, lw=3) sns.swarmplot(x="roi", y="acc", data=exp_df, size=4, color=".85", # facecolor="none", linewidth=1, edgecolor=".4", ax=ax) ax.set(xlabel="", ylabel="", xticklabels=["IFS", "MFC"]) ax_l, ax_r = axes ax_l.set(ylabel="Decoding accuracy") ax_r.set(yticks=[]) ax_l.text(.5, .91, "Experiment 1", ha="center", va="center", size=7.5) ax_r.text(.5, .91, "Experiment 2", ha="center", va="center", size=7.5) sns.despine(ax=ax_l, trim=True) sns.despine(ax=ax_r, left=True, trim=True)
def sb_scatter(self, req, debug=False): image_list = [] image_filename = req["ImgFile"] import seaborn as sns import numpy as np from matplotlib import pyplot import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.patches import Rectangle from matplotlib.finance import volume_overlay import pandas as pd from pandas.tseries.offsets import BDay source_df = req["SourceDF"] ds_name = req["DSName"] sns.set_style("whitegrid", {'axes.grid' : True}) sns.color_palette("Set1", n_colors=8, desat=.5) cur_xlabel = "measurement" cur_ylabel = "value" cur_hue = "ResultLabel" cur_width = 10.0 cur_height = 10.0 if "X" in req: cur_xlabel = str(req["X"]) if "Y" in req: cur_ylabel = str(req["Y"]) if "Width" in req: cur_width = float(req["Width"]) if "Height" in req: cur_height = float(req["Height"]) if "Hue" in req: cur_hue = str(req["Hue"]) # end of parsing inputs # Add custom plots here plt.figure(figsize=(cur_width, cur_height)) ax = sns.swarmplot(x=cur_xlabel, y=cur_ylabel, hue=cur_hue, data=source_df) if debug: self.lg("Saving File(" + str(image_filename) + ")", 6) self.pd_add_footnote(ax.figure) ax.figure.savefig(image_filename) image_list.append(image_filename) if req["ShowPlot"] == True: plt.show() return image_list # end of sb_scatter
def plot_swarm(df, x, y, hue, tag='eda', directory=None): r"""Display a Swarm Plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``x`` and ``y`` features. x : str Variable name in ``df`` to display along the x-axis. y : str Variable name in ``df`` to display along the y-axis. hue : str Variable name to be used as hue, i.e., another data dimension. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.swarmplot.html """ logger.info("Generating Swarm Plot") # Generate the swarm plot swarm_plot = sns.swarmplot(x=x, y=y, hue=hue, data=df) swarm_fig = swarm_plot.get_figure() # Save the plot write_plot('seaborn', swarm_fig, 'swarm_plot', tag, directory) # # Time Series Plots # # # Function plot_time_series #
def plot_pair_by_layer(ax, layers, all_accs, maj, mfl, title, hide_xlabel=False, hide_ylabel=False, ymin=0, ymax=100, plot_maj=True, nbins=6, delta_above=True, delta_val=4): # compute stats means = np.mean(all_accs, axis=0) stds = np.std(all_accs, axis=0) maxs = np.max(all_accs, axis=0) mins = np.max(all_accs, axis=0) deltas = [0] + [means[i+1]-means[i] for i in range(len(means)-1)] num_runs = len(all_accs) flat_accs = np.concatenate(all_accs) df = pd.DataFrame({'Layer' : [0,1,2,3,4]*num_runs, 'Accuracy' : flat_accs }) ax.set_ylim(ymin,ymax) sns.swarmplot(x='Layer', y='Accuracy', data=df, ax=ax) if hide_xlabel: ax.set_xlabel('') if hide_ylabel: ax.set_ylabel('') if plot_maj: maj_line = ax.axhline(y=maj, label='Majority', linestyle='--', color='black') else: maj_line = None mfl_line = ax.axhline(y=mfl, label='MFL', linestyle='-.', color='black') for i in range(len(deltas)): if delta_above: x, y = i, maxs[i] + delta_val else: x, y = i, mins[i] - delta_val*2 str_val = '{:+.1f} ({:.1f})'.format(deltas[i], stds[i]) ax.text(x, y, str_val, horizontalalignment='center', size='small') xmin, xmax = plt.xlim() #ax.text(xmax-0.4, maj+1, 'maj', horizontalalignment='left', size='medium') #ax.text(xmax-0.4, mfl+1, 'mfl', horizontalalignment='left', size='medium') ax.locator_params(axis='y', nbins=nbins) ax.set_title(title) #ax.tight_layout() #plt.savefig(figname) return maj_line, mfl_line
def ageing_wip_chart(cycle_data, start_column, end_column, done_column=None, now=None, title=None, ax=None): if len(cycle_data.index) == 0: raise UnchartableData("Cannot draw ageing WIP chart with no data") if ax is None: fig, ax = plt.subplots() if title is not None: ax.set_title(title) if now is None: now = pd.Timestamp.now() if done_column is None: done_column = cycle_data.columns[-1] today = now.date() # remove items that are done cycle_data = cycle_data[pd.isnull(cycle_data[done_column])] # Check that we still have some data to proceed with. if len(cycle_data.index) == 0: raise UnchartableData("Cannot draw ageing WIP chart with no data - All items done!") cycle_data = pd.concat(( cycle_data[['key', 'summary']], cycle_data.ix[:, start_column:end_column] ), axis=1) def extract_status(row): last_valid = row.last_valid_index() if last_valid is None: return np.NaN return last_valid def extract_age(row): started = row[start_column] if pd.isnull(started): return np.NaN return (today - started.date()).days wip_data = cycle_data[['key', 'summary']].copy() wip_data['status'] = cycle_data.apply(extract_status, axis=1) wip_data['age'] = cycle_data.apply(extract_age, axis=1) wip_data.dropna(how='any', inplace=True) sns.swarmplot(x='status', y='age', order=cycle_data.columns[2:], data=wip_data, ax=ax) ax.set_xlabel("Status") ax.set_ylabel("Age (days)") ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=90) bottom, top = ax.get_ylim() ax.set_ylim(0, top) return ax
def gRNA_swarmplot(s1, s2, prefix=""): # Rank of gRNA change fig, axis = plt.subplots(3, 2, sharex=True, sharey=True, figsize=(8, 8)) axis = axis.flatten() for i, screen in enumerate(s2.columns[::-1]): s = s1.join(s2) # .fillna(0) s = s.iloc[np.random.permutation(len(s))] if ("TCR" in screen) or ("Jurkat" in screen) or ("stimulated" in screen) or ("unstimulated" in screen): s = s.ix[s.index[~s.index.str.contains("Wnt")]] if prefix.startswith("mid_screen-"): b = s["gDNA_Jurkat"] else: b = s["plasmid_pool_TCR"] x = s.ix[s.index[s.index.str.contains("Tcr")]] y = s.ix[s.index[s.index.str.contains("Essential")]] z = s.ix[s.index[s.index.str.contains("CTRL")]] b_x = b.ix[s.index[s.index.str.contains("Tcr")]] b_y = b.ix[s.index[s.index.str.contains("Essential")]] b_z = b.ix[s.index[s.index.str.contains("CTRL")]] elif ("WNT" in screen) or ("HEK" in screen): s = s.ix[s.index[~s.index.str.contains("Tcr")]] if prefix.startswith("mid_screen-"): if "_4_" in prefix: b = s["gDNA_HEKclone4"] else: b = s["gDNA_HEKclone6"] else: b = s["plasmid_pool_WNT"] x = s.ix[s.index[s.index.str.contains("Wnt")]] y = s.ix[s.index[s.index.str.contains("Essential")]] z = s.ix[s.index[s.index.str.contains("CTRL")]] b_x = b.ix[s.index[s.index.str.contains("Wnt")]] b_y = b.ix[s.index[s.index.str.contains("Essential")]] b_z = b.ix[s.index[s.index.str.contains("CTRL")]] fc_x = np.log2(1 + x[screen]) - np.log2(1 + b_x) fc_y = np.log2(1 + y[screen]) - np.log2(1 + b_y) fc_z = np.log2(1 + z[screen]) - np.log2(1 + b_z) fc_x.name = screen fc_y.name = "Essential" fc_z.name = "CTRL" sns.violinplot(x="variable", y="value", alpha=0.1, inner="box", data=pd.melt(pd.DataFrame([fc_x, fc_y, fc_z]).T), ax=axis[i]) sns.swarmplot(x="variable", y="value", alpha=0.5, data=pd.melt(pd.DataFrame([fc_x, fc_y, fc_z]).T), ax=axis[i]) axis[i].axhline(y=0, color='black', linestyle='--', lw=0.5) axis[i].set_title(screen) sns.despine(fig) fig.savefig(os.path.join(results_dir, "gRNA_counts.norm.{}.violin_swarmplot.svg".format(prefix)), bbox_inches="tight")