i'm trying to make a 2x1 subplot figure in seaborn using:
data = pandas.DataFrame({"x": [1, 2, 4],
"y": [10,20,40],
"s": [0.01,0.1,1.0]})
plt.figure()
plt.subplot(2, 1, 1)
sns.pointplot(x="x", y="y", data=data)
plt.errorbar(np.arange(len(data["x"])), data["y"], yerr=data["s"])
plt.subplot(2, 1, 2)
sns.factorplot(x="x", y="y", data=data)
plt.show()
it produces two separate figures instead of a single figure with two subplots. why does it do this and how can seaborn be called multiple times for separate subplots?
i tried looking at the post referenced below but i cannot see how the subplots can be added even if factorplot
is called first. can someone show an example of this? it would be helpful. my attempt:
data = pandas.DataFrame({"x": [1, 2, 4],
"y": [10,20,40],
"s": [0.01,0.1,1.0]})
fig = plt.figure()
sns.pointplot(x="x", y="y", data=data)
ax = sns.factorplot(x="x", y="y", data=data)
fig.add_subplot(212, axes=ax)
plt.errorbar(np.arange(len(data["x"])), data["y"], yerr=data["s"])
plt.show()
The issue is that
factorplot
creates a newFacetGrid
instance (which in turn creates its own figure), on which it will apply a plotting function (pointplot by default). So if all you want is thepointplot
, it would make sense to just usepointplot
, and notfactorplot
.The following is a bit of a hack, if you really want to, for whatever reason, tell
factorplot
whichAxes
to perform its plotting on. As @mwaskom points out in comments, this is not a supported behaviour, so while it might work now, it may not in the future.You can tell
factorplot
to plot on a givenAxes
using theax
kwarg, which gets passed on down tomatplotlib
, so the linked answer does sort of answer your query. However, it will still create the second figure because of thefactorplot
call, but that figure will just be empty. A workaround here it to close that extra figure before callingplt.show()
For example: