【问题标题】:Plotting columns of DataFrame as scatterplots against same y-column将 DataFrame 的列绘制为针对相同 y 列的散点图
【发布时间】:2017-05-03 02:07:35
【问题描述】:

我有一个 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 的列。

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:

    我不知道在 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 数据列的列名。

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

    【讨论】:

    • 啊,使用df.plot 来获得它固有的给你的东西。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 2018-07-21
    • 2017-09-13
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多