2016-09-27 108 views
2

具有用於散點圖與他們的直方圖沿示例代碼的Python - 堆疊兩個直方圖與散點圖

x = np.random.rand(5000,1) 
y = np.random.rand(5000,1) 



fig = plt.figure(figsize=(7,7)) 
ax = fig.add_subplot(111) 
ax.scatter(x, y, facecolors='none') 
ax.set_xlim(0,1) 
ax.set_ylim(0,1) 



fig1 = plt.figure(figsize=(7,7)) 
ax1 = fig1.add_subplot(111) 
ax1.hist(x, bins=25, fill = None, facecolor='none', 
     edgecolor='black', linewidth = 1) 



fig2 = plt.figure(figsize=(7,7)) 
ax2 = fig2.add_subplot(111) 
ax2.hist(y, bins=25 , fill = None, facecolor='none', 
     edgecolor='black', linewidth = 1) 

什麼我想要做的是創造該圖與連接到他們的尊重直方圖軸幾乎像這個例子

enter image description here

我熟悉的堆疊和合並x軸

f, (ax1, ax2, ax3) = plt.subplots(3) 
ax1.scatter(x, y) 
ax2.hist(x, bins=25, fill = None, facecolor='none', 
     edgecolor='black', linewidth = 1) 
ax3.hist(y, bins=25 , fill = None, facecolor='none', 
     edgecolor='black', linewidth = 1) 

f.subplots_adjust(hspace=0) 
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) 

enter image description here

但我不知道如何將直方圖連接到Y軸和X軸類似的圖片我張貼以上,並且最重要的是,如何改變圖形的大小(即做散點圖較大,直方圖比較小)

回答

1

我認爲這很難單獨使用matplotlib,但可以使用seaborn,它具有jointplot函數。

import numpy as np 
import pandas as pd 
import seaborn as sns 
sns.set(color_codes=True) 

x = np.random.rand(1000,1) 
y = np.random.rand(1000,1) 
data = np.column_stack((x,y)) 
df = pd.DataFrame(data, columns=["x", "y"]) 

sns.jointplot(x="x", y="y", data=df); 

enter image description here

2

Seaborn是去快速統計圖的方式。但是,如果您想避免依賴關係,您可以使用subplot2grid來放置子圖和關鍵字sharexsharey以確保軸同步。

import numpy as np 
import matplotlib.pyplot as plt 

x = np.random.randn(100) 
y = np.random.randn(100) 

scatter_axes = plt.subplot2grid((3, 3), (1, 0), rowspan=2, colspan=2) 
x_hist_axes = plt.subplot2grid((3, 3), (0, 0), colspan=2, 
           sharex=scatter_axes) 
y_hist_axes = plt.subplot2grid((3, 3), (1, 2), rowspan=2, 
           sharey=scatter_axes) 

scatter_axes.plot(x, y, '.') 
x_hist_axes.hist(x) 
y_hist_axes.hist(y, orientation='horizontal') 

plot

你應該總是看matplotlib gallery詢問如何繪製的東西之前,有機會,它會爲你節省幾個按鍵 - 我的意思是,你不必問。畫廊裏實際上有兩個這樣的情節。不幸的是,代碼是舊的,並沒有利用subplot2grid,the first one使用矩形和second one使用axes_grid,這是一個有點怪異的野獸。這就是我發佈這個答案的原因。