pandas.plot参数c vs s

Cod*_*ope 2 python matplotlib pandas

我从python的机器学习书中获得以下代码:

copy_set.plot(kind = "scatter" , x = "longitude" , 
              y = "latitude" , alpha = 0.4 , 
              s = copy_set[ "population" ], 
              label = "population" , figsize=(10,7), 
              c = "median_house_value" , cmap = plt.get_cmap ( "jet" ) ) 
Run Code Online (Sandbox Code Playgroud)

median_house_valuepopulationcopy_set数据框中的两列。我不明白为什么s我必须使用copy_set['population']参数c,但是对于参数,只能使用列名median_house_value。当我尝试仅将列名用作parameter时s,收到一条错误消息:

TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 5

很好的问题。df.plot是matplotlib几个绘图功能的包装。对于kind="scatter"matplotlib的scatter函数将被调用。df.plot()首先将要转换的大多数参数转换为Series您从各自名称的数据框的列中获取的数据。

例如

df.plot(x="lon", y="lat")
Run Code Online (Sandbox Code Playgroud)

将被转换为

ax.scatter(x=df["lon"].values, y=df["lat"].values)
Run Code Online (Sandbox Code Playgroud)

剩余的参数传递给分散,因此

df.plot(x="lon", y="lat", some_argument_pandas_doesnt_know=True)
Run Code Online (Sandbox Code Playgroud)

将导致

ax.scatter(x=df["lon"].values, y=df["lat"].values, some_argument_pandas_doesnt_know=True)
Run Code Online (Sandbox Code Playgroud)

因此,尽管大熊猫皈依个参数xyc,它不会这么做的ss因此,将其简单地传递给ax.scatter,但是matplotlib函数不知道某些字符串的"population"含义。
对于传递给matplotlib函数的参数,需要坚持使用matplotlib的签名,并且在s直接提供数据的情况下。

但是请注意,matplotlib的分散本身也允许使用字符串作为其参数。但是,这需要告诉它应从哪个数据集中获取它们。这是通过data参数完成的。因此,以下工作正常,并且等同于问题中的pandas调用的matplotlib:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np; np.random.seed(42)

df = pd.DataFrame(np.random.rand(20,2), columns=["lon", "lat"])
df["pop"] = np.random.randint(5,300,size=20)
df["med"] = np.random.rand(20)*1e5

fig, ax = plt.subplots(figsize=(10,7))
sc = ax.scatter(x = "lon", y = "lat", alpha = 0.4, 
                s = "pop", label = "population" , 
                c = "med" , cmap = "jet", data=df)
fig.colorbar(sc, label="med")
ax.set(xlabel="longitude", ylabel="latitude")

plt.show()
Run Code Online (Sandbox Code Playgroud)

最后,您现在可能会问,是否data同样无法通过参数通过pandas包装器将数据提供给matplotlib 。不幸的是没有,因为熊猫data在内部使用了作为参数,因此它不会被传递。因此,您有两个选择:

  1. 在问题中使用熊猫,并通过s参数而不是列名提供数据本身。
  2. 如下所示,使用matplotlib并为所有参数使用列名。(或者使用数据本身,这是您在查看matplotlib代码时最常看到的。)

  • 我认为坏消息是:如果不查看源代码,您将无法找到答案。但一般来说,pandas 使用 `x` 和 `y` 并接受它们的标签。在 scatter 的情况下,它也是 `c`。 (2认同)