2017-08-03 43 views
1

我有一個數據幀有x1, x2, x3, x4, x5, x6, my_y列。我提出的散點圖每個XI〜ÿ喜歡:Matplotlib:在一個圖中創建多個子圖

%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]) 

我重複上面的代碼6次x1, x2, x3, x4, x5, x6,創造6個的數字。我想知道是否可以用6個分散子圖形成一個數字?謝謝!

+0

會發生什麼,如果你做的'X = [ 'X1', 'X2', 'X3', 'X4',「X5 ','x6']'? –

回答

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 

選項1
使用從axes元件scatter方法。

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


選項2
使用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


迴應評論
沒有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

+0

謝謝!還想知道在使用選項2時,是否可以爲第一行子圖創建x軸標籤(x1,x2,x3)? – Edamame

+1

關掉我的'sharex = True' – piRSquared

相關問題