具有散点图及其直方图的示例代码
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)我想要做的是创建这个图表,直方图连接到它们尊重的轴上,就像这个例子一样

我熟悉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)

但我不知道如何将直方图连接到y轴和x轴,最重要的是,如何改变图表的大小(即使散点图更大,直方图更小)。
发布于 2016-09-28 01:59:14
Seaborn是快速绘制统计图的好方法。但是,如果希望避免另一个依赖,可以使用subplot2grid放置子图,并使用关键字sharex和sharey来确保轴是同步的。
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')

在询问如何绘制某些内容之前,您应该始终查看matplotlib gallery,它很可能会为您节省几次击键操作--我的意思是,您不必询问。实际上在画廊里有两个这样的地块。不幸的是,代码很旧,并且没有利用subplot2grid,the first one使用矩形,而second one使用axes_grid,这是一个有点奇怪的野兽。这就是我发布这个答案的原因。
发布于 2016-09-28 01:17:55
我认为单独使用matplotlib很难做到这一点,但您可以使用具有jointplot功能的seaborn。
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);

https://stackoverflow.com/questions/39730184
复制相似问题