iro*_*man 5 python plot numpy matplotlib
有一个散点图的示例代码及其直方图
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)
Run Code Online (Sandbox Code Playgroud)
我想要做的是创建这个图形,直方图附加到他们尊重的轴上,就像这个例子一样
我熟悉堆叠和合并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)
Run Code Online (Sandbox Code Playgroud)
但我不知道如何将直方图附加到y轴和x轴,就像我上面发布的图片一样,最重要的是,如何改变图形的大小(即使散点图更大,直方图更小)相比下)
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')
Run Code Online (Sandbox Code Playgroud)
在询问如何绘制某些东西之前,你应该总是看看matplotlib画廊,很可能它会为你节省一些按键 - 我的意思是你不必问.画廊中实际上有两个这样的情节.不幸的是,代码是旧的,没有利用subplot2grid
,第一个使用矩形,第二个使用axes_grid
,这是一个有点奇怪的野兽.这就是我发布这个答案的原因.
我认为单独使用它很难做到这一点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);
Run Code Online (Sandbox Code Playgroud)