KRS-fun
KRS-fun

Reputation: 724

How to despine a matplotlib and seaborn axes

I'm having difficulty turning the axes on and off in plots, and sizing my axes appropriately. I've followed several threads and my method is:

f1=plt.figure(1,(3,3))
ax=Subplot(f1,111)
f1.add_subplot(ax)
ax.scatter(current,backg,label='Background Height')
ax.plot(current,backg)
ax.scatter(current,peak,color = 'red',label='Peak Spot Height')
ax.plot(current,peak,color='red')
ax.plot(current,meanspot,color='green')
ax.scatter(current,meanspot,color = 'green',label='Mean Spot Height')

ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

But my figures still end up with axes on the top and right, and a strange gap due to the sizing of the axes.enter image description here

Upvotes: 6

Views: 16554

Answers (2)

jmz
jmz

Reputation: 4328

I highly recommend looking at the seaborn library for this sort of manipulation. Removing spines is as easy as sns.despine().

For example, to make a spineless chart with a white background I might write

import pandas as pd
import numpy as np
import seaborn as sns

df2 = pd.Series([np.sqrt(x) for x in range(20)])
sns.set(style="nogrid")
df2.plot()
sns.despine(left=True, bottom=True)

to get

enter image description here

Have a look at the linked documentation for more details. It really does make controlling matplotlib aesthetics dramatically easier than writing all the code out manually.

Upvotes: 8

Tim Ernst
Tim Ernst

Reputation: 397

Can you be more specific what's needed?

You can remove the spine with:

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)

But it sounds like you might be referring to ticks on the spine...

Upvotes: 23

Related Questions