我想使用 sns barplot 从 pd df 进行绘图。一切正常:
相关代码:
result = df.groupby(['Code departement']).size().sort_values(ascending=False)
x=result.index
y=result.values
plot=sns.barplot(x, y)
plot.set(xlabel='Code departement', ylabel='Nombre de transactions')
sns.barplot(x, y, data=df).set_title('title')
但是正如您在图 1 中看到的,有太多条形图,所以我只想要 10 个最高的条形图,当我对 x 和 y 进行切片时:
x=result[:10].index
y=result[:10].values
plot=sns.barplot(x, y)
我通过打印 x 和 y (切片)进行检查,它们的顺序正确,我不知道我缺少什么,谢谢您的帮助
最佳答案
您没有说明您正在使用的版本,但可能不是最新的。 Seaborn 和 matplotlib 在每个新版本中都得到了相当多的改进。
使用seaborn 0.11.1,您会收到警告,因为 x
和 y
首选通过关键字传递,即 sns.barplot(x =x,y=y)
。该警告试图避免与 data=
关键字混淆。除此之外,数字 x 值将按数字排序。
可以通过order=
关键字控制顺序。在本例中,sns.barplot(x=x, y=y, order=x)
。要仅显示 10 个最高值,您可以传递 sns.barplot(x=x, y=y, order=x[:10])
。
另请注意,您创建了两次条形图(只是为了更改标题?),这可能会非常令人困惑。由于 sns.barplot
返回 ax
(绘制绘图的子图),通常的方法是 ax = sns.barplot(...)
,然后是ax.set_title(...)
。 (名称ax
是首选,以便更容易理解如何在新代码中使用matplotlib和seaborn示例代码。)
以下示例代码已经使用seaborn 0.11.1进行了测试:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
print(sns.__version__)
df = pd.DataFrame({'Code departement': np.random.randint(1, 51, 1000)})
result = df.groupby(['Code departement']).size().sort_values(ascending=False)
x = result.index
y = result.values
ax = sns.barplot(x, y, order=x[:10])
ax.set(xlabel='Code departement', ylabel='Nombre de transactions')
ax.set_title('title')
plt.show()
关于pandas - Sns barplot 不对切片值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67723351/