【问题标题】:Plotting scatterplots from a dataframe on a grid with matplotlib [duplicate]使用matplotlib在网格上绘制数据框的散点图[重复]
【发布时间】:2019-10-17 22:10:47
【问题描述】:

有没有办法用来自数据框的所有列的散点图制作网格,其中 Y 是数据框的列之一?

我可以在 matplotlibseaborn 上执行 for 循环(请参阅下面的代码),但我不能让它们显示在网格上。

我希望它们显示在网格可视化中,以便于比较它们。

这是我能做的:

for col in boston_df:
    plt.scatter(boston_df[col], boston_df["MEDV"], c="red", label=col)
    plt.ylabel("medv")
    plt.legend()
    plt.show()

for col in boston_df:
    sns.regplot(x=boston_df[col], y=boston_df["MEDV"])
    plt.show()

现在,如果我尝试创建一个子图并像这样在我的循环中使用 ax.scatter()

fig, ax = plt.subplots(3, 5,figsize=(16,6))
for col in boston_df:
    ax.scatter(boston_df[col], boston_df["MEDV"], c="red", label=col)
    plt.ylabel("medv")
    plt.legend()
    plt.show()

它给了我错误AttributeError: 'numpy.ndarray' object has no attribute 'scatter'

找到一些像这样简单的解决方案会很漂亮:

df.hist(figsize=(18,10), density=True, label=df.columns)
plt.show()

【问题讨论】:

    标签: python matplotlib seaborn scatter-plot


    【解决方案1】:

    考虑使用 pandas DataFrame.plot 和 seaborn 的 regplotax 参数:

    fig, ax = plt.subplots(1, 5, figsize=(16,6))
    
    for i,col in enumerate(boston_df.columns[1:]):
         #boston_df.plot(kind='scatter', x=col, y='MEDV', ax=ax[i])
         sns.regplot(x=boston_df[col], y=boston_df["MEDV"], ax=ax[i])
    
    fig.suptitle('My Scatter Plots')
    fig.tight_layout()
    fig.subplots_adjust(top=0.95)      # TO ACCOMMODATE TITLE
    
    plt.show()
    

    用随机数据演示:

    import numpy as np
    import pandas as pd
    
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    ### DATA BUILD
    np.random.seed(6012019)
    random_df = pd.DataFrame(np.random.randn(50,6), 
                             columns = ['MEDV', 'COL1', 'COL2', 'COL3', 'COL4', 'COL5'])
    
    ### PLOT BUILD
    fig, ax = plt.subplots(1, 5, figsize=(16,6))
    
    for i,col in enumerate(random_df.columns[1:]):
         #random_df.plot(kind='scatter', x=col, y='MEDV', ax=ax[i])
         sns.regplot(x=random_df[col], y=random_df["MEDV"], ax=ax[i])
    
    fig.suptitle('My Scatter Plots')
    fig.tight_layout()
    fig.subplots_adjust(top=0.95)
    
    plt.show()
    plt.clf()
    plt.close()
    

    对于跨多列的多行,将分配调整为 ax,这是一个使用索引的 numpy 数组:ax[row_idx, col_idx]

    import numpy as np
    import pandas as pd
    
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    ### DATA BUILD
    np.random.seed(6012019)
    random_df = pd.DataFrame(np.random.randn(50,14), 
                             columns = ['MEDV', 'COL1', 'COL2', 'COL3', 'COL4', 
                                        'COL5', 'COL6', 'COL7', 'COL8', 'COl9', 
                                        'COL10', 'COL11', 'COL12', 'COL13'])
    
    ### PLOT BUILD
    fig, ax = plt.subplots(2, 7, figsize=(16,6))
    
    for i,col in enumerate(random_df.columns[1:]):
         #random_df.plot(kind='scatter', x=col, y='MEDV', ax=ax[i])
         if i <= 6:
            sns.regplot(x=random_df[col], y=random_df["MEDV"], ax=ax[0,i])
         else:
            sns.regplot(x=random_df[col], y=random_df["MEDV"], ax=ax[1,i-7])     
    
    ax[1,6].axis('off')                  # HIDES AXES ON LAST ROW AND COL
    
    fig.suptitle('My Scatter Plots')
    fig.tight_layout()
    fig.subplots_adjust(top=0.95)
    
    plt.show()
    plt.clf()
    plt.close()
    

    【讨论】:

    • 这段代码只为我提供了前 5 列数据的散点图(跳过作为目标的第一列),但我有 13 列。 (它也会抛出错误IndexError: index 5 is out of bounds for axis 0 with size 5,尽管它仍然显示绘图。)如果我尝试将fig, ax = plt.subplots(2, 5, figsize=(16,6)) 从 1 行更改为 2 行,那么我会收到错误 AttributeError: 'numpy.ndarray' object has no attribute 'scatter'
    • 您需要调整subplots 以容纳所有列。因此IndexError。此解决方案假定 MEDV 是第一列,并且您不想在其自身上运行散点图。只需将 plt.subplots() 中 5 的 ncol 调整为 13。对于多行,请参阅扩展答案,其中必须调整对 ax 的分配。
    • 它适用于 2, 7 - 我不能让它适用于 3, 5... 我敢肯定只是这样,作为一个初学者,我不完全理解发生了什么使用代码,因此无法自己进行调整。我会继续尝试,如果我想要 3 行,我可能必须添加一个 elif?无论如何,上面 2、7 的解决方案确实有效!
    • 真的吗?没有什么可以阻止它在任何一个版本中工作。我从未在 Python 2 中工作过!也许您的库或环境是混合的。将来,请发布实际数据样本以供我们帮助。编码愉快!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2021-10-14
    • 2015-10-01
    • 2022-01-02
    • 2023-03-13
    • 1970-01-01
    • 2018-12-23
    相关资源
    最近更新 更多