1

I have a data frame has columns x1, x2, x3, x4, x5, x6, my_y. I am making a scatter plot for each xi ~ y like:

%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
my_df.plot(x='x1', y='my_y', kind = 'scatter', marker = 'x', color = 'black', ylim = [0, 10])

I repeated the above code 6 times for x1, x2, x3, x4, x5, x6, to create 6 figures. I am wondering if it possible to make one figure with 6 scatter subplots? Thanks!

1
  • What happens if you do x=['x1', 'x2', 'x3', 'x4', 'x5', 'x6']? Commented Aug 3, 2017 at 19:47

1 Answer 1

2
df = pd.DataFrame(
    np.random.randint(10, size=(5, 7)),
    columns='x1 x2 x3 x4 x5 x6 my_y'.split()
)

df

   x1  x2  x3  x4  x5  x6  my_y
0   0   8   3   2   7   5     8
1   0   6   2   5   8   4     9
2   4   7   1   2   6   4     5
3   8   5   4   0   5   7     4
4   5   6   0   1   8   7     2

Option1
Use the scatter method from the axes elements.

fig, axes = plt.subplots(2, 3, figsize=(6, 4), sharex=True, sharey=True)
y = df.my_y.values
for i in range(6):
    axes[i//3, i%3].scatter(df.iloc[:, i].values, y)

fig.tight_layout()

enter image description here


Option 2
Use pandas.DataFrame.plot

fig, axes = plt.subplots(2, 3, figsize=(6, 4), sharex=True, sharey=True)
y = df.my_y.values
for i in range(6):
    df.plot(x='x' + str(i+1),
            y='my_y',
            kind='scatter',
            marker='x',
            color='black',
            ylim=[0, 10],
            ax=axes[i//3, i%3])

fig.tight_layout()

enter image description here


Response to Comment
Without sharex=True

fig, axes = plt.subplots(2, 3, figsize=(6, 4), sharey=True)
y = df.my_y.values
for i in range(6):
    df.plot(x='x' + str(i+1),
            y='my_y',
            kind='scatter',
            marker='x',
            color='black',
            ylim=[0, 10],
            ax=axes[i//3, i%3])

fig.tight_layout()

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Also wondering when using the option 2, is it possible to have the x-axis label (x1, x2, x3) for the first row subplots?
Turn off my sharex=True

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.