Building DataFrame columns as scatter plots against the same column

I have a DataFrame dfrepresenting CSV data found in Advertising.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

I would like to build each column in my DataFrame in the Sales column in my own scatter chart, i.e. enter image description here

I managed to do this with

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')

My question is , is there a construct inside df.plotthat could facilitate this task in Matplotlib and the loop, like me?


motivation

I know in R, to achieve a similar result, I would do something like

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 )
      }
    )

which admittedly seems a little cleaner than my Pandas IMO approach, and made me ask if there is an easier way to construct DataFrames columns this way.

+4
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 . x y df.plot().

:

Three graphs

+3

Source: https://habr.com/ru/post/1676207/


All Articles