2016-09-27 128 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,这是一个有点怪异的野兽。这就是我发布这个答案的原因。