文章目录
- 1. matplotlib实现
- 1.1 效果
- 1.2 代码
- 2. seaborn实现
- 2.1 效果
- 2.2 代码
左图是matplotlib的结果,右图是seaborn的结果
1. matplotlib实现
1.1 效果
效果:(二维正态分布的散点图+每个轴的直方图)
1.2 代码
import numpy as np
import matplotlib.pyplot as plt
# <https://blog.csdn.net/Castlehe/article/details/127555925>
# 6. 正态(normal)/高斯(gaussian)分布distribution 3σ原则
# μ-σ~μ+σ=0.6826,(0-1~0+1 点落在-1~1之间的概率是68.26%)
# μ-2σ~μ+2σ=0.9544 (点落在-2~2之间的概率是95.44%)
# μ-3σ~μ+3σ=0.9974 (点落在-3~3之间的概率是99.74%)
x = np.random.randn(2000)
y = np.random.randn(2000)
def scatter_hist(x, y, ax, ax_histx, ax_histy):
# no labels
ax_histx.tick_params(axis="x", labelbottom=False)
ax_histy.tick_params(axis="y", labelleft=False)
# (0,0) center
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# x, y scale equal
ax.set_aspect('equal', adjustable='box')
# scatter plot
ax.scatter(x, y)
# now determine nice limits by hand:
binwidth = 0.25
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
lim = (int(xymax/binwidth) + 1) * binwidth
# hist plot
bins = np.arange(-lim, lim + binwidth, binwidth)
ax_histx.hist(x, bins=bins, color="tab:cyan")
ax_histy.hist(y, bins=bins, orientation='horizontal', color="y")
fig = plt.figure(figsize=(6, 6))
# fig.add_gridspec
gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4),
left=0.1, right=0.9, bottom=0.1, top=0.9,
wspace=0.05, hspace=0.05)
ax = fig.add_subplot(gs[1, 0])
ax_histx = fig.add_subplot(gs[0, 0], sharex=ax)
ax_histy = fig.add_subplot(gs[1, 1], sharey=ax)
scatter_hist(x, y, ax, ax_histx, ax_histy)
plt.show()
参考:Scatter plot with histograms
2. seaborn实现
2.1 效果
2.2 代码
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randn(2000)
y = np.random.randn(2000)
sns.jointplot(x=x, y=y)
plt.show()
就很简单。。。
参考:
- Distribution visualization in other settings
- matplotlib: plotting histogram plot just above scatter plot