Seaborn在x轴刻度上给出了错误的值?

时间:2019-05-03 15:09:33

标签: python matplotlib seaborn

在Matplotlib下面的代码中,正确的范围是5.0到10.0,为什么Seaborn与众不同?

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from matplotlib import ticker

sns.set()

fig, (ax1, ax2) = plt.subplots(2)

x = np.linspace(5, 10)
y = x ** 2

sns.barplot(x, y, ax=ax1)
ax1.xaxis.set_major_locator(ticker.MultipleLocator(5))
ax1.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))

ax2.bar(x, y, width = 0.1)
ax2.xaxis.set_major_locator(ticker.MultipleLocator(5))
ax2.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))

plt.show()

enter image description here

1 个答案:

答案 0 :(得分:3)

Seaborn的barplot是分类情节。这意味着它将条形图放置在连续的整数位置(0,1,... N-1)。因此,如果您有N条,则轴的范围为-0.5至N-0.5。

没有办法告诉Seaborn将条形图放置在不同的位置。但是您当然可以伪造标签以使其看起来像这样。例如。用x中的值标记第5个小节:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from matplotlib import ticker

sns.set()

fig, ax = plt.subplots()

x = np.linspace(5, 10)
y = x ** 2

sns.barplot(x, y, ax=ax)
ax.xaxis.set_major_locator(ticker.FixedLocator(np.arange(0, len(x), 5)))
ax.xaxis.set_major_formatter(ticker.FixedFormatter(x[::5]))
ax.tick_params(axis="x", rotation=90)

plt.tight_layout()
plt.show()

enter image description here

相反,可以使用matplotlib绘制分类图。为此,需要绘制字符串。

ax.bar(x.astype(str), y)
ax.xaxis.set_major_locator(ticker.FixedLocator(np.arange(0, len(x), 5)))
ax.xaxis.set_major_formatter(ticker.FixedFormatter(x[::5]))
ax.tick_params(axis="x", rotation=90)

enter image description here

如果要使用数字条形图,即每个条形图在x的轴位置处的图,则需要使用matplotlib。这也是问题中显示的默认情况,条形图的范围在5到10之间。在这种情况下,应确保条形图的宽度小于连续x个位置之间的差。

ax.bar(x, y, width=np.diff(x).mean()*0.8)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))
ax.tick_params(axis="x", rotation=90)

enter image description here