Skip to content

Instantly share code, notes, and snippets.

@CnrLwlss
Last active November 6, 2021 14:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CnrLwlss/22f4abbb11e4ab01ae8bb35e041941bb to your computer and use it in GitHub Desktop.
Save CnrLwlss/22f4abbb11e4ab01ae8bb35e041941bb to your computer and use it in GitHub Desktop.
Script for plotting stripplot or swarmplot with barplot overlay, including custom error bars, with matplotlib/Seaborn.
import seaborn as sns
tips = sns.load_dataset("tips")
print(sns.__version__)
print(tips.head())
ax=sns.swarmplot(x="day", y="total_bill", hue="sex", data=tips,split=True)
sns.barplot(x="day", y="total_bill", hue="sex", data=tips,capsize=0.1,errwidth=1.25,alpha=0.25,ci=None)
xcentres=[0,1,2,3]
delt=0.2
xneg=[x-delt for x in xcentres]
xpos=[x+delt for x in xcentres]
xvals=xneg+xpos
xvals.sort()
yvals=tips.groupby(["day","sex"]).mean().total_bill
yerr=tips.groupby(["day","sex"]).std().total_bill
(_, caps, _)=ax.errorbar(x=xvals,y=yvals,yerr=yerr,fmt=None,capsize=4,errwidth=1.25,ecolor="red")
for cap in caps:
cap.set_markeredgewidth(2)
handles, labels = ax.get_legend_handles_labels()
l = sns.plt.legend(handles[0:2], labels[0:2])
sns.plt.ylim([0,60])
sns.plt.ylabel("Total Bill ($)")
sns.plt.xlabel("")
sns.plt.show()
@fomightez
Copy link

fomightez commented Apr 13, 2018

While there are still some deprecation warnings showing, I got this to work in 2018 in Python 3.6 Jupyter notebook by removing last line, and putting %matplotlib inline at the start of the cell and changing ones above the removed line to below:

l = ax.legend(handles[0:2], labels[0:2]) # changed based on https://stackoverflow.com/a/42768387/8508004
#sns.ax.ylim([0,60]) #original
ax.set_ylim([0,60]) # adapted from https://stackoverflow.com/a/49049501/8508004 and change to legend
ax.set_ylabel("Total Bill ($)") # based on https://stackoverflow.com/a/46235777/8508004
ax.set_xlabel("") # based on https://stackoverflow.com/a/46235777/8508004

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment