如何传递 Seaborn 位置和关键字参数
- 2025-02-25 09:07:00
- admin 原创
- 32
问题描述:
我想绘制一个 seaborn regplot
。我的代码:
x=data['Healthy life expectancy']
y=data['max_dead']
sns.regplot(x,y)
plt.show()
但是这会给我未来警告错误。如何修复此警告?
FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid
positional argument will be 'data', and passing other arguments without an explicit keyword will
result in an error or misinterpretation.
解决方案 1:
Seaborn >= 0.12
有了
seaborn 0.12
,FutureWarning
来自seaborn 0.11
现在变成了TypeError
。只能
data
指定为 seaborn 图的第一个位置参数。所有其他参数必须使用关键字(例如x=
和y=
)。这适用于所有seaborn
绘图函数。sns.*plot(data=penguins, x="bill_length_mm", y="bill_depth_mm")
或者sns.*plot(penguins, x="bill_length_mm", y="bill_depth_mm")
sns.*plot(data=penguins.bill_length_mm)
或者sns.*plot(penguins.bill_length_mm)
请参阅seaborn 绘图函数概述
使用 seaborn 时不正确使用位置参数和关键字参数可能会导致一些错误:
TypeError: *plot() takes from 0 to 1 positional arguments but 3 were given
当没有传递关键字时发生。sns.*plot(penguins, "bill_length_mm", "bill_depth_mm")
TypeError: *plot() got multiple values for argument 'data'
在传递data=
后用作位置参数
时发生。x
`y`sns.*plot("bill_length_mm", "bill_depth_mm", data=penguins)
TypeError: *plot() takes from 0 to 1 positional arguments but 2 positional arguments (and 1 keyword-only argument) were given
`x当为and传递位置参数
y,后跟除 之外的关键字参数时发生
data`sns.*plot(penguins.bill_length_mm, penguins.bill_depth_mm, kind="reg")
请参阅TypeError:method() 需要 1 个位置参数,但一般
python
解释给出了 2 个。位置参数与关键字参数
Seaborn 0.11
从技术上讲,这是一个警告,而不是错误,暂时可以忽略,如该答案的底部所示。
我建议按照警告所述进行操作,为指定
x
和y
参数seaborn.regplot
,或使用此警告的任何其他seaborn 绘图函数。sns.regplot(x=x, y=y)
,其中x
和y
是的参数regplot
,您要向其传递x
和y
变量。从 0.12 版本开始,传递任何位置参数(除
data
)都将导致error
或misinterpretation
。对于那些关心向后兼容性的人,请编写一个脚本来修复现有代码,或者不要更新到 0.12(一旦可用)。
x
和y
用作数据变量名,因为这是 OP 中使用的名称。数据可以分配给任何变量名(例如a
和b
)。这也适用于,它可以通过仅需要或 的
FutureWarning: Pass the following variable as a keyword arg: x
图来生成,例如:x
`y`sns.countplot(penguins['sex'])
,但应该是sns.countplot(x=penguins['sex'])
或sns.countplot(y=penguins['sex'])
import seaborn as sns
import pandas as pd
penguins = sns.load_dataset('penguins')
x = penguins.culmen_depth_mm # or bill_depth_mm
y = penguins.culmen_length_mm # or bill_length_mm
# plot without specifying the x, y parameters
sns.regplot(x, y)
# plot with specifying the x, y parameters
sns.regplot(x=x, y=y)
# or use
sns.regplot(data=penguins, x='bill_depth_mm', y='bill_length_mm')
忽略警告
我不建议使用此选项。
一旦 seaborn v0.12 可用,此选项将不再可行。
从 0.12 版本开始,唯一有效的位置参数是
data
,传递没有明确关键字的其他参数将导致错误或误解。
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
# plot without specifying the x, y parameters
sns.regplot(x, y)