[英]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). 我使用matplotlib和seaborn来散布两个数组x和y(二维绘图)中包含的某些数据。 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: 生成的图如下:
But the desired output should be something like this: 但是所需的输出应该是这样的:
Thank you in advance for any advice or help! 预先感谢您的任何建议或帮助!
You need two things: zorder
and a bold
weight for the ticklabels. 您需要两件事:
zorder
和bold
。 The zorder
of scatter points needs to be lower than that of the tick labels so that the latter appear on the top. 散点的
zorder
必须低于对勾标签的zorder
,以便后者显示在顶部。 'fontweight': 'bold'
is to have boldfaced tick labels. 'fontweight': 'bold'
是带有粗体的勾号标签。
The axis appears shifted off the 0 but that is because you did not provide any data. 轴显示偏离0,但这是因为您未提供任何数据。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.