我有一个 DataFrame df
表示在 Advertising.csv 中找到的 CSV 数据.
>>> df = pd.read_csv('Advertising.csv', index_col=0)
>>> df.head(5)
TV Radio Newspaper Sales
1 230.1 37.8 69.2 22.1
2 44.5 39.3 45.1 10.4
3 17.2 45.9 69.3 9.3
4 151.5 41.3 58.5 18.5
5 180.8 10.8 58.4 12.9
我想将我的 DataFrame 中的每一列与各自散点图中的 Sales 列进行对比,即
我设法做到了
import matplotlib.pyplot as plt
f, ax_l = plt.subplots(1, 3, figsize=(14, 4))
for e, col_name in enumerate(df.loc[:, :'Newspaper'].columns):
ax_l[e].scatter(df[col_name], df.Sales, alpha=0.5, color='r')
ax_l[e].set_xlabel(col_name)
ax_l[e].set_ylabel('Sales')
我的问题是,df.plot
中是否有一个结构可以让这个任务比像我那样进入 Matplotlib 和循环更容易?
动机
我知道在 R 中,为了获得类似的结果,我会做类似的事情
savePar <- par(mfrow=c(1,3))
col <- adjustcolor( 'red', 0.5 )
with( Advertising,
{ plot( TV , Sales, pch=19, col=col )
plot( Radio , Sales, pch=19, col=col )
plot( Newspaper, Sales, pch=19, col=col )
}
)
诚然,这似乎比我的 Pandas 方法 IMO 更清晰,并且让我质疑是否有更直接的方法以这种方式绘制 DataFrame 的列。
最佳答案
我不知道有什么方法可以在 df.plot()
方法中完全完成,但是有一种更简单的方法来绘制图形:
import pandas as pd
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(14,4))
for xcol, ax in zip(['TV', 'Radio', 'Newspaper'], axes):
df.plot(kind='scatter', x=xcol, y='Sales', ax=ax, alpha=0.5, color='r')
此处的方法是使用内置的 zip
函数将列名称与各个 axis
对象配对。您可以将 axis
对象直接传递给 df.plot
以告诉它使用哪个 axis
。您还可以在调用 df.plot()
时指定 x 和 y 数据列的列名。
使用您提供的数据子集,这将产生:
关于python - 将 DataFrame 的列绘制为针对相同 y 列的散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43749920/