python - 将 DataFrame 的列绘制为针对相同 y 列的散点图

标签 python pandas matplotlib plot

我有一个 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 列进行对比,即 enter image description here

我设法做到了

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 数据列的列名。

使用您提供的数据子集,这将产生:

Three graphs

关于python - 将 DataFrame 的列绘制为针对相同 y 列的散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43749920/

相关文章:

python - 如何使用一个模型中间层的输出作为另一个模型的输入?

pandas - 使用dask从Hive读取数据

python - 从 Tkinter gui 更新 matplotlib imshow

python - 如何使用 Matplotlib (Python) 在 SymPy 中制作动画

python - Matplotlib:带有变量的图例条目

python - 如何在列表循环中找到特定位置的最小值和最大值?

python - 数据帧 : add column with the size of a group

python - 如果内容是阿拉伯语,Scrapy 检索 json 中的符号

python - Pandas 数据帧 : how to turn one row into separate rows based on labelled column value

python - Pandas:对数据框中的行进行排序