首页 > 解决方案 > Seaborn 图未显示在轴上

问题描述

我有一个看起来像这样的熊猫数据框:

counts = pd.DataFrame({'Pair A': {8: 4, 9: 1, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0},
 'Pair B': {8: 4, 9: 2, 10: 1, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0},
 'Pair C': {8: 3, 9: 2, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1},
 'Pair D': {8: 2, 9: 1, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0}})

我只是使用以下代码使用 DataFrame 的一部分创建一个简单的绘图:

plt.figure()
sns.set_palette("pastel")
temp = pd.DataFrame(counts).drop([0,1,2,3,4,5,6], axis='index')
temp.index = temp.index + 1

temp.plot()
sns.set_style('ticks')
plt.ylabel('title')
plt.xlabel('xlabel')
plt.title('title')
plt.xticks(range(len(temp.index)), temp.index, rotation=45)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
sns.despine(offset=10, trim=True)
plt.xticks(rotation=45)

但它会产生如下所示的图像:

在此处输入图像描述

如何将绘图集中在 x 轴上?

标签: pythonpandasmatplotlibseaborn

解决方案


当您调用plt.xticks并提供 2 个位置参数时,第一个参数变为locs标签将出现的 x 值,第二个参数变为labels刻度标签值。因此,plt.xticks(range(len(temp.index)), temp.index, rotation=45)您在位置 0、1、2、3.... 处绘制 x 刻度标签,而您的数据在不同的范围内(8、9、10....)。

因此,如果您想自定义标签,您可以更改label部分,例如plt.xticks(temp.index, ['x%s'% v for v in temp.index], rotation=45).


推荐阅读