[英]How to set x axis ticklabels in a seaborn plot
I am unable to set x axis ticklabels for a seaborn lineplot
correctly.我无法正确设置lineplot
线图的 x 轴刻度标签。
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({'a':np.random.rand(8),'b':np.random.rand(8)})
sns.set(style="darkgrid")
g = sns.lineplot(data=df)
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])
The years on the x axis are not aligning properly. x 轴上的年份未正确对齐。
Whenever you set the x-ticklabels manually, you should try to first set the corresponding ticks, and then specify the labels.每当您手动设置 x-ticklabels 时,您应该尝试先设置相应的刻度,然后再指定标签。 In your case, therefore you should do在你的情况下,因此你应该做
g = sns.lineplot(data=df)
g.set_xticks(range(len(df))) # <--- set the ticks first
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])
set_xticklabels
is now discouraged:现在不鼓励使用set_xticklabels
:
The use of this method is discouraged because of the dependency on tick positions.由于依赖于刻度位置,不鼓励使用此方法。 In most cases, you'll want to use
set_xticks(positions, labels)
instead.在大多数情况下,您需要使用set_xticks(positions, labels)
来代替。
Now set_xticks
includes a new labels
param to set ticks and labels simultaneously:现在set_xticks
包括一个新的labels
参数来同时设置刻度和标签:
ax = sns.lineplot(data=df)
ax.set_xticks(range(len(df)), labels=range(2011, 2019))
# ^^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.