alvarobartt
alvarobartt

Reputation: 463

How to display axis tick labels over plotted values using matplotlib and seaborn?

I am using matplotlib and seaborn in order to scatter plot some data contained in two arrays, x and y, (2-dimensional plot). The issue here is when it comes to displaying both axis labels over the data, because plotted data overlaps the values so the are unseen.

I have tried different possibilities such as resetting the labels after the plot is done and setting them later, or using annotation marks. Anyways any of those options worked for me...

The piece of code I am using to generate this scatter plot is:

sns.set_style("whitegrid")

ax = sns.scatterplot(x=x, y=y, s=125)

ax.set_xlim(-20, 20)
ax.set_ylim(-20, 20)

ax.spines['left'].set_position('zero')
ax.spines['left'].set_color('black')

ax.spines['right'].set_color('none')
ax.yaxis.tick_left()

ax.spines['bottom'].set_position('zero')
ax.spines['bottom'].set_color('black')

ax.spines['top'].set_color('none')
ax.xaxis.tick_bottom()

values = ax.get_xticks()
ax.set_xticklabels(["{0:.0%}".format(x/100) for x in values])

values = ax.get_yticks()
ax.set_yticklabels(["{0:.0%}".format(y/100) for y in values])

ax.tick_params(axis='both', which='major', labelsize=15)

ax.grid(True)

The generated plot is as follows: generated scatter plot

But the desired output should be something like this: desired scatter plot

Thank you in advance for any advice or help!

Upvotes: 1

Views: 690

Answers (1)

Sheldore
Sheldore

Reputation: 39042

You need two things: zorder and a bold weight for the ticklabels. The zorder of scatter points needs to be lower than that of the tick labels so that the latter appear on the top. 'fontweight': 'bold' is to have boldfaced tick labels.

The axis appears shifted off the 0 but that is because you did not provide any data. So I have to choose some random data

# import commands here

x = np.random.randint(-100, 100, 10000)
y = np.random.randint(-100, 100, 10000)
ax = sns.scatterplot(x=x, y=y, s=125, zorder=-1)

# Rest of the code

values = ax.get_xticks()
ax.set_xticklabels(["{0:.0%}".format(x/100) for x in values], fontdict={'fontweight': 'bold'})

values = ax.get_yticks()
ax.set_yticklabels(["{0:.0%}".format(y/100) for y in values], fontdict={'fontweight': 'bold'})

ax.tick_params(axis='both', which='major', labelsize=15, zorder=1)
ax.grid(True)

enter image description here

Upvotes: 3

Related Questions